domain-status 0.2.1

Concurrent URL status checker that captures comprehensive metadata in SQLite.
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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
//! Shared database queries for export functionality.
//!
//! This module centralizes all export-related queries to ensure consistency
//! between CSV and JSONL export formats.
//!
//! All helper functions used by both CSV and JSONL exports are defined here
//! to prevent duplication and ensure both formats stay in sync.

use anyhow::Result;
#[cfg(test)]
use sqlx::SqlitePool;
use sqlx::{QueryBuilder, Row};
use std::io::{self, ErrorKind, Write};

use crate::storage::DbPool;

fn with_export_limit(query: &str) -> String {
    format!(
        "{query} LIMIT {}",
        crate::config::MAX_EXPORT_RELATED_RECORDS
    )
}

/// Wrapper around a Write that ignores broken pipe errors (EPIPE).
/// This allows graceful handling when stdout is piped to a command that exits early.
pub(crate) struct IgnoreBrokenPipe<W: Write> {
    inner: W,
}

impl<W: Write> IgnoreBrokenPipe<W> {
    pub(crate) fn new(inner: W) -> Self {
        Self { inner }
    }
}

impl<W: Write> Write for IgnoreBrokenPipe<W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.inner.write(buf).or_else(|e| {
            if e.kind() == ErrorKind::BrokenPipe {
                // Ignore broken pipe - downstream command closed the pipe
                Ok(buf.len())
            } else {
                Err(e)
            }
        })
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush().or_else(|e| {
            if e.kind() == ErrorKind::BrokenPipe {
                Ok(())
            } else {
                Err(e)
            }
        })
    }
}

/// Helper: Fetch a list of string values from a query that returns a single column.
/// Returns (`joined_string`, count).
pub(crate) async fn fetch_string_list(
    pool: &DbPool,
    query: &str,
    url_status_id: i64,
) -> Result<(String, usize)> {
    let rows = crate::sql::query(with_export_limit(query))
        .bind(url_status_id)
        .fetch_all(pool.as_ref())
        .await?;

    let items: Vec<String> = rows.iter().map(|r| r.get::<String, _>(0)).collect();
    let count = items.len();
    let joined = items.join(",");
    Ok((joined, count))
}

/// Helper: Fetch a count from a query.
pub(crate) async fn fetch_count_query(
    pool: &DbPool,
    query: &str,
    url_status_id: i64,
) -> Result<i64> {
    crate::sql::query_scalar::<i64>(query)
        .bind(url_status_id)
        .fetch_one(pool.as_ref())
        .await
        .map_err(Into::into)
}

/// Helper: Fetch key-value pairs and format as "key:value" strings.
/// Returns (`joined_string`, count).
///
/// Production export derives these strings from structured satellite rows; this
/// helper remains as the unit-test seam for the CSV `key:value` join format.
#[cfg(test)]
pub(crate) async fn fetch_key_value_list(
    pool: &DbPool,
    query: &str,
    key_field: &str,
    value_field: &str,
    url_status_id: i64,
) -> Result<(String, usize)> {
    let rows = crate::sql::query(with_export_limit(query))
        .bind(url_status_id)
        .fetch_all(pool.as_ref())
        .await?;

    let items: Vec<String> = rows
        .iter()
        .map(|r| {
            let key: String = r.get::<Option<String>, _>(key_field).unwrap_or_default();
            let value: String = r.get::<Option<String>, _>(value_field).unwrap_or_default();
            format!("{key}:{value}")
        })
        .collect();
    let count = items.len();
    let joined = items.join(",");
    Ok((joined, count))
}

/// Identifies which header table an export query targets.
///
/// `SQLite` query builders cannot bind a table name as a parameter, so we have to
/// inline it textually. Using an enum (rather than a `&str`) makes the set of
/// valid identifiers exhaustive and verified at compile time, so a future caller
/// mistake cannot accidentally introduce a SQL-injection footgun.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HttpHeadersTable {
    /// `url_http_headers` — full response headers captured during the scan.
    Standard,
    /// `url_security_headers` — security-relevant headers (CSP, HSTS, etc.) only.
    Security,
}

