oxirs-ttl 0.3.2

Turtle-family RDF parser and serializer for OxiRS - ported from Oxigraph
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
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
# Async Usage Guide - OxiRS TTL

This guide covers asynchronous, non-blocking RDF parsing and serialization using Tokio.

## Table of Contents

- [Why Async?]#why-async
- [Setup]#setup
- [Basic Async Parsing]#basic-async-parsing
- [Async Streaming]#async-streaming
- [Concurrent Parsing]#concurrent-parsing
- [Network Integration]#network-integration
- [Error Handling]#error-handling
- [Performance Optimization]#performance-optimization
- [Real-World Examples]#real-world-examples

## Why Async?

Asynchronous I/O is essential for:

- **Web servers**: Parse RDF from HTTP requests without blocking
- **Network clients**: Fetch and parse RDF from remote sources
- **Concurrent operations**: Parse multiple files simultaneously
- **Microservices**: Non-blocking integration with async frameworks

**Performance benefits**:
- Handle thousands of concurrent connections
- Efficient resource utilization (CPU + I/O overlap)
- Low latency for high-throughput applications

## Setup

Add the `async-tokio` feature to your `Cargo.toml`:

```toml
[dependencies]
oxirs-ttl = { version = "0.3.0", features = ["async-tokio"] }
tokio = { version = "1", features = ["full"] }
```

## Basic Async Parsing

### Async Turtle Parsing

```rust
use oxirs_ttl::async_parser::AsyncTurtleParser;
use tokio::fs::File;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Open file asynchronously
    let file = File::open("data.ttl").await?;

    // Parse with async parser
    let parser = AsyncTurtleParser::new();
    let triples = parser.parse_async(file).await?;

    println!("Parsed {} triples", triples.len());
    Ok(())
}
```

### Async N-Triples Parsing

```rust
use oxirs_ttl::async_parser::AsyncNTriplesParser;
use tokio::fs::File;
use tokio::io::AsyncBufReadExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let file = File::open("data.nt").await?;
    let reader = tokio::io::BufReader::new(file);
    let parser = AsyncNTriplesParser::new();

    let mut lines = reader.lines();
    let mut count = 0;

    // Parse line by line asynchronously
    while let Some(line) = lines.next_line().await? {
        if let Ok(triple) = parser.parse_line(&line) {
            count += 1;
            // Process triple immediately
        }
    }

    println!("Parsed {} triples", count);
    Ok(())
}
```

### Async TriG Parsing

```rust
use oxirs_ttl::async_parser::AsyncTriGParser;
use tokio::fs::File;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let file = File::open("data.trig").await?;
    let parser = AsyncTriGParser::new();

    let quads = parser.parse_async(file).await?;

    for quad in quads {
        println!("Graph: {:?}, Triple: {}", quad.graph_name, quad);
    }

    Ok(())
}
```

## Async Streaming

### Async Streaming with Tokio

Stream large files asynchronously:

```rust
use oxirs_ttl::async_parser::AsyncStreamingParser;
use tokio::fs::File;
use futures::StreamExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let file = File::open("large.ttl").await?;
    let parser = AsyncStreamingParser::new(file);

    // Get async stream of batches
    let mut stream = parser.batches();

    let mut total = 0;
    while let Some(batch) = stream.next().await {
        let triples = batch?;
        total += triples.len();

        // Async processing
        async_process_batch(&triples).await?;
    }

    println!("Total: {} triples", total);
    Ok(())
}

async fn async_process_batch(
    triples: &[Triple]
) -> Result<(), Box<dyn std::error::Error>> {
    // Async database insert, network call, etc.
    tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
    Ok(())
}
```

### Configuring Async Streaming

```rust
use oxirs_ttl::{AsyncStreamingParser, StreamingConfig};

let config = StreamingConfig::default()
    .with_batch_size(10_000)
    .with_buffer_size(128 * 1024);  // 128KB async read buffer

let file = File::open("data.ttl").await?;
let parser = AsyncStreamingParser::with_config(file, config);

let mut stream = parser.batches();
while let Some(batch) = stream.next().await {
    let triples = batch?;
    // Process asynchronously...
}
```

## Concurrent Parsing

### Parse Multiple Files Concurrently

