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
use crate::{
    borrowed::raw::{UnvalidatedLogline as UnvalidatedRaw, ValidatedLogline as ValidatedRaw},
    shared::*,
    types::*,
    CHRONO_DATE_FMT, CHRONO_TIME_FMT,
};

pub use crate::types::{Datelike, Timelike};

// todo: write correct schema!
pub const SCHEMA: &str = r#"message rust_schema {
    REQUIRED boolean         a_bool;
    REQUIRED BINARY          a_str (STRING);
    REQUIRED BINARY          a_string (STRING);
    REQUIRED BINARY          a_borrowed_string (STRING);
    OPTIONAL BINARY          maybe_a_str (STRING);
    OPTIONAL BINARY          maybe_a_string (STRING);
    REQUIRED INT32           i16 (INTEGER(16,true));
    REQUIRED INT32           i32;
    REQUIRED INT64           u64 (INTEGER(64,false));
    OPTIONAL INT32           maybe_u8 (INTEGER(8,false));
    OPTIONAL INT32           maybe_i16 (INTEGER(16,true));
    OPTIONAL INT32           maybe_u32 (INTEGER(32,false));
    OPTIONAL INT64           maybe_usize (INTEGER(64,false));
    REQUIRED INT64           isize (INTEGER(64,true));
    REQUIRED FLOAT           float;
    REQUIRED DOUBLE          double;
    OPTIONAL FLOAT           maybe_float;
    OPTIONAL DOUBLE          maybe_double;
    OPTIONAL BINARY          borrowed_maybe_a_string (STRING);
    OPTIONAL BINARY          borrowed_maybe_a_str (STRING);
    REQUIRED INT64           now (TIMESTAMP_MILLIS);
    REQUIRED FIXED_LEN_BYTE_ARRAY (16) uuid (UUID);
    REQUIRED BINARY          byte_vec;
    OPTIONAL BINARY          maybe_byte_vec;
    REQUIRED BINARY          borrowed_byte_vec;
    OPTIONAL BINARY          borrowed_maybe_byte_vec;
    OPTIONAL BINARY          borrowed_maybe_borrowed_byte_vec;
}"#;

/// The validated log line for [`parquet`] usage
///
/// Most fields are parsed into more meaningful types.
/// Unfortunately, [`parquet_derive`] does not support all the types;
/// thus we lower some fields down to:
/// * &str / Option<&str> (instead of enums, NaiveTime, IpAddr)
/// * f64 (instead of Duration)
///
/// On construction it checks if the line can be parsed.
/// This is useful if you cannot skip the comment lines or have reason to not trust the input for format correctness.
/// The latter should be only an issue if you do not use this crate on CloudFront logs directly.
///
/// # Panics
///
/// Construction can panic if the input is not a valid log line!
///
/// # Examples
///
/// Use `.try_from()` or `.try_into()` to construct an instance, since action can fail.
///
/// ```rust
/// use cloudfront_logs::{borrowed::parquet::ValidatedLogline, types::*};
///
/// let line = "2019-12-04	21:02:31	LAX1	392	192.0.2.100	GET	d111111abcdef8.cloudfront.net	/index.html	200	-	Mozilla/5.0%20(Windows%20NT%2010.0;%20Win64;%20x64)%20AppleWebKit/537.36%20(KHTML,%20like%20Gecko)%20Chrome/78.0.3904.108%20Safari/537.36	-	-	Hit	SOX4xwn4XV6Q4rgb7XiVGOHms_BGlTAC4KyHmureZmBNrjGdRLiNIQ==	d111111abcdef8.cloudfront.net	https	23	0.001	-	TLSv1.2	ECDHE-RSA-AES128-GCM-SHA256	Hit	HTTP/2.0	-	-	11040	0.001	Hit	text/html	78	-	-";
///
/// let item = ValidatedLogline::try_from(line).unwrap();
/// // alternative:
/// let item: ValidatedLogline<'_> = line.try_into().unwrap();
///
/// assert_eq!(item.date, NaiveDate::from_ymd_opt(2019, 12, 4).unwrap());
/// assert_eq!(item.sc_bytes, 392u64);
/// assert_eq!(item.cs_protocol, "https");
/// ```
#[must_use]
#[derive(Debug, Clone, PartialEq, parquet_derive::ParquetRecordWriter)]
pub struct ValidatedLogline<'a> {
    pub date: NaiveDate,
    pub time: &'a str, // not supported: NaiveTime
    pub datetime: NaiveDateTime,
    pub x_edge_location: &'a str,
    pub sc_bytes: u64,
    pub c_ip: &'a str,
    pub cs_method: &'a str,
    pub cs_host: &'a str,
    pub cs_uri_stem: &'a str,
    pub sc_status: u16,
    pub cs_referer: Option<&'a str>,
    pub cs_user_agent: &'a str,
    pub cs_uri_query: Option<&'a str>,
    pub cs_cookie: Option<&'a str>,
    pub x_edge_result_type: &'a str,
    pub x_edge_request_id: &'a str,
    pub x_host_header: &'a str,
    pub cs_protocol: &'a str,
    pub cs_bytes: u64,
    pub time_taken: f64,
    pub x_forwarded_for: Option<&'a str>,
    pub ssl_protocol: Option<&'a str>,
    pub ssl_cipher: Option<&'a str>,
    pub x_edge_response_result_type: &'a str,
    pub cs_protocol_version: &'a str,
    pub fle_status: Option<&'a str>,
    pub fle_encrypted_fields: Option<u64>,
    pub c_port: u16,
    pub time_to_first_byte: f64,
    pub x_edge_detailed_result_type: &'a str,
    pub sc_content_type: &'a str,
    pub sc_content_len: u64,
    pub sc_range_start: Option<u64>,
    pub sc_range_end: Option<u64>,
}

