wp-core-connectors 0.5.2

Core connector registry and sink runtimes for WarpParse
Documentation
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
use super::chunk_reader::ChunkedLineReader;
use crate::sources::event_id::next_event_id;
use async_trait::async_trait;
use base64::Engine;
use base64::engine::general_purpose;
use bytes::Bytes;
use orion_conf::ErrorWith;
use orion_error::conversion::ToStructError;
use std::collections::VecDeque;
use std::path::Path;
use std::sync::Arc;
use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
use tokio::task::JoinHandle;
use wp_connector_api::{
    DataSource, SourceBatch, SourceError, SourceEvent, SourceReason, SourceResult, Tags,
};
use wp_model_core::raw::RawData;

#[derive(Debug, Clone)]
pub enum FileEncoding {
    Text,
    Base64,
    Hex,
}

const DEFAULT_BATCH_LINES: usize = 128;
const DEFAULT_BATCH_BYTES: usize = 400 * 1024;
const DEFAULT_CHUNK_BYTES: usize = 64 * 1024;
const MIN_CHUNK_BYTES: usize = 4 * 1024;
const MAX_CHUNK_BYTES: usize = 128 * 1024;

pub struct FileSource {
    pub(super) key: String,
    pub(super) reader: ChunkedLineReader,
    pub(super) encode: FileEncoding,
    pub(super) base_tags: Tags,
    pub(super) batch_lines: usize,
    pub(super) batch_bytes_budget: usize,
}

impl FileSource {
    pub async fn new(
        key: String,
        path: &str,
        encode: FileEncoding,
        mut tags: Tags,
        range_start: u64,
        range_end: Option<u64>,
    ) -> SourceResult<Self> {
        use std::path::Path;
        let file_path = Path::new(path);
        if !file_path.exists() {
            return Err(SourceReason::core_conf().to_err());
        }
        let mut file = tokio::fs::File::open(file_path)
            .await
            .map_err(|e| SourceReason::disconnect(e.to_string()))
            .with_context(file_path)
            .doing("open source file")?;
        use std::io::SeekFrom;
        use tokio::io::AsyncSeekExt;
        file.seek(SeekFrom::Start(range_start))
            .await
            .map_err(|e| SourceReason::disconnect(e.to_string()))
            .with_context(file_path)
            .doing("seek to posion")?;
        tags.set("access_source", path.to_string());
        let batch_lines = DEFAULT_BATCH_LINES;
        let batch_bytes_budget = DEFAULT_BATCH_BYTES;
        let chunk_bytes = DEFAULT_CHUNK_BYTES.clamp(MIN_CHUNK_BYTES, MAX_CHUNK_BYTES);
        let limit = range_end.map(|end| end.saturating_sub(range_start));
        let reader = ChunkedLineReader::new(file, chunk_bytes, limit);
        Ok(Self {
            key,
            reader,
            encode,
            base_tags: tags,
            batch_lines,
            batch_bytes_budget,
        })
    }

    fn payload_from_line(encode: &FileEncoding, line: Vec<u8>) -> SourceResult<RawData> {
        match encode {
            FileEncoding::Text => Ok(RawData::Bytes(Bytes::from(line))),
            FileEncoding::Base64 => {
                let s = std::str::from_utf8(&line)
                    .map_err(|_| SourceReason::supplier_error("invalid utf8 in base64 text"))?;
                let val = general_purpose::STANDARD
                    .decode(s.trim())
                    .map_err(|_| SourceReason::supplier_error("base64 decode error"))?;
                Ok(RawData::Bytes(Bytes::from(val)))
            }
            FileEncoding::Hex => {
                let s = std::str::from_utf8(&line)
                    .map_err(|_| SourceReason::supplier_error("invalid utf8 in hex text"))?;
                let val = hex::decode(s.trim())
                    .map_err(|_| SourceReason::supplier_error("hex decode error"))?;
                Ok(RawData::Bytes(Bytes::from(val)))
            }
        }
    }

    fn make_event(&self, payload: RawData) -> SourceEvent {
        SourceEvent::new(
            next_event_id(),
            &self.key,
            payload,
            Arc::new(self.base_tags.clone()),
        )
    }

    pub fn identifier(&self) -> String {
        self.key.clone()
    }
}

pub struct MultiFileSource {
    key: String,
    paths: VecDeque<String>,
    encode: FileEncoding,
    tags: Tags,
    instances: usize,
    current_rx: Option<UnboundedReceiver<ParallelSourceMsg>>,
    current_tasks: Vec<JoinHandle<()>>,
    active_tasks: usize,
}