impl HttpHeadersTable {
    /// Returns the SQL identifier for this table. Always a static string literal
    /// from a closed set, so it cannot smuggle attacker-controlled SQL.
    fn as_sql_ident(self) -> &'static str {
        match self {
            HttpHeadersTable::Standard => "url_http_headers",
            HttpHeadersTable::Security => "url_security_headers",
        }
    }
}

/// Helper: Fetch filtered HTTP headers and format as "name:value" strings.
/// Returns (`joined_string`, `total_count`).
/// The joined string contains only filtered headers (separated by semicolons),
/// but the count is the total number of headers in the table.
pub(crate) async fn fetch_filtered_http_headers(
    pool: &DbPool,
    table: HttpHeadersTable,
    url_status_id: i64,
    allowed_headers: &[&str],
) -> Result<(String, i64)> {
    // Static identifier from a closed enum (HttpHeadersTable). Safe to inline.
    let table = table.as_sql_ident();

    // Build query with IN clause for allowed headers
    // Use QueryBuilder to safely construct the query
    let mut query_builder = sqlx::QueryBuilder::new(format!(
        "SELECT header_name, header_value FROM {table} WHERE url_status_id = "
    ));

    query_builder.push_bind(url_status_id);
    query_builder.push(" AND header_name IN (");

    // Add placeholders for each allowed header
    let mut separated = query_builder.separated(", ");
    for header in allowed_headers {
        separated.push_bind(*header);
    }
    separated.push_unseparated(") ORDER BY header_name LIMIT ");
    query_builder.push_bind(crate::config::MAX_EXPORT_RELATED_RECORDS);

    let rows = query_builder.build().fetch_all(pool.as_ref()).await?;

    let items: Vec<String> = rows
        .iter()
        .map(|r| {
            let name: String = r.get("header_name");
            let value: String = r.get("header_value");
            format!("{name}:{value}")
        })
        .collect();
    let joined = items.join(";");

    // Get total count (all headers, not just filtered)
    let total_count = fetch_count_query(
        pool,
        &format!("SELECT COUNT(*) FROM {table} WHERE url_status_id = ?"),
        url_status_id,
    )
    .await?;

    Ok((joined, total_count))
}

/// Build the complete export query with optional filters and ordering.
///
/// This is the single source of truth for the export SELECT query.
/// All export formats (CSV, JSONL, Parquet) use this function.
pub(crate) fn build_export_query<'a>(
    run_id: Option<&'a str>,
    domain: Option<&'a str>,
    status: Option<u16>,
    since: Option<i64>,
) -> QueryBuilder<sqlx::Sqlite> {
    let mut qb = QueryBuilder::new(
        "SELECT us.id, us.initial_domain, us.final_domain, us.initial_url, us.final_url, us.ip_address, us.reverse_dns_name,
                us.http_status, us.http_status_text, us.response_time_seconds, us.title,
                us.description, us.meta_robots, us.tls_version, us.ssl_cert_subject,
                us.ssl_cert_issuer, us.ssl_cert_valid_to_ms, us.cipher_suite, us.key_algorithm,
                us.spf_record, us.dmarc_record,
                us.mta_sts_record, us.tls_rpt_record, us.bimi_record,
                us.hsts_max_age, us.hsts_include_subdomains, us.hsts_preload,
                us.cdn_provider,
                us.observed_at_ms, us.run_id,
                us.body_sha256, us.content_length, us.http_version,
                us.content_type, us.canonical_url, us.cert_fingerprint_sha256,
                us.body_truncated
         FROM url_status us",
    );
    build_where_clause(&mut qb, run_id, domain, status, since);
    qb.push(" ORDER BY us.observed_at_ms DESC");
    qb
}

/// Builds WHERE clause for export queries based on filter parameters.
/// Modifies the query builder in place.
fn build_where_clause<'a>(
    query_builder: &mut QueryBuilder<sqlx::Sqlite>,
    run_id: Option<&'a str>,
    domain: Option<&'a str>,
    status: Option<u16>,
    since: Option<i64>,
) {
    let mut has_where = false;

    if let Some(run_id) = run_id {
        query_builder.push(" WHERE us.run_id = ");
        query_builder.push_bind(run_id);
        has_where = true;
    }

    if let Some(domain) = domain {
        if has_where {
            query_builder.push(" AND ");
        } else {
            query_builder.push(" WHERE ");
            has_where = true;
        }
        query_builder.push("(us.initial_domain = ");
        query_builder.push_bind(domain);
        query_builder.push(" OR us.final_domain = ");
        query_builder.push_bind(domain);
        query_builder.push(")");
    }

    if let Some(status) = status {
        if has_where {
            query_builder.push(" AND ");
        } else {
            query_builder.push(" WHERE ");
            has_where = true;
        }
        query_builder.push("us.http_status = ");
        query_builder.push_bind(status);
    }

    if let Some(since) = since {
        if has_where {
            query_builder.push(" AND ");
        } else {
            query_builder.push(" WHERE ");
        }
        query_builder.push("us.observed_at_ms >= ");
        query_builder.push_bind(since);
    }
}