impl<'a> TryFrom<&'a str> for ValidatedLogline<'a> {
    type Error = &'static str;

    #[must_use]
    fn try_from(line: &'a str) -> Result<Self, Self::Error> {
        validate_line(line)?;
        let mut iter = MemchrTabSplitter::new(line);

        let date = NaiveDate::parse_from_str(iter.next().unwrap(), CHRONO_DATE_FMT)
            .map_err(|_| "date invalid")?;
        let raw_time = iter.next().unwrap();
        let time =
            NaiveTime::parse_from_str(raw_time, CHRONO_TIME_FMT).map_err(|_| "time invalid")?;
        let datetime = NaiveDateTime::new(date, time);

        let line = Self {
            date,
            time: raw_time,
            datetime,
            x_edge_location: iter.next().unwrap(),
            sc_bytes: iter
                .next()
                .unwrap()
                .parse::<u64>()
                .map_err(|_| "sc_bytes invalid")?,
            c_ip: iter.next().unwrap(),
            cs_method: iter.next().unwrap(),
            cs_host: iter.next().unwrap(),
            cs_uri_stem: iter.next().unwrap(),
            sc_status: iter
                .next()
                .unwrap()
                .parse::<u16>()
                .map_err(|_| "sc_status invalid")?,
            cs_referer: iter.next().and_then(str::as_optional_str),
            cs_user_agent: iter.next().unwrap(),
            cs_uri_query: iter.next().and_then(str::as_optional_str),
            cs_cookie: iter.next().and_then(str::as_optional_str),
            x_edge_result_type: iter.next().unwrap(),
            x_edge_request_id: iter.next().unwrap(),
            x_host_header: iter.next().unwrap(),
            cs_protocol: iter.next().unwrap(),
            cs_bytes: iter
                .next()
                .unwrap()
                .parse::<u64>()
                .map_err(|_| "cs_bytes invalid")?,
            time_taken: iter
                .next()
                .unwrap()
                .parse::<f64>()
                .map_err(|_| "time_taken invalid")?,
            x_forwarded_for: iter.next().and_then(str::as_optional_str),
            ssl_protocol: iter.next().and_then(str::as_optional_str),
            ssl_cipher: iter.next().and_then(str::as_optional_str),
            x_edge_response_result_type: iter.next().unwrap(),
            cs_protocol_version: iter.next().unwrap(),
            fle_status: iter.next().and_then(str::as_optional_str),
            fle_encrypted_fields: iter
                .next()
                .and_then(as_optional_t)
                .transpose()
                .map_err(|_| "fle_encrypted_fields invalid")?,
            c_port: iter
                .next()
                .unwrap()
                .parse::<u16>()
                .map_err(|_| "c_port invalid")?,
            time_to_first_byte: iter
                .next()
                .unwrap()
                .parse::<f64>()
                .map_err(|_| "time_to_first_byte invalid")?,
            x_edge_detailed_result_type: iter.next().unwrap(),
            sc_content_type: iter.next().unwrap(),
            sc_content_len: iter
                .next()
                .unwrap()
                .parse::<u64>()
                .map_err(|_| "sc_content_len invalid")?,
            sc_range_start: iter
                .next()
                .and_then(as_optional_t)
                .transpose()
                .map_err(|_| "sc_range_start invalid")?,
            sc_range_end: iter
                .next()
                .and_then(as_optional_t)
                .transpose()
                .map_err(|_| "sc_range_end invalid")?,
        };
        Ok(line)
    }
}