```rust
use oxirs_ttl::async_parser::AsyncTurtleParser;
use tokio::fs::File;
use futures::future::join_all;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let files = vec!["file1.ttl", "file2.ttl", "file3.ttl"];

    // Parse all files concurrently
    let parse_tasks: Vec<_> = files
        .into_iter()
        .map(|path| async move {
            let file = File::open(path).await?;
            let parser = AsyncTurtleParser::new();
            parser.parse_async(file).await
        })
        .collect();

    let results = join_all(parse_tasks).await;

    let mut total = 0;
    for (i, result) in results.into_iter().enumerate() {
        match result {
            Ok(triples) => {
                println!("File {}: {} triples", i, triples.len());
                total += triples.len();
            }
            Err(e) => eprintln!("File {}: Error: {}", i, e),
        }
    }

    println!("Total across all files: {} triples", total);
    Ok(())
}
```

### Concurrent Streaming with Tokio Tasks

```rust
use oxirs_ttl::async_parser::AsyncStreamingParser;
use tokio::task;
use futures::StreamExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let files = vec!["large1.ttl", "large2.ttl", "large3.ttl"];

    let mut handles = vec![];

    for path in files {
        let handle = task::spawn(async move {
            let file = File::open(path).await.unwrap();
            let parser = AsyncStreamingParser::new(file);
            let mut stream = parser.batches();

            let mut count = 0;
            while let Some(batch) = stream.next().await {
                let triples = batch.unwrap();
                count += triples.len();
            }

            (path, count)
        });

        handles.push(handle);
    }

    // Wait for all tasks to complete
    for handle in handles {
        let (path, count) = handle.await?;
        println!("{}: {} triples", path, count);
    }

    Ok(())
}
```

### Rate-Limited Concurrent Parsing

Control concurrency with semaphores:

```rust
use tokio::sync::Semaphore;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let files: Vec<String> = (0..100)
        .map(|i| format!("file{}.ttl", i))
        .collect();

    // Limit to 10 concurrent parses
    let semaphore = Arc::new(Semaphore::new(10));
    let mut handles = vec![];

    for path in files {
        let sem = semaphore.clone();

        let handle = task::spawn(async move {
            // Acquire permit (blocks if 10 tasks already running)
            let _permit = sem.acquire().await.unwrap();

            let file = File::open(&path).await.unwrap();
            let parser = AsyncTurtleParser::new();
            let triples = parser.parse_async(file).await.unwrap();

            (path, triples.len())
        });

        handles.push(handle);
    }

    for handle in handles {
        let (path, count) = handle.await?;
        println!("{}: {} triples", path, count);
    }

    Ok(())
}
```

## Network Integration

### Fetch and Parse RDF from HTTP

```rust
use oxirs_ttl::async_parser::AsyncTurtleParser;
use tokio::io::AsyncReadExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Fetch RDF from remote server
    let response = reqwest::get("https://example.org/data.ttl").await?;
    let bytes = response.bytes().await?;

    // Parse from bytes
    let parser = AsyncTurtleParser::new();
    let triples = parser.parse_async(&bytes[..]).await?;

    println!("Fetched and parsed {} triples", triples.len());
    Ok(())
}
```

### Streaming HTTP Response

Stream large RDF files from network:

```rust
use oxirs_ttl::async_parser::AsyncStreamingParser;
use futures::StreamExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let response = reqwest::get("https://example.org/large.ttl").await?;

    // Wrap response body in async reader
    let reader = tokio_util::io::StreamReader::new(
        response.bytes_stream().map(|r| {
            r.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))
        })
    );

    let parser = AsyncStreamingParser::new(reader);
    let mut stream = parser.batches();

    let mut total = 0;
    while let Some(batch) = stream.next().await {
        let triples = batch?;
        total += triples.len();

        // Process while downloading continues
        async_process_batch(&triples).await?;
    }

    println!("Downloaded and parsed {} triples", total);
    Ok(())
}
```

### WebSocket RDF Streaming

Real-time RDF updates over WebSocket:

```rust
use tokio_tungstenite::{connect_async, tungstenite::Message};
use futures::{StreamExt, SinkExt};
use oxirs_ttl::async_parser::AsyncTurtleParser;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (ws_stream, _) = connect_async("ws://example.org/rdf-stream").await?;
    let (mut write, mut read) = ws_stream.split();

    let parser = AsyncTurtleParser::new();

    while let Some(msg) = read.next().await {
        let msg = msg?;

        if let Message::Text(text) = msg {
            // Parse RDF chunk
            match parser.parse_document(&text) {
                Ok(triples) => {
                    println!("Received {} triples", triples.len());
                    // Process real-time...
                }
                Err(e) => eprintln!("Parse error: {}", e),
            }
        }
    }

    Ok(())
}
```

