meta_oxide 0.1.1

Universal metadata extraction library supporting 13 formats (HTML Meta, Open Graph, Twitter Cards, JSON-LD, Microdata, Microformats, RDFa, Dublin Core, Web App Manifest, oEmbed, rel-links, Images, SEO) with 7 language bindings
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
# MetaOxide Performance Tuning Guide

Comprehensive guide to optimizing MetaOxide for maximum performance across all language bindings.

## Table of Contents

- [General Principles]#general-principles
- [Language-Specific Optimizations]#language-specific-optimizations
- [Caching Strategies]#caching-strategies
- [Parallel Processing]#parallel-processing
- [Memory Optimization]#memory-optimization
- [Production Deployment]#production-deployment

## General Principles

### 1. Extract Only What You Need

**Bad**: Extract everything when you only need social metadata
```rust
let metadata = extractor.extract_all()?;  // Extracts 13 formats
let og_title = metadata.get("og:title");
```

**Good**: Use specific extractors
```rust
let og = extractor.extract_opengraph()?;  // Only Open Graph
let og_title = og.title;
```

**Performance Impact**: 3-5x faster for selective extraction

### 2. Reuse HTTP Connections

**Bad**: Create new HTTP client for each request
```python
# Each request creates new connection
response = requests.get(url)
```

**Good**: Reuse session
```python
session = requests.Session()
# Reuses connections
response = session.get(url)
```

**Performance Impact**: 2-3x faster HTTP requests

### 3. Avoid Unnecessary Parsing

**Bad**: Parse same HTML multiple times
```javascript
const extractor1 = new MetaOxide(html, url);
const og = extractor1.extractOpenGraph();

const extractor2 = new MetaOxide(html, url);  // Parses again!
const twitter = extractor2.extractTwitterCard();
```

**Good**: Parse once, extract multiple
```javascript
const extractor = new MetaOxide(html, url);  // Parse once
const og = extractor.extractOpenGraph();
const twitter = extractor.extractTwitterCard();
```

**Performance Impact**: 10-20x faster

## Language-Specific Optimizations

### Rust

#### Use Rayon for Parallel Processing

```rust
use rayon::prelude::*;
use meta_oxide::MetaOxide;

let urls: Vec<String> = vec![/* ... */];

let results: Vec<_> = urls.par_iter()
    .map(|url| {
        let html = fetch_html(url).unwrap();
        let extractor = MetaOxide::new(&html, url).unwrap();
        extractor.extract_all().unwrap()
    })
    .collect();
```

**Performance**: Process 100,000 docs/sec on 16-core CPU

#### Avoid Cloning Large Strings

```rust
// Bad: Clones HTML string
fn process(html: String) {
    let extractor = MetaOxide::new(&html, url).unwrap();
}

// Good: Use references
fn process(html: &str) {
    let extractor = MetaOxide::new(html, url).unwrap();
}
```

#### Use Arc for Shared Data

```rust
use std::sync::Arc;
use std::thread;

let html = Arc::new(fetch_html(url));

let handles: Vec<_> = (0..4).map(|_| {
    let html_clone = Arc::clone(&html);
    thread::spawn(move || {
        let extractor = MetaOxide::new(&html_clone, url).unwrap();
        extractor.extract_all()
    })
}).collect();
```

### Python

#### Use Connection Pooling

```python
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

session = requests.Session()
retry = Retry(total=3, backoff_factor=0.1)
adapter = HTTPAdapter(max_retries=retry, pool_connections=100, pool_maxsize=100)
session.mount('http://', adapter)
session.mount('https://', adapter)

# Fast parallel requests
from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(max_workers=10) as executor:
    futures = [executor.submit(extract_url, url) for url in urls]
    results = [f.result() for f in futures]
```

**Performance**: 10x faster than sequential requests

#### Use Process Pool for CPU-Intensive Work

```python
from multiprocessing import Pool
from meta_oxide import MetaOxide

def extract_metadata(args):
    html, url = args
    extractor = MetaOxide(html, url)
    return extractor.extract_all()

with Pool(processes=8) as pool:
    results = pool.map(extract_metadata, [(html, url) for html, url in data])
```