impl<'a> TryFrom<ValidatedRaw<'a>> for ValidatedLogline<'a> {
    type Error = &'static str;

    #[must_use]
    fn try_from(raw: ValidatedRaw<'a>) -> Result<Self, Self::Error> {
        let date =
            NaiveDate::parse_from_str(raw.date, CHRONO_DATE_FMT).map_err(|_| "date invalid")?;
        let time =
            NaiveTime::parse_from_str(raw.time, CHRONO_TIME_FMT).map_err(|_| "time invalid")?;
        let datetime = NaiveDateTime::new(date, time);

        let line = Self {
            date,
            time: raw.time,
            datetime,
            x_edge_location: raw.x_edge_location,
            sc_bytes: raw
                .sc_bytes
                .parse::<u64>()
                .map_err(|_| "sc_bytes invalid")?,
            c_ip: raw.c_ip,
            cs_method: raw.cs_method,
            cs_host: raw.cs_host,
            cs_uri_stem: raw.cs_uri_stem,
            sc_status: raw
                .sc_status
                .parse::<u16>()
                .map_err(|_| "sc_status invalid")?,
            cs_referer: raw.cs_referer.as_optional_str(),
            cs_user_agent: raw.cs_user_agent,
            cs_uri_query: raw.cs_uri_query.as_optional_str(),
            cs_cookie: raw.cs_cookie.as_optional_str(),
            x_edge_result_type: raw.x_edge_result_type,
            x_edge_request_id: raw.x_edge_request_id,
            x_host_header: raw.x_host_header,
            cs_protocol: raw.cs_protocol,
            cs_bytes: raw
                .cs_bytes
                .parse::<u64>()
                .map_err(|_| "cs_bytes invalid")?,
            time_taken: raw
                .time_taken
                .parse::<f64>()
                .map_err(|_| "time_taken invalid")?,
            x_forwarded_for: raw.x_forwarded_for.as_optional_str(),
            ssl_protocol: raw.ssl_protocol.as_optional_str(),
            ssl_cipher: raw.ssl_cipher.as_optional_str(),
            x_edge_response_result_type: raw.x_edge_response_result_type,
            cs_protocol_version: raw.cs_protocol_version,
            fle_status: raw.fle_status.as_optional_str(),
            fle_encrypted_fields: parse_as_option(raw.fle_encrypted_fields)
                .map_err(|_| "fle_encrypted_fields invalid")?,
            c_port: raw.c_port.parse::<u16>().map_err(|_| "c_port invalid")?,
            time_to_first_byte: raw
                .time_to_first_byte
                .parse::<f64>()
                .map_err(|_| "time_to_first_byte invalid")?,
            x_edge_detailed_result_type: raw.x_edge_detailed_result_type,
            sc_content_type: raw.sc_content_type,
            sc_content_len: raw
                .sc_content_len
                .parse::<u64>()
                .map_err(|_| "sc_content_len invalid")?,
            sc_range_start: parse_as_option(raw.sc_range_start)
                .map_err(|_| "sc_range_start invalid")?,
            sc_range_end: parse_as_option(raw.sc_range_end).map_err(|_| "sc_range_end invalid")?,
        };
        Ok(line)
    }
}