// The following functions return structured data (not formatted strings).
// Used by tests; the main export path uses the formatted helpers above.
#[cfg(test)]
/// Fetches redirect chain for a URL status record.
pub async fn fetch_redirect_chain(
    pool: &SqlitePool,
    url_status_id: i64,
) -> Result<Vec<String>, sqlx::Error> {
    let rows = sqlx::query(
        "SELECT redirect_url FROM url_redirect_chain WHERE url_status_id = ? ORDER BY sequence_order",
    )
    .bind(url_status_id)
    .fetch_all(pool)
    .await?;

    Ok(rows
        .iter()
        .map(|r| r.get::<String, _>("redirect_url"))
        .collect())
}

/// Fetches technologies with optional versions for a URL status record.
#[cfg(test)]
pub async fn fetch_technologies(
    pool: &SqlitePool,
    url_status_id: i64,
) -> Result<Vec<(String, Option<String>)>, sqlx::Error> {
    let rows = sqlx::query(
        "SELECT technology_name, technology_version FROM url_technologies
         WHERE url_status_id = ? ORDER BY technology_name, technology_version",
    )
    .bind(url_status_id)
    .fetch_all(pool)
    .await?;

    Ok(rows
        .iter()
        .map(|r| {
            (
                r.get::<String, _>("technology_name"),
                r.get::<Option<String>, _>("technology_version"),
            )
        })
        .collect())
}

#[cfg(test)]
mod tests {
    use super::*;
    use sqlx::sqlite::SqlitePoolOptions;
    use std::sync::Arc;

    async fn create_test_pool() -> SqlitePool {
        let pool = SqlitePoolOptions::new()
            .max_connections(1)
            .connect("sqlite::memory:")
            .await
            .unwrap();

        // Create minimal schema for testing
        sqlx::query(
            "CREATE TABLE url_status (
                id INTEGER PRIMARY KEY,
                initial_domain TEXT NOT NULL
            )",
        )
        .execute(&pool)
        .await
        .unwrap();