impl MultiFileSource {
    pub fn new(
        key: String,
        paths: Vec<String>,
        encode: FileEncoding,
        tags: Tags,
        instances: usize,
    ) -> Self {
        Self {
            key,
            paths: paths.into(),
            encode,
            tags,
            instances,
            current_rx: None,
            current_tasks: Vec::new(),
            active_tasks: 0,
        }
    }

    async fn launch_next_file(&mut self) -> SourceResult<bool> {
        let Some(path) = self.paths.pop_front() else {
            return Ok(false);
        };
        let ranges = compute_file_ranges(Path::new(&path), self.instances)
            .map_err(|e| SourceReason::disconnect(e.to_string()))
            .with_context(path.as_str())
            .doing("open source file")?;
        let (tx, rx) = unbounded_channel();
        let shard_total = ranges.len();
        let mut tasks = Vec::with_capacity(shard_total);
        for (idx, (start, end)) in ranges.into_iter().enumerate() {
            let shard_key = if shard_total > 1 {
                format!("{}-{}", self.key, idx + 1)
            } else {
                self.key.clone()
            };
            let mut source = FileSource::new(
                shard_key,
                &path,
                self.encode.clone(),
                self.tags.clone(),
                start,
                end,
            )
            .await?;
            let tx = tx.clone();
            tasks.push(tokio::spawn(async move {
                loop {
                    match source.receive().await {
                        Ok(batch) => {
                            if tx.send(ParallelSourceMsg::Batch(batch)).is_err() {
                                break;
                            }
                        }
                        Err(err) if matches!(err.reason(), SourceReason::EOF) => {
                            let _ = tx.send(ParallelSourceMsg::Done);
                            break;
                        }
                        Err(err) => {
                            let _ = tx.send(ParallelSourceMsg::Err(err));
                            break;
                        }
                    }
                }
            }));
        }
        drop(tx);
        self.current_rx = Some(rx);
        self.current_tasks = tasks;
        self.active_tasks = shard_total;
        Ok(true)
    }

    async fn clear_finished_group(&mut self) {
        for task in self.current_tasks.drain(..) {
            let _ = task.await;
        }
        self.current_rx = None;
        self.active_tasks = 0;
    }

    async fn abort_current_group(&mut self) {
        for task in &self.current_tasks {
            task.abort();
        }
        self.clear_finished_group().await;
    }
}

enum ParallelSourceMsg {
    Batch(SourceBatch),
    Done,
    Err(SourceError),
}

#[async_trait]
impl DataSource for FileSource {
    async fn receive(&mut self) -> SourceResult<SourceBatch> {
        let mut batch = SourceBatch::with_capacity(self.batch_lines);
        let mut produced_rows = 0usize;
        let mut used_bytes = 0usize;
        loop {
            match self.reader.next_line().await? {
                Some(line) => {
                    used_bytes = used_bytes.saturating_add(line.len());
                    let payload = Self::payload_from_line(&self.encode, line)?;
                    batch.push(self.make_event(payload));
                    produced_rows += 1;
                    if produced_rows >= self.batch_lines
                        || (self.batch_bytes_budget > 0 && used_bytes >= self.batch_bytes_budget)
                    {
                        break;
                    }
                }
                None => {
                    if batch.is_empty() {
                        return Err(SourceError::from(SourceReason::EOF));
                    }
                    break;
                }
            }
        }
        Ok(batch)
    }

    fn try_receive(&mut self) -> Option<SourceBatch> {
        None
    }

    fn can_try_receive(&mut self) -> bool {
        false
    }

    fn identifier(&self) -> String {
        self.key.clone()
    }
}

#[async_trait]
impl DataSource for MultiFileSource {
    async fn receive(&mut self) -> SourceResult<SourceBatch> {
        loop {
            if self.current_rx.is_none() && !self.launch_next_file().await? {
                return Err(SourceError::from(SourceReason::EOF));
            }

            let msg = match self.current_rx.as_mut() {
                Some(rx) => rx.recv().await,
                None => continue,
            };
            match msg {
                Some(ParallelSourceMsg::Batch(batch)) => return Ok(batch),
                Some(ParallelSourceMsg::Done) => {
                    self.active_tasks = self.active_tasks.saturating_sub(1);
                    if self.active_tasks == 0 {
                        self.clear_finished_group().await;
                    }
                }
                Some(ParallelSourceMsg::Err(err)) => {
                    self.abort_current_group().await;
                    return Err(err);
                }
                None => {
                    if self.active_tasks == 0 {
                        self.clear_finished_group().await;
                        continue;
                    }
                    self.abort_current_group().await;
                    return Err(SourceReason::disconnect(
                        "file source worker channel closed unexpectedly".to_string(),
                    ));
                }
            }
        }
    }