/// The unvalidated log line for [`parquet`] usage
///
/// Most fields are parsed into more meaningful types.
///
/// Unlike [`ValidatedLogline`], this variant does not check if the line can be parsed.
/// Use this if you already did a check before creating this struct.
/// A common scenario is that you 1) trust the input data and 2) skipped the comment lines.
///
/// Note: This is the only variant which can use the `From` trait instead of `TryFrom`,
/// because validation is skipped and the input data does not need to be parsed into other types.
///
/// # Panics
///
/// Construction can panic if the input is not a valid log line!
///
/// # Examples
///
/// Use `.try_from()` or `.try_into()` to construct an instance, since action can fail.
///
/// ```rust
/// use cloudfront_logs::{borrowed::parquet::UnvalidatedLogline, types::*};
///
/// let line = "2019-12-04	21:02:31	LAX1	392	192.0.2.100	GET	d111111abcdef8.cloudfront.net	/index.html	200	-	Mozilla/5.0%20(Windows%20NT%2010.0;%20Win64;%20x64)%20AppleWebKit/537.36%20(KHTML,%20like%20Gecko)%20Chrome/78.0.3904.108%20Safari/537.36	-	-	Hit	SOX4xwn4XV6Q4rgb7XiVGOHms_BGlTAC4KyHmureZmBNrjGdRLiNIQ==	d111111abcdef8.cloudfront.net	https	23	0.001	-	TLSv1.2	ECDHE-RSA-AES128-GCM-SHA256	Hit	HTTP/2.0	-	-	11040	0.001	Hit	text/html	78	-	-";
///
/// let item = UnvalidatedLogline::try_from(line).unwrap();
/// // alternative:
/// let item: UnvalidatedLogline<'_> = line.try_into().unwrap();
///
/// assert_eq!(item.date, NaiveDate::from_ymd_opt(2019, 12, 4).unwrap());
/// assert_eq!(item.sc_bytes, 392u64);
/// assert_eq!(item.cs_protocol, "https");
/// ```
#[must_use]
#[derive(Debug, Clone, PartialEq, parquet_derive::ParquetRecordWriter)]
pub struct UnvalidatedLogline<'a> {
    pub date: NaiveDate,
    pub time: &'a str, // not supported: NaiveTime
    pub datetime: NaiveDateTime,
    pub x_edge_location: &'a str,
    pub sc_bytes: u64,
    pub c_ip: &'a str,
    pub cs_method: &'a str,
    pub cs_host: &'a str,
    pub cs_uri_stem: &'a str,
    pub sc_status: u16,
    pub cs_referer: Option<&'a str>,
    pub cs_user_agent: &'a str,
    pub cs_uri_query: Option<&'a str>,
    pub cs_cookie: Option<&'a str>,
    pub x_edge_result_type: &'a str,
    pub x_edge_request_id: &'a str,
    pub x_host_header: &'a str,
    pub cs_protocol: &'a str,
    pub cs_bytes: u64,
    pub time_taken: f64,
    pub x_forwarded_for: Option<&'a str>,
    pub ssl_protocol: Option<&'a str>,
    pub ssl_cipher: Option<&'a str>,
    pub x_edge_response_result_type: &'a str,
    pub cs_protocol_version: &'a str,
    pub fle_status: Option<&'a str>,
    pub fle_encrypted_fields: Option<u64>,
    pub c_port: u16,
    pub time_to_first_byte: f64,
    pub x_edge_detailed_result_type: &'a str,
    pub sc_content_type: &'a str,
    pub sc_content_len: u64,
    pub sc_range_start: Option<u64>,
    pub sc_range_end: Option<u64>,
}