**Performance**: Scales linearly with CPU cores

#### Cache Results

```python
from functools import lru_cache
import hashlib

@lru_cache(maxsize=1000)
def extract_cached(html_hash: str, url: str) -> dict:
    html = get_html_from_cache(html_hash)
    extractor = MetaOxide(html, url)
    return extractor.extract_all()

# Usage
html_hash = hashlib.md5(html.encode()).hexdigest()
metadata = extract_cached(html_hash, url)
```

### Go

#### Use Worker Pools

```go
func extractWithWorkerPool(urls []string, workers int) []Metadata {
    jobs := make(chan string, len(urls))
    results := make(chan Metadata, len(urls))

    // Start workers
    var wg sync.WaitGroup
    for w := 0; w < workers; w++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for url := range jobs {
                metadata, err := extractFromURL(url)
                if err == nil {
                    results <- metadata
                }
            }
        }()
    }

    // Send jobs
    for _, url := range urls {
        jobs <- url
    }
    close(jobs)

    // Wait and collect
    wg.Wait()
    close(results)

    var allResults []Metadata
    for result := range results {
        allResults = append(allResults, result)
    }

    return allResults
}
```

**Performance**: Process 50,000 URLs/sec with 100 workers

#### Reuse HTTP Client

```go
var client = &http.Client{
    Transport: &http.Transport{
        MaxIdleConns:        100,
        MaxIdleConnsPerHost: 100,
        IdleConnTimeout:     90 * time.Second,
    },
    Timeout: 10 * time.Second,
}

func extractFromURL(url string) (Metadata, error) {
    resp, err := client.Get(url)  // Reuses connections
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    extractor, _ := metaoxide.NewExtractor(string(body), url)
    defer extractor.Free()

    return extractor.ExtractAll()
}
```

#### Use sync.Pool for Extractors

```go
var extractorPool = sync.Pool{
    New: func() interface{} {
        return &ExtractorWrapper{}
    },
}

type ExtractorWrapper struct {
    extractor *metaoxide.Extractor
}

func processWithPool(html, url string) Metadata {
    wrapper := extractorPool.Get().(*ExtractorWrapper)
    defer extractorPool.Put(wrapper)

    extractor, _ := metaoxide.NewExtractor(html, url)
    defer extractor.Free()

    return extractor.ExtractAll()
}
```

### Node.js

#### Use Worker Threads

```javascript
const { Worker } = require('worker_threads');

function extractInWorker(html, url) {
    return new Promise((resolve, reject) => {
        const worker = new Worker('./extract-worker.js', {
            workerData: { html, url }
        });

        worker.on('message', resolve);
        worker.on('error', reject);
        worker.on('exit', (code) => {
            if (code !== 0) {
                reject(new Error(`Worker stopped with exit code ${code}`));
            }
        });
    });
}

// extract-worker.js
const { parentPort, workerData } = require('worker_threads');
const { MetaOxide } = require('meta-oxide');

const { html, url } = workerData;
const extractor = new MetaOxide(html, url);
const metadata = extractor.extractAll();

parentPort.postMessage(metadata);
```

#### Connection Pooling with axios

```javascript
const axios = require('axios');
const http = require('http');
const https = require('https');

const client = axios.create({
    httpAgent: new http.Agent({ keepAlive: true, maxSockets: 100 }),
    httpsAgent: new https.Agent({ keepAlive: true, maxSockets: 100 }),
    timeout: 10000
});

async function extractFromURL(url) {
    const response = await client.get(url);
    const extractor = new MetaOxide(response.data, url);
    return extractor.extractAll();
}
```

#### Cluster Mode for Multi-Core

```javascript
const cluster = require('cluster');
const os = require('os');

if (cluster.isMaster) {
    const numCPUs = os.cpus().length;

    for (let i = 0; i < numCPUs; i++) {
        cluster.fork();
    }
} else {
    // Worker process
    const app = require('./app');
    app.listen(3000);
}
```