        sqlx::query(
            "CREATE TABLE url_redirect_chain (
                id INTEGER PRIMARY KEY,
                url_status_id INTEGER NOT NULL,
                redirect_url TEXT NOT NULL,
                sequence_order INTEGER NOT NULL
            )",
        )
        .execute(&pool)
        .await
        .unwrap();

        sqlx::query(
            "CREATE TABLE url_technologies (
                id INTEGER PRIMARY KEY,
                url_status_id INTEGER NOT NULL,
                technology_name TEXT NOT NULL,
                technology_version TEXT,
                technology_category TEXT,
                is_implied INTEGER NOT NULL DEFAULT 0,
                detection_source TEXT
            )",
        )
        .execute(&pool)
        .await
        .unwrap();

        sqlx::query(
            "CREATE TABLE url_analytics_ids (
                id INTEGER PRIMARY KEY,
                url_status_id INTEGER NOT NULL,
                provider TEXT NOT NULL,
                tracking_id TEXT NOT NULL
            )",
        )
        .execute(&pool)
        .await
        .unwrap();

        pool
    }

    #[tokio::test]
    async fn test_fetch_redirect_chain() {
        let pool = create_test_pool().await;

        sqlx::query("INSERT INTO url_redirect_chain (url_status_id, redirect_url, sequence_order) VALUES (1, 'https://a.com', 1), (1, 'https://b.com', 2)")
            .execute(&pool)
            .await
            .unwrap();

        let chain = fetch_redirect_chain(&pool, 1).await.unwrap();
        assert_eq!(chain, vec!["https://a.com", "https://b.com"]);
    }

    #[tokio::test]
    async fn test_fetch_redirect_chain_empty() {
        let pool = create_test_pool().await;
        let chain = fetch_redirect_chain(&pool, 999).await.unwrap();
        assert!(chain.is_empty());
    }

    #[tokio::test]
    async fn test_fetch_technologies() {
        let pool = create_test_pool().await;

        sqlx::query("INSERT INTO url_technologies (url_status_id, technology_name, technology_version) VALUES (1, 'WordPress', '6.0'), (1, 'PHP', NULL)")
            .execute(&pool)
            .await
            .unwrap();

        let techs = fetch_technologies(&pool, 1).await.unwrap();
        assert_eq!(techs.len(), 2);
        assert!(techs.contains(&("PHP".to_string(), None)));
        assert!(techs.contains(&("WordPress".to_string(), Some("6.0".to_string()))));
    }

    #[tokio::test]
    async fn test_fetch_string_list_empty() {
        // Test fetch_string_list with no results
        let pool = create_test_pool().await;
        let pool_arc = Arc::new(pool);

        let (result, count) = fetch_string_list(
            &pool_arc,
            "SELECT redirect_url FROM url_redirect_chain WHERE url_status_id = ?",
            999,
        )
        .await
        .expect("Should succeed with empty result");

        assert_eq!(result, "");
        assert_eq!(count, 0);
    }

    #[tokio::test]
    async fn test_fetch_string_list_multiple() {
        // Test fetch_string_list with multiple results
        let pool = create_test_pool().await;
        let pool_arc = Arc::new(pool);

        sqlx::query("INSERT INTO url_redirect_chain (url_status_id, redirect_url, sequence_order) VALUES (1, 'https://a.com', 1), (1, 'https://b.com', 2), (1, 'https://c.com', 3)")
            .execute(&*pool_arc)
            .await
            .unwrap();

        let (result, count) = fetch_string_list(
            &pool_arc,
            "SELECT redirect_url FROM url_redirect_chain WHERE url_status_id = ? ORDER BY sequence_order",
            1,
        )
        .await
        .expect("Should succeed");

        assert_eq!(result, "https://a.com,https://b.com,https://c.com");
        assert_eq!(count, 3);
    }

    #[tokio::test]
    async fn test_fetch_count_query_zero() {
        // Test fetch_count_query with zero count
        let pool = create_test_pool().await;
        let pool_arc = Arc::new(pool);

        let count = fetch_count_query(
            &pool_arc,
            "SELECT COUNT(*) FROM url_redirect_chain WHERE url_status_id = ?",
            999,
        )
        .await
        .expect("Should succeed");

        assert_eq!(count, 0);
    }

    #[tokio::test]
    async fn test_fetch_count_query_non_zero() {
        // Test fetch_count_query with non-zero count
        let pool = create_test_pool().await;
        let pool_arc = Arc::new(pool);

        sqlx::query("INSERT INTO url_redirect_chain (url_status_id, redirect_url, sequence_order) VALUES (1, 'https://a.com', 1), (1, 'https://b.com', 2)")
            .execute(&*pool_arc)
            .await
            .unwrap();

        let count = fetch_count_query(
            &pool_arc,
            "SELECT COUNT(*) FROM url_redirect_chain WHERE url_status_id = ?",
            1,
        )
        .await
        .expect("Should succeed");

        assert_eq!(count, 2);
    }

    #[tokio::test]
    async fn test_fetch_key_value_list_empty() {
        // Test fetch_key_value_list with no results
        let pool = create_test_pool().await;
        let pool_arc = Arc::new(pool);

        let (result, count) = fetch_key_value_list(
            &pool_arc,
            "SELECT provider, tracking_id FROM url_analytics_ids WHERE url_status_id = ?",
            "provider",
            "tracking_id",
            999,
        )
        .await
        .expect("Should succeed with empty result");

        assert_eq!(result, "");
        assert_eq!(count, 0);
    }

    #[tokio::test]
    async fn test_fetch_key_value_list_multiple() {
        // Test fetch_key_value_list with multiple results
        let pool = create_test_pool().await;
        let pool_arc = Arc::new(pool);

        sqlx::query("INSERT INTO url_analytics_ids (url_status_id, provider, tracking_id) VALUES (1, 'Google Analytics', 'UA-12345'), (1, 'Facebook Pixel', '123456789')")
            .execute(&*pool_arc)
            .await
            .unwrap();

        let (result, count) = fetch_key_value_list(
            &pool_arc,
            "SELECT provider, tracking_id FROM url_analytics_ids WHERE url_status_id = ? ORDER BY provider",
            "provider",
            "tracking_id",
            1,
        )
        .await
        .expect("Should succeed");

        assert!(result.contains("Facebook Pixel:123456789"));
        assert!(result.contains("Google Analytics:UA-12345"));
        assert_eq!(count, 2);
    }

    #[test]
    fn test_build_where_clause_no_filters_produces_no_where() {
        let mut qb = sqlx::QueryBuilder::new("SELECT * FROM url_status us");
        build_where_clause(&mut qb, None, None, None, None);
        let sql = qb.sql();
        let sql = sql.as_str();
        assert!(
            !sql.contains("WHERE"),
            "No filters should produce no WHERE clause, got: {sql}"
        );
    }

    #[test]
    fn test_build_where_clause_all_filters_produces_correct_sql() {
        let mut qb = sqlx::QueryBuilder::new("SELECT * FROM url_status us");
        build_where_clause(
            &mut qb,
            Some("run-1"),
            Some("example.com"),
            Some(200),
            Some(1704067200000i64),
        );
        let sql = qb.sql();
        let sql = sql.as_str();
        // Should have WHERE and three ANDs (4 clauses joined)
        assert!(sql.contains("WHERE"), "Should have WHERE clause");
        assert_eq!(
            sql.matches(" AND ").count(),
            3,
            "4 filters should produce 3 ANDs, got: {sql}"
        );
        // Should reference the correct columns
        assert!(sql.contains("us.run_id"), "Should filter by run_id");
        assert!(
            sql.contains("us.initial_domain") && sql.contains("us.final_domain"),
            "Should filter by both initial and final domain"
        );
        assert!(sql.contains("us.http_status"), "Should filter by status");
        assert!(
            sql.contains("us.observed_at_ms"),
            "Should filter by timestamp"
        );
    }

    #[tokio::test]
    async fn test_fetch_filtered_http_headers_empty() {
        // Test fetch_filtered_http_headers with no matching headers
        let pool = create_test_pool().await;
        let pool_arc = Arc::new(pool);

        // Create a table for headers (simplified schema)
        sqlx::query(
            "CREATE TABLE IF NOT EXISTS url_http_headers (
                id INTEGER PRIMARY KEY,
                url_status_id INTEGER NOT NULL,
                header_name TEXT NOT NULL,
                header_value TEXT NOT NULL
            )",
        )
        .execute(&*pool_arc)
        .await
        .unwrap();

        let (result, count) = fetch_filtered_http_headers(
            &pool_arc,
            HttpHeadersTable::Standard,
            999,
            &["Content-Type", "Server"],
        )
        .await
        .expect("Should succeed with empty result");

        assert_eq!(result, "");
        assert_eq!(count, 0);
    }

    #[tokio::test]
    async fn test_fetch_filtered_http_headers_with_matches() {
        // Test fetch_filtered_http_headers with matching headers
        let pool = create_test_pool().await;
        let pool_arc = Arc::new(pool);

        // Create a table for headers
        sqlx::query(
            "CREATE TABLE IF NOT EXISTS url_http_headers (
                id INTEGER PRIMARY KEY,
                url_status_id INTEGER NOT NULL,
                header_name TEXT NOT NULL,
                header_value TEXT NOT NULL
            )",
        )
        .execute(&*pool_arc)
        .await
        .unwrap();

        // Insert headers (some matching, some not)
        sqlx::query("INSERT INTO url_http_headers (url_status_id, header_name, header_value) VALUES (1, 'Content-Type', 'text/html'), (1, 'Server', 'nginx'), (1, 'X-Custom', 'value')")
            .execute(&*pool_arc)
            .await
            .unwrap();

        let (result, total_count) = fetch_filtered_http_headers(
            &pool_arc,
            HttpHeadersTable::Standard,
            1,
            &["Content-Type", "Server"],
        )
        .await
        .expect("Should succeed");

        // Result should contain only filtered headers (Content-Type and Server)
        assert!(result.contains("Content-Type:text/html"));
        assert!(result.contains("Server:nginx"));
        assert!(!result.contains("X-Custom")); // Should not include non-filtered header
                                               // Total count should be 3 (all headers), but result string only has filtered ones
        assert_eq!(total_count, 3);
    }

    #[test]
    fn test_ignore_broken_pipe_write() {
        // Test that IgnoreBrokenPipe handles broken pipe errors gracefully
        // This is critical - allows graceful shutdown when piped to commands that exit early
        use std::io::ErrorKind;

        struct BrokenPipeWriter;

        impl Write for BrokenPipeWriter {
            fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
                Err(io::Error::new(ErrorKind::BrokenPipe, "Broken pipe"))
            }

            fn flush(&mut self) -> io::Result<()> {
                Ok(())
            }
        }

        let mut wrapper = IgnoreBrokenPipe::new(BrokenPipeWriter);
        let test_data = b"test data";

        // Should not return error for broken pipe
        let result = wrapper.write(test_data);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), test_data.len());
    }

    #[test]
    fn test_ignore_broken_pipe_flush() {
        // Test that IgnoreBrokenPipe handles broken pipe errors in flush
        use std::io::ErrorKind;

        struct BrokenPipeWriter;

        impl Write for BrokenPipeWriter {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                Ok(buf.len())
            }

            fn flush(&mut self) -> io::Result<()> {
                Err(io::Error::new(ErrorKind::BrokenPipe, "Broken pipe"))
            }
        }

        let mut wrapper = IgnoreBrokenPipe::new(BrokenPipeWriter);

        // Should not return error for broken pipe in flush
        let result = wrapper.flush();
        assert!(result.is_ok());
    }

    #[test]
    fn test_ignore_broken_pipe_other_errors_propagate() {
        // Test that non-broken-pipe errors are still propagated
        // This is critical - we only want to ignore broken pipe, not all errors
        use std::io::ErrorKind;

        struct ErrorWriter;

        impl Write for ErrorWriter {
            fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
                Err(io::Error::new(
                    ErrorKind::PermissionDenied,
                    "Permission denied",
                ))
            }

            fn flush(&mut self) -> io::Result<()> {
                Ok(())
            }
        }

        let mut wrapper = IgnoreBrokenPipe::new(ErrorWriter);
        let test_data = b"test data";

        // Should propagate non-broken-pipe errors
        let result = wrapper.write(test_data);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().kind(), ErrorKind::PermissionDenied);
    }

    #[tokio::test]
    async fn test_fetch_key_value_list_with_colon_in_value() {
        // Test that fetch_key_value_list handles colons in values correctly
        // This is critical - values like "https://example.com" contain colons
        // The code at line 100 formats as "key:value", so colons in values are preserved
        let pool = create_test_pool().await;
        let pool_arc = Arc::new(pool);

        sqlx::query("INSERT INTO url_analytics_ids (url_status_id, provider, tracking_id) VALUES (1, 'Google Analytics', 'https://example.com/UA-12345')")
            .execute(&*pool_arc)
            .await
            .unwrap();

        let (result, count) = fetch_key_value_list(
            &pool_arc,
            "SELECT provider, tracking_id FROM url_analytics_ids WHERE url_status_id = ?",
            "provider",
            "tracking_id",
            1,
        )
        .await
        .expect("Should succeed");

        // Should preserve colon in value
        assert!(result.contains("Google Analytics:https://example.com/UA-12345"));
        assert_eq!(count, 1);
    }

    #[tokio::test]
    async fn test_fetch_key_value_list_with_empty_value() {
        // Test that fetch_key_value_list handles empty values correctly
        let pool = create_test_pool().await;
        let pool_arc = Arc::new(pool);

        sqlx::query("INSERT INTO url_analytics_ids (url_status_id, provider, tracking_id) VALUES (1, 'Test', '')")
            .execute(&*pool_arc)
            .await
            .unwrap();

        let (result, count) = fetch_key_value_list(
            &pool_arc,
            "SELECT provider, tracking_id FROM url_analytics_ids WHERE url_status_id = ?",
            "provider",
            "tracking_id",
            1,
        )
        .await
        .expect("Should succeed");

        // Should format as "key:" (empty value)
        assert_eq!(result, "Test:");
        assert_eq!(count, 1);
    }
}