impl<'a> TryFrom<&'a str> for UnvalidatedLogline<'a> {
    type Error = &'static str;

    #[must_use]
    fn try_from(line: &'a str) -> Result<Self, Self::Error> {
        let mut iter = MemchrTabSplitter::new(line);

        let date = NaiveDate::parse_from_str(iter.next().unwrap(), "%Y-%m-%d")
            .map_err(|_| "date invalid")?;
        let raw_time = iter.next().unwrap();
        let time = NaiveTime::parse_from_str(raw_time, "%H:%M:%S").map_err(|_| "time invalid")?;
        let datetime = NaiveDateTime::new(date, time);

        let line = Self {
            date,
            time: raw_time,
            datetime,
            x_edge_location: iter.next().unwrap(),
            sc_bytes: iter
                .next()
                .unwrap()
                .parse::<u64>()
                .map_err(|_| "sc_bytes invalid")?,
            c_ip: iter.next().unwrap(),
            cs_method: iter.next().unwrap(),
            cs_host: iter.next().unwrap(),
            cs_uri_stem: iter.next().unwrap(),
            sc_status: iter
                .next()
                .unwrap()
                .parse::<u16>()
                .map_err(|_| "sc_status invalid")?,
            cs_referer: iter.next().and_then(str::as_optional_str),
            cs_user_agent: iter.next().unwrap(),
            cs_uri_query: iter.next().and_then(str::as_optional_str),
            cs_cookie: iter.next().and_then(str::as_optional_str),
            x_edge_result_type: iter.next().unwrap(),
            x_edge_request_id: iter.next().unwrap(),
            x_host_header: iter.next().unwrap(),
            cs_protocol: iter.next().unwrap(),
            cs_bytes: iter
                .next()
                .unwrap()
                .parse::<u64>()
                .map_err(|_| "cs_bytes invalid")?,
            time_taken: iter
                .next()
                .unwrap()
                .parse::<f64>()
                .map_err(|_| "time_taken invalid")?,
            x_forwarded_for: iter.next().and_then(str::as_optional_str),
            ssl_protocol: iter.next().and_then(str::as_optional_str),
            ssl_cipher: iter.next().and_then(str::as_optional_str),
            x_edge_response_result_type: iter.next().unwrap(),
            cs_protocol_version: iter.next().unwrap(),
            fle_status: iter.next().and_then(str::as_optional_str),
            fle_encrypted_fields: iter
                .next()
                .and_then(as_optional_t)
                .transpose()
                .map_err(|_| "fle_encrypted_fields invalid")?,
            c_port: iter
                .next()
                .unwrap()
                .parse::<u16>()
                .map_err(|_| "c_port invalid")?,
            time_to_first_byte: iter
                .next()
                .unwrap()
                .parse::<f64>()
                .map_err(|_| "time_to_first_byte invalid")?,
            x_edge_detailed_result_type: iter.next().unwrap(),
            sc_content_type: iter.next().unwrap(),
            sc_content_len: iter
                .next()
                .unwrap()
                .parse::<u64>()
                .map_err(|_| "sc_content_len invalid")?,
            sc_range_start: iter
                .next()
                .and_then(as_optional_t)
                .transpose()
                .map_err(|_| "sc_range_start invalid")?,
            sc_range_end: iter
                .next()
                .and_then(as_optional_t)
                .transpose()
                .map_err(|_| "sc_range_end invalid")?,
        };
        Ok(line)
    }
}

impl<'a> TryFrom<UnvalidatedRaw<'a>> for UnvalidatedLogline<'a> {
    type Error = &'static str;

    #[must_use]
    fn try_from(raw: UnvalidatedRaw<'a>) -> Result<Self, Self::Error> {
        let date =
            NaiveDate::parse_from_str(raw.date, CHRONO_DATE_FMT).map_err(|_| "date invalid")?;
        let time =
            NaiveTime::parse_from_str(raw.time, CHRONO_TIME_FMT).map_err(|_| "time invalid")?;
        let datetime = NaiveDateTime::new(date, time);

        let line = Self {
            date,
            time: raw.time,
            datetime,
            x_edge_location: raw.x_edge_location,
            sc_bytes: raw
                .sc_bytes
                .parse::<u64>()
                .map_err(|_| "sc_bytes invalid")?,
            c_ip: raw.c_ip,
            cs_method: raw.cs_method,
            cs_host: raw.cs_host,
            cs_uri_stem: raw.cs_uri_stem,
            sc_status: raw
                .sc_status
                .parse::<u16>()
                .map_err(|_| "sc_status invalid")?,
            cs_referer: raw.cs_referer.as_optional_str(),
            cs_user_agent: raw.cs_user_agent,
            cs_uri_query: raw.cs_uri_query.as_optional_str(),
            cs_cookie: raw.cs_cookie.as_optional_str(),
            x_edge_result_type: raw.x_edge_result_type,
            x_edge_request_id: raw.x_edge_request_id,
            x_host_header: raw.x_host_header,
            cs_protocol: raw.cs_protocol,
            cs_bytes: raw
                .cs_bytes
                .parse::<u64>()
                .map_err(|_| "cs_bytes invalid")?,
            time_taken: raw
                .time_taken
                .parse::<f64>()
                .map_err(|_| "time_taken invalid")?,
            x_forwarded_for: raw.x_forwarded_for.as_optional_str(),
            ssl_protocol: raw.ssl_protocol.as_optional_str(),
            ssl_cipher: raw.ssl_cipher.as_optional_str(),
            x_edge_response_result_type: raw.x_edge_response_result_type,
            cs_protocol_version: raw.cs_protocol_version,
            fle_status: raw.fle_status.as_optional_str(),
            fle_encrypted_fields: parse_as_option(raw.fle_encrypted_fields)
                .map_err(|_| "fle_encrypted_fields invalid")?,
            c_port: raw.c_port.parse::<u16>().map_err(|_| "c_port invalid")?,
            time_to_first_byte: raw
                .time_to_first_byte
                .parse::<f64>()
                .map_err(|_| "time_to_first_byte invalid")?,
            x_edge_detailed_result_type: raw.x_edge_detailed_result_type,
            sc_content_type: raw.sc_content_type,
            sc_content_len: raw
                .sc_content_len
                .parse::<u64>()
                .map_err(|_| "sc_content_len invalid")?,
            sc_range_start: parse_as_option(raw.sc_range_start)
                .map_err(|_| "sc_range_start invalid")?,
            sc_range_end: parse_as_option(raw.sc_range_end).map_err(|_| "sc_range_end invalid")?,
        };
        Ok(line)
    }
}