**Performance**: Utilize all CPU cores

### Java

#### Use Virtual Threads (Java 21+)

```java
import java.util.concurrent.Executors;

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    List<Future<Metadata>> futures = urls.stream()
        .map(url -> executor.submit(() -> extractFromURL(url)))
        .toList();

    List<Metadata> results = futures.stream()
        .map(f -> {
            try { return f.get(); }
            catch (Exception e) { return null; }
        })
        .filter(Objects::nonNull)
        .toList();
}
```

**Performance**: Handle millions of concurrent requests

#### Connection Pooling

```java
import java.net.http.HttpClient;
import java.time.Duration;

private static final HttpClient client = HttpClient.newBuilder()
    .connectTimeout(Duration.ofSeconds(10))
    .build();

public static Metadata extractFromURL(String url) throws Exception {
    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create(url))
        .build();

    HttpResponse<String> response = client.send(request,
        HttpResponse.BodyHandlers.ofString());

    try (MetaOxide extractor = new MetaOxide(response.body(), url)) {
        return extractor.extractAll();
    }
}
```

#### Parallel Streams

```java
List<Metadata> results = urls.parallelStream()
    .map(url -> {
        try {
            return extractFromURL(url);
        } catch (Exception e) {
            return null;
        }
    })
    .filter(Objects::nonNull)
    .toList();
```

### C#

#### Use IHttpClientFactory

```csharp
// Startup.cs
services.AddHttpClient("metadata")
    .ConfigureHttpClient(client => {
        client.Timeout = TimeSpan.FromSeconds(10);
    })
    .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler {
        PooledConnectionLifetime = TimeSpan.FromMinutes(5),
        PooledConnectionIdleTimeout = TimeSpan.FromMinutes(2),
        MaxConnectionsPerServer = 100
    });

// Service
public class MetadataService {
    private readonly HttpClient _client;

    public MetadataService(IHttpClientFactory clientFactory) {
        _client = clientFactory.CreateClient("metadata");
    }

    public async Task<Dictionary<string, object>> ExtractAsync(string url) {
        string html = await _client.GetStringAsync(url);
        using var extractor = new MetaOxideExtractor(html, url);
        return extractor.ExtractAll();
    }
}
```

#### Parallel.ForEachAsync

```csharp
await Parallel.ForEachAsync(urls, new ParallelOptions {
    MaxDegreeOfParallelism = 10
}, async (url, ct) => {
    var metadata = await ExtractFromURLAsync(url);
    // Process metadata
});
```

#### Memory Pool

```csharp
using System.Buffers;

var pool = ArrayPool<byte>.Shared;
byte[] buffer = pool.Rent(1024 * 1024);  // 1MB buffer

try {
    // Use buffer
}
finally {
    pool.Return(buffer);
}
```

### WebAssembly

#### Initialize Once

```javascript
import init, { MetaOxide } from 'meta-oxide-wasm';

let wasmInitialized = false;
let initPromise = null;

async function ensureInit() {
    if (wasmInitialized) return;

    if (!initPromise) {
        initPromise = init();
    }

    await initPromise;
    wasmInitialized = true;
}

// Usage
await ensureInit();  // Only initializes once
```

#### Web Workers for Concurrency

```javascript
// main.js
const workers = [];
for (let i = 0; i < 4; i++) {
    workers.push(new Worker('extract-worker.js', { type: 'module' }));
}

let currentWorker = 0;

function extract(html, url) {
    return new Promise((resolve) => {
        const worker = workers[currentWorker];
        currentWorker = (currentWorker + 1) % workers.length;

        worker.postMessage({ html, url });
        worker.onmessage = (e) => resolve(e.data);
    });
}
```

## Caching Strategies

### Redis Cache (Python)

```python
import redis
import hashlib
import json
from meta_oxide import MetaOxide

redis_client = redis.Redis(host='localhost', port=6379, db=0)

def extract_with_cache(html: str, url: str) -> dict:
    # Create cache key
    cache_key = f"metadata:{hashlib.md5(html.encode()).hexdigest()}"

    # Check cache
    cached = redis_client.get(cache_key)
    if cached:
        return json.loads(cached)

    # Extract and cache
    extractor = MetaOxide(html, url)
    metadata = extractor.extract_all()

    redis_client.setex(cache_key, 3600, json.dumps(metadata))  # 1 hour TTL

    return metadata
```