## Error Handling

### Async Result Handling

```rust
use oxirs_ttl::async_parser::AsyncTurtleParser;
use oxirs_ttl::TurtleParseError;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let file = File::open("data.ttl").await?;
    let parser = AsyncTurtleParser::new();

    match parser.parse_async(file).await {
        Ok(triples) => {
            println!("Success: {} triples", triples.len());
        }
        Err(TurtleParseError::Syntax(e)) => {
            eprintln!("Syntax error at {}:{}: {}",
                e.position.line, e.position.column, e.message);
        }
        Err(TurtleParseError::Io(e)) => {
            eprintln!("I/O error: {}", e);
        }
        Err(e) => {
            eprintln!("Parse error: {}", e);
        }
    }

    Ok(())
}
```

### Timeout Handling

Add timeouts to prevent hanging:

```rust
use tokio::time::{timeout, Duration};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let file = File::open("data.ttl").await?;
    let parser = AsyncTurtleParser::new();

    // 30 second timeout
    match timeout(Duration::from_secs(30), parser.parse_async(file)).await {
        Ok(Ok(triples)) => {
            println!("Parsed {} triples", triples.len());
        }
        Ok(Err(e)) => {
            eprintln!("Parse error: {}", e);
        }
        Err(_) => {
            eprintln!("Parse timed out after 30 seconds");
        }
    }

    Ok(())
}
```

### Retry Logic

Implement exponential backoff for network failures:

```rust
use tokio::time::{sleep, Duration};

async fn fetch_and_parse_with_retry(
    url: &str,
    max_retries: u32
) -> Result<Vec<Triple>, Box<dyn std::error::Error>> {
    let mut retries = 0;

    loop {
        match try_fetch_and_parse(url).await {
            Ok(triples) => return Ok(triples),
            Err(e) if retries < max_retries => {
                retries += 1;
                let delay = Duration::from_secs(2_u64.pow(retries));
                eprintln!("Retry {} after {:?}: {}", retries, delay, e);
                sleep(delay).await;
            }
            Err(e) => return Err(e),
        }
    }
}

async fn try_fetch_and_parse(
    url: &str
) -> Result<Vec<Triple>, Box<dyn std::error::Error>> {
    let response = reqwest::get(url).await?;
    let bytes = response.bytes().await?;
    let parser = AsyncTurtleParser::new();
    Ok(parser.parse_async(&bytes[..]).await?)
}
```

## Performance Optimization

### Buffered Async I/O

Use proper buffering for optimal performance:

```rust
use tokio::io::BufReader;

let file = File::open("data.ttl").await?;

// Wrap in BufReader for efficient async reads
let buffered = BufReader::with_capacity(128 * 1024, file);  // 128KB buffer

let parser = AsyncStreamingParser::new(buffered);
```

### Async Batch Processing Pipeline

Overlap I/O and processing:

```rust
use tokio::sync::mpsc;
use futures::StreamExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (tx, mut rx) = mpsc::channel(10);  // Buffer 10 batches

    // Parser task
    let parser_task = tokio::spawn(async move {
        let file = File::open("large.ttl").await.unwrap();
        let parser = AsyncStreamingParser::new(file);
        let mut stream = parser.batches();

        while let Some(batch) = stream.next().await {
            if tx.send(batch).await.is_err() {
                break;  // Receiver dropped
            }
        }
    });

    // Processing task
    let processor_task = tokio::spawn(async move {
        while let Some(batch) = rx.recv().await {
            let triples = batch.unwrap();
            // CPU-intensive processing happens while next batch is parsing
            process_batch(&triples).await.unwrap();
        }
    });

    // Wait for both tasks
    tokio::try_join!(parser_task, processor_task)?;
    Ok(())
}
```

### Parallel Async Operations

Combine async I/O with parallel CPU processing:

```rust
use rayon::prelude::*;
use tokio::task;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let file = File::open("large.ttl").await?;
    let parser = AsyncStreamingParser::new(file);
    let mut stream = parser.batches();

    while let Some(batch) = stream.next().await {
        let triples = batch?;

        // Move CPU-intensive work to thread pool
        let processed = task::spawn_blocking(move || {
            triples.par_iter()
                .map(|t| expensive_computation(t))
                .collect::<Vec<_>>()
        }).await?;

        // Continue with results...
    }

    Ok(())
}
```