impl<'a> TryFrom<ValidatedRaw<'a>> for UnvalidatedLogline<'a> {
    type Error = &'static str;

    #[must_use]
    fn try_from(raw: ValidatedRaw<'a>) -> Result<Self, Self::Error> {
        let date =
            NaiveDate::parse_from_str(raw.date, CHRONO_DATE_FMT).map_err(|_| "date invalid")?;
        let time =
            NaiveTime::parse_from_str(raw.time, CHRONO_TIME_FMT).map_err(|_| "time invalid")?;
        let datetime = NaiveDateTime::new(date, time);

        let line = Self {
            date,
            time: raw.time,
            datetime,
            x_edge_location: raw.x_edge_location,
            sc_bytes: raw
                .sc_bytes
                .parse::<u64>()
                .map_err(|_| "sc_bytes invalid")?,
            c_ip: raw.c_ip,
            cs_method: raw.cs_method,
            cs_host: raw.cs_host,
            cs_uri_stem: raw.cs_uri_stem,
            sc_status: raw
                .sc_status
                .parse::<u16>()
                .map_err(|_| "sc_status invalid")?,
            cs_referer: raw.cs_referer.as_optional_str(),
            cs_user_agent: raw.cs_user_agent,
            cs_uri_query: raw.cs_uri_query.as_optional_str(),
            cs_cookie: raw.cs_cookie.as_optional_str(),
            x_edge_result_type: raw.x_edge_result_type,
            x_edge_request_id: raw.x_edge_request_id,
            x_host_header: raw.x_host_header,
            cs_protocol: raw.cs_protocol,
            cs_bytes: raw
                .cs_bytes
                .parse::<u64>()
                .map_err(|_| "cs_bytes invalid")?,
            time_taken: raw
                .time_taken
                .parse::<f64>()
                .map_err(|_| "time_taken invalid")?,
            x_forwarded_for: raw.x_forwarded_for.as_optional_str(),
            ssl_protocol: raw.ssl_protocol.as_optional_str(),
            ssl_cipher: raw.ssl_cipher.as_optional_str(),
            x_edge_response_result_type: raw.x_edge_response_result_type,
            cs_protocol_version: raw.cs_protocol_version,
            fle_status: raw.fle_status.as_optional_str(),
            fle_encrypted_fields: parse_as_option(raw.fle_encrypted_fields)
                .map_err(|_| "fle_encrypted_fields invalid")?,
            c_port: raw.c_port.parse::<u16>().map_err(|_| "c_port invalid")?,
            time_to_first_byte: raw
                .time_to_first_byte
                .parse::<f64>()
                .map_err(|_| "time_to_first_byte invalid")?,
            x_edge_detailed_result_type: raw.x_edge_detailed_result_type,
            sc_content_type: raw.sc_content_type,
            sc_content_len: raw
                .sc_content_len
                .parse::<u64>()
                .map_err(|_| "sc_content_len invalid")?,
            sc_range_start: parse_as_option(raw.sc_range_start)
                .map_err(|_| "sc_range_start invalid")?,
            sc_range_end: parse_as_option(raw.sc_range_end).map_err(|_| "sc_range_end invalid")?,
        };
        Ok(line)
    }
}