### In-Memory LRU Cache (Node.js)

```javascript
const LRU = require('lru-cache');
const { MetaOxide } = require('meta-oxide');
const crypto = require('crypto');

const cache = new LRU({
    max: 10000,  // Max items
    maxAge: 1000 * 60 * 60  // 1 hour
});

function extractWithCache(html, url) {
    const key = crypto.createHash('md5').update(html).digest('hex');

    if (cache.has(key)) {
        return cache.get(key);
    }

    const extractor = new MetaOxide(html, url);
    const metadata = extractor.extractAll();

    cache.set(key, metadata);

    return metadata;
}
```

## Parallel Processing

### Optimal Worker Count

General formula: **Workers = CPU_Cores × 2** (for I/O-bound tasks)

```python
import multiprocessing

optimal_workers = multiprocessing.cpu_count() * 2
```

### Batch Processing

Process in batches to avoid memory issues:

```python
def process_in_batches(urls, batch_size=1000):
    results = []

    for i in range(0, len(urls), batch_size):
        batch = urls[i:i+batch_size]

        with ThreadPoolExecutor(max_workers=20) as executor:
            batch_results = list(executor.map(extract_from_url, batch))

        results.extend(batch_results)

    return results
```

## Memory Optimization

### Limit Concurrent Extractions

```go
// Semaphore pattern
sem := make(chan struct{}, 100)  // Max 100 concurrent

for _, url := range urls {
    sem <- struct{}{}  // Acquire
    go func(u string) {
        defer func() { <-sem }()  // Release

        extract(u)
    }(url)
}
```

### Stream Processing

For very large HTML documents:

```rust
// Process HTML in streaming fashion
use std::io::BufReader;

let reader = BufReader::new(file);
// MetaOxide handles streaming internally
```

## Production Deployment

### Kubernetes Deployment

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: metadata-extractor
spec:
  replicas: 4
  template:
    spec:
      containers:
      - name: extractor
        image: metaoxide-api:latest
        resources:
          requests:
            memory: "256Mi"
            cpu: "500m"
          limits:
            memory: "512Mi"
            cpu: "1000m"
        env:
        - name: WORKER_COUNT
          value: "4"
```

### Load Balancing

Distribute requests across multiple instances:

```nginx
upstream metaoxide_backend {
    least_conn;  # Route to least busy server

    server backend1:3000 max_fails=3 fail_timeout=30s;
    server backend2:3000 max_fails=3 fail_timeout=30s;
    server backend3:3000 max_fails=3 fail_timeout=30s;
    server backend4:3000 max_fails=3 fail_timeout=30s;
}
```

### Monitoring

Track key metrics:

```python
from prometheus_client import Counter, Histogram

extraction_duration = Histogram('extraction_duration_seconds',
                               'Time spent extracting metadata')
extraction_errors = Counter('extraction_errors_total',
                           'Total extraction errors')

@extraction_duration.time()
def extract_metadata(html, url):
    try:
        extractor = MetaOxide(html, url)
        return extractor.extract_all()
    except Exception as e:
        extraction_errors.inc()
        raise
```

## Performance Checklist

- [ ] Extract only needed metadata formats
- [ ] Reuse HTTP connections
- [ ] Implement caching (Redis, Memcached)
- [ ] Use parallel processing (workers, threads, processes)
- [ ] Set appropriate timeouts
- [ ] Monitor memory usage
- [ ] Profile hot paths
- [ ] Use connection pooling
- [ ] Implement rate limiting
- [ ] Set up load balancing
- [ ] Configure auto-scaling
- [ ] Monitor with metrics

## See Also

- [Benchmarks]/docs/performance/benchmarks.md
- [Architecture Overview]/docs/architecture/architecture-overview.md
- [Examples]/examples/real-world/