## Real-World Examples

### Example 1: Async Web Service

Axum web service for RDF parsing:

```rust
use axum::{
    Router,
    extract::Multipart,
    response::IntoResponse,
    routing::post,
};
use oxirs_ttl::async_parser::AsyncTurtleParser;

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/parse", post(parse_rdf));

    axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

async fn parse_rdf(mut multipart: Multipart) -> impl IntoResponse {
    while let Some(field) = multipart.next_field().await.unwrap() {
        let data = field.bytes().await.unwrap();

        let parser = AsyncTurtleParser::new();
        match parser.parse_async(&data[..]).await {
            Ok(triples) => {
                return format!("Parsed {} triples", triples.len());
            }
            Err(e) => {
                return format!("Error: {}", e);
            }
        }
    }

    "No data received".to_string()
}
```

### Example 2: Distributed RDF Processing

Process RDF files from S3 with AWS SDK:

```rust
use aws_sdk_s3::Client;
use oxirs_ttl::async_parser::AsyncStreamingParser;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = aws_config::load_from_env().await;
    let client = Client::new(&config);

    // List objects in bucket
    let objects = client
        .list_objects_v2()
        .bucket("my-rdf-bucket")
        .send()
        .await?;

    for obj in objects.contents.unwrap_or_default() {
        let key = obj.key.unwrap();

        // Get object stream
        let output = client
            .get_object()
            .bucket("my-rdf-bucket")
            .key(&key)
            .send()
            .await?;

        // Parse streaming
        let parser = AsyncStreamingParser::new(output.body.into_async_read());
        let mut stream = parser.batches();

        let mut count = 0;
        while let Some(batch) = stream.next().await {
            let triples = batch?;
            count += triples.len();
        }

        println!("{}: {} triples", key, count);
    }

    Ok(())
}
```

### Example 3: Real-time RDF Updates

Process RDF updates from Kafka:

```rust
use rdkafka::consumer::{Consumer, StreamConsumer};
use rdkafka::config::ClientConfig;
use futures::StreamExt;
use oxirs_ttl::async_parser::AsyncTurtleParser;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let consumer: StreamConsumer = ClientConfig::new()
        .set("bootstrap.servers", "localhost:9092")
        .set("group.id", "rdf-parser")
        .create()?;

    consumer.subscribe(&["rdf-updates"])?;

    let parser = AsyncTurtleParser::new();
    let mut message_stream = consumer.stream();

    while let Some(message) = message_stream.next().await {
        let message = message?;

        if let Some(payload) = message.payload() {
            match parser.parse_async(payload).await {
                Ok(triples) => {
                    println!("Received update with {} triples", triples.len());
                    // Process triples...
                }
                Err(e) => eprintln!("Parse error: {}", e),
            }
        }
    }

    Ok(())
}
```

## Best Practices

1. **Use proper buffering**: Wrap file readers with `BufReader` for efficient async I/O
2. **Set timeouts**: Always use timeouts for network operations
3. **Handle backpressure**: Use bounded channels to prevent memory issues
4. **Limit concurrency**: Use semaphores to control concurrent tasks
5. **Error recovery**: Implement retry logic for transient failures
6. **Monitor performance**: Track throughput and latency metrics
7. **CPU-bound work**: Use `spawn_blocking` for CPU-intensive operations
8. **Resource cleanup**: Ensure proper cleanup with `Drop` or `finally` patterns

## Troubleshooting

### "Too many open files" error

Reduce concurrent parsing or increase file descriptor limit:

```bash
ulimit -n 4096  # Increase to 4096
```

```rust
// Limit concurrent operations
let semaphore = Arc::new(Semaphore::new(100));  // Max 100 concurrent
```

### Slow async performance

- Use `BufReader` for file I/O
- Increase buffer sizes for network I/O
- Profile with `tokio-console` to identify bottlenecks
- Consider using `spawn_blocking` for CPU-intensive work

### Memory leaks in long-running services

- Ensure proper cleanup of resources
- Use weak references for caches
- Monitor memory with tools like `valgrind`
- Consider periodic restarts for critical services

## See Also

- [Streaming Tutorial]STREAMING_TUTORIAL.md - Memory-efficient batch processing
- [Performance Tuning Guide]PERFORMANCE_GUIDE.md - Optimization techniques
- [Tokio Documentation]https://tokio.rs - Async runtime documentation
- [API Documentation]https://docs.rs/oxirs-ttl - Full API reference