impl<'a> From<ValidatedLogline<'a>> for UnvalidatedLogline<'a> {
    #[must_use]
    fn from(validated: ValidatedLogline<'a>) -> Self {
        UnvalidatedLogline {
            date: validated.date,
            time: validated.time,
            datetime: validated.datetime,
            x_edge_location: validated.x_edge_location,
            sc_bytes: validated.sc_bytes,
            c_ip: validated.c_ip,
            cs_method: validated.cs_method,
            cs_host: validated.cs_host,
            cs_uri_stem: validated.cs_uri_stem,
            sc_status: validated.sc_status,
            cs_referer: validated.cs_referer,
            cs_user_agent: validated.cs_user_agent,
            cs_uri_query: validated.cs_uri_query,
            cs_cookie: validated.cs_cookie,
            x_edge_result_type: validated.x_edge_result_type,
            x_edge_request_id: validated.x_edge_request_id,
            x_host_header: validated.x_host_header,
            cs_protocol: validated.cs_protocol,
            cs_bytes: validated.cs_bytes,
            time_taken: validated.time_taken,
            x_forwarded_for: validated.x_forwarded_for,
            ssl_protocol: validated.ssl_protocol,
            ssl_cipher: validated.ssl_cipher,
            x_edge_response_result_type: validated.x_edge_response_result_type,
            cs_protocol_version: validated.cs_protocol_version,
            fle_status: validated.fle_status,
            fle_encrypted_fields: validated.fle_encrypted_fields,
            c_port: validated.c_port,
            time_to_first_byte: validated.time_to_first_byte,
            x_edge_detailed_result_type: validated.x_edge_detailed_result_type,
            sc_content_type: validated.sc_content_type,
            sc_content_len: validated.sc_content_len,
            sc_range_start: validated.sc_range_start,
            sc_range_end: validated.sc_range_end,
        }
    }
}

impl<'a> From<UnvalidatedLogline<'a>> for ValidatedLogline<'a> {
    #[must_use]
    fn from(unvalidated: UnvalidatedLogline<'a>) -> Self {
        ValidatedLogline {
            date: unvalidated.date,
            time: unvalidated.time,
            datetime: unvalidated.datetime,
            x_edge_location: unvalidated.x_edge_location,
            sc_bytes: unvalidated.sc_bytes,
            c_ip: unvalidated.c_ip,
            cs_method: unvalidated.cs_method,
            cs_host: unvalidated.cs_host,
            cs_uri_stem: unvalidated.cs_uri_stem,
            sc_status: unvalidated.sc_status,
            cs_referer: unvalidated.cs_referer,
            cs_user_agent: unvalidated.cs_user_agent,
            cs_uri_query: unvalidated.cs_uri_query,
            cs_cookie: unvalidated.cs_cookie,
            x_edge_result_type: unvalidated.x_edge_result_type,
            x_edge_request_id: unvalidated.x_edge_request_id,
            x_host_header: unvalidated.x_host_header,
            cs_protocol: unvalidated.cs_protocol,
            cs_bytes: unvalidated.cs_bytes,
            time_taken: unvalidated.time_taken,
            x_forwarded_for: unvalidated.x_forwarded_for,
            ssl_protocol: unvalidated.ssl_protocol,
            ssl_cipher: unvalidated.ssl_cipher,
            x_edge_response_result_type: unvalidated.x_edge_response_result_type,
            cs_protocol_version: unvalidated.cs_protocol_version,
            fle_status: unvalidated.fle_status,
            fle_encrypted_fields: unvalidated.fle_encrypted_fields,
            c_port: unvalidated.c_port,
            time_to_first_byte: unvalidated.time_to_first_byte,
            x_edge_detailed_result_type: unvalidated.x_edge_detailed_result_type,
            sc_content_type: unvalidated.sc_content_type,
            sc_content_len: unvalidated.sc_content_len,
            sc_range_start: unvalidated.sc_range_start,
            sc_range_end: unvalidated.sc_range_end,
        }
    }
}