    fn try_receive(&mut self) -> Option<SourceBatch> {
        None
    }

    fn can_try_receive(&mut self) -> bool {
        false
    }

    fn identifier(&self) -> String {
        self.key.clone()
    }

    async fn close(&mut self) -> SourceResult<()> {
        self.abort_current_group().await;
        Ok(())
    }
}

// -- BinaryFileSource --------------------------------------------------------

/// Whole-file binary source. Reads an entire file as a single `RawData::Bytes`
/// payload, then signals EOF. Suitable for Arrow IPC / framed formats where
/// line-based splitting would corrupt the stream.
///
/// Unlike [`FileSource`], this does not support intra-file byte-range sharding
/// (`instances`) because splitting an arbitrary byte range can land mid-record.
pub struct BinaryFileSource {
    key: String,
    data: Option<Bytes>,
    base_tags: Tags,
}

impl BinaryFileSource {
    pub async fn new(key: String, path: &str, mut tags: Tags) -> SourceResult<Self> {
        let file_path = Path::new(path);
        if !file_path.exists() {
            return Err(SourceReason::core_conf().to_err());
        }
        let data = tokio::fs::read(file_path)
            .await
            .map_err(|e| SourceReason::disconnect(e.to_string()))
            .with_context(file_path)
            .doing("read binary source file")?;
        tags.set("access_source", path.to_string());
        Ok(Self {
            key,
            data: Some(Bytes::from(data)),
            base_tags: tags,
        })
    }
}

#[async_trait]
impl DataSource for BinaryFileSource {
    async fn receive(&mut self) -> SourceResult<SourceBatch> {
        match self.data.take() {
            Some(bytes) if !bytes.is_empty() => {
                let event = SourceEvent::new(
                    next_event_id(),
                    &self.key,
                    RawData::Bytes(bytes),
                    Arc::new(self.base_tags.clone()),
                );
                Ok(vec![event])
            }
            _ => Err(SourceError::from(SourceReason::EOF)),
        }
    }

    fn try_receive(&mut self) -> Option<SourceBatch> {
        None
    }

    fn can_try_receive(&mut self) -> bool {
        false
    }

    fn identifier(&self) -> String {
        self.key.clone()
    }
}

pub(super) fn compute_file_ranges(
    path: &Path,
    instances: usize,
) -> std::io::Result<Vec<(u64, Option<u64>)>> {
    let size = std::fs::metadata(path)?.len();
    if size == 0 || instances <= 1 {
        return Ok(vec![(0, None)]);
    }
    let chunk = size.div_ceil(instances as u64);
    let mut starts = vec![0u64];
    for i in 1..instances {
        let target = chunk.saturating_mul(i as u64);
        if target >= size {
            break;
        }
        let aligned = align_to_next_line(path, target, size)?;
        if aligned < size {
            starts.push(aligned);
        }
    }
    starts.sort_unstable();
    starts.dedup();
    let mut ranges = Vec::with_capacity(starts.len());
    for (idx, &start) in starts.iter().enumerate() {
        let end = if idx + 1 < starts.len() {
            Some(starts[idx + 1])
        } else {
            None
        };
        ranges.push((start, end));
    }
    Ok(ranges)
}

fn align_to_next_line(path: &Path, offset: u64, file_size: u64) -> std::io::Result<u64> {
    use std::io::{Read, Seek, SeekFrom};
    if offset == 0 {
        return Ok(0);
    }
    let mut file = std::fs::File::open(path)?;
    let seek_pos = offset.saturating_sub(1);
    file.seek(SeekFrom::Start(seek_pos))?;
    let mut pos = seek_pos;
    let mut buf = [0u8; 4096];
    loop {
        let read = file.read(&mut buf)?;
        if read == 0 {
            return Ok(file_size);
        }
        for &b in &buf[..read] {
            pos += 1;
            if b == b'\n' {
                return Ok(pos);
            }
            if pos >= file_size {
                return Ok(file_size);
            }
        }
    }
}