esi 0.6.2

A streaming parser and executor for Edge Side Includes
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
use crate::{ExecutionError, Result};
use log::debug;
use quick_xml::events::{BytesStart, Event as XmlEvent};
use quick_xml::name::QName;
use quick_xml::Reader;
use std::io::BufRead;
use std::ops::Deref;

// State carrier of Try branch
#[derive(Debug, PartialEq)]
enum TryTagArms {
    Try,
    Attempt,
    Except,
}

/// Representation of an ESI tag from a source response.
#[derive(Debug)]
pub struct Include {
    pub src: String,
    pub alt: Option<String>,
    pub continue_on_error: bool,
}

/// Represents a tag in the ESI parsing process.
#[derive(Debug)]
pub enum Tag<'a> {
    Include {
        src: String,
        alt: Option<String>,
        continue_on_error: bool,
    },
    Try {
        attempt_events: Vec<Event<'a>>,
        except_events: Vec<Event<'a>>,
    },
    Assign {
        name: String,
        value: String,
    },
    Vars {
        name: Option<String>,
    },
    When {
        test: String,
        match_name: Option<String>,
    },
    Choose {
        when_branches: Vec<(Tag<'a>, Vec<Event<'a>>)>,
        otherwise_events: Vec<Event<'a>>,
    },
}

/// Representation of either XML data or a parsed ESI tag.
#[derive(Debug)]
#[allow(clippy::upper_case_acronyms)]
pub enum Event<'e> {
    Content(XmlEvent<'e>),
    InterpolatedContent(XmlEvent<'e>),
    ESI(Tag<'e>),
}

// #[derive(Debug)]
struct TagNames {
    include: Vec<u8>,
    comment: Vec<u8>,
    remove: Vec<u8>,
    r#try: Vec<u8>,
    attempt: Vec<u8>,
    except: Vec<u8>,
    assign: Vec<u8>,
    vars: Vec<u8>,
    choose: Vec<u8>,
    when: Vec<u8>,
    otherwise: Vec<u8>,
}
impl TagNames {
    fn init(namespace: &str) -> Self {
        Self {
            include: format!("{namespace}:include",).into_bytes(),
            comment: format!("{namespace}:comment",).into_bytes(),
            remove: format!("{namespace}:remove",).into_bytes(),
            r#try: format!("{namespace}:try",).into_bytes(),
            attempt: format!("{namespace}:attempt",).into_bytes(),
            except: format!("{namespace}:except",).into_bytes(),
            assign: format!("{namespace}:assign",).into_bytes(),
            vars: format!("{namespace}:vars",).into_bytes(),
            choose: format!("{namespace}:choose",).into_bytes(),
            when: format!("{namespace}:when",).into_bytes(),
            otherwise: format!("{namespace}:otherwise",).into_bytes(),
        }
    }
}

#[derive(Debug, PartialEq)]
enum ContentType {
    Normal,
    Interpolated,
}

fn do_parse<'a, R>(
    reader: &mut Reader<R>,
    callback: &mut dyn FnMut(Event<'a>) -> Result<()>,
    task: &mut Vec<Event<'a>>,
    use_queue: bool,
    try_depth: &mut usize,
    choose_depth: &mut usize,
    current_arm: &mut Option<TryTagArms>,
    tag: &TagNames,
    content_type: &ContentType,
) -> Result<()>
where
    R: BufRead,
{
    let mut is_remove_tag = false;
    let mut open_include = false;
    let mut open_assign = false;
    let mut open_vars = false;

    let attempt_events = &mut Vec::new();
    let except_events = &mut Vec::new();

    // choose/when variables
    let when_branches = &mut Vec::new();
    let otherwise_events = &mut Vec::new();

    let mut buffer = Vec::new();

    // When you are in the top level of a try or choose block, the
    // only allowable tags are attempt/except or when/otherwise. All
    // other data should be eaten.
    let mut in_try = false;
    let mut in_choose = false;

    // Parse tags and build events vec
    loop {
        match reader.read_event_into(&mut buffer) {
            // Handle <esi:remove> tags
            Ok(XmlEvent::Start(e)) if e.name() == QName(&tag.remove) => {
                is_remove_tag = true;
            }

            Ok(XmlEvent::End(e)) if e.name() == QName(&tag.remove) => {
                if !is_remove_tag {
                    return unexpected_closing_tag_error(&e);
                }

                is_remove_tag = false;
            }
            _ if is_remove_tag => continue,

            // Handle <esi:include> tags, and ignore the contents if they are not self-closing
            Ok(XmlEvent::Empty(e)) if e.name().into_inner().starts_with(&tag.include) => {
                include_tag_handler(&e, callback, task, use_queue)?;
            }

            Ok(XmlEvent::Start(e)) if e.name().into_inner().starts_with(&tag.include) => {
                open_include = true;
                include_tag_handler(&e, callback, task, use_queue)?;
            }

            Ok(XmlEvent::End(e)) if e.name().into_inner().starts_with(&tag.include) => {
                if !open_include {
                    return unexpected_closing_tag_error(&e);
                }

                open_include = false;
            }

            _ if open_include => continue,

            // Ignore <esi:comment> tags
            Ok(XmlEvent::Empty(e)) if e.name().into_inner().starts_with(&tag.comment) => continue,

            // Handle <esi:try> tags
            Ok(XmlEvent::Start(ref e)) if e.name() == QName(&tag.r#try) => {
                *current_arm = Some(TryTagArms::Try);
                *try_depth += 1;
                in_try = true;
                continue;
            }

            // Handle <esi:attempt> and <esi:except> tags in recursion
            Ok(XmlEvent::Start(ref e))
                if e.name() == QName(&tag.attempt) || e.name() == QName(&tag.except) =>
            {
                if *current_arm != Some(TryTagArms::Try) {
                    return unexpected_opening_tag_error(e);
                }
                if e.name() == QName(&tag.attempt) {
                    *current_arm = Some(TryTagArms::Attempt);
                    do_parse(
                        reader,
                        callback,
                        attempt_events,
                        true,
                        try_depth,
                        choose_depth,
                        current_arm,
                        tag,
                        &ContentType::Interpolated,
                    )?;
                } else if e.name() == QName(&tag.except) {
                    *current_arm = Some(TryTagArms::Except);
                    do_parse(
                        reader,
                        callback,
                        except_events,
                        true,
                        try_depth,
                        choose_depth,
                        current_arm,
                        tag,
                        &ContentType::Interpolated,
                    )?;
                }
            }

            Ok(XmlEvent::End(ref e)) if e.name() == QName(&tag.r#try) => {
                *current_arm = None;
                in_try = false;

                if *try_depth == 0 {
                    return unexpected_closing_tag_error(e);
                }
                try_end_handler(use_queue, task, attempt_events, except_events, callback)?;
                *try_depth -= 1;
                continue;
            }

            Ok(XmlEvent::End(ref e))
                if e.name() == QName(&tag.attempt) || e.name() == QName(&tag.except) =>
            {
                *current_arm = Some(TryTagArms::Try);
                if *try_depth == 0 {
                    return unexpected_closing_tag_error(e);
                }
                return Ok(());
            }

            // Handle <esi:assign> tags, and ignore the contents if they are not self-closing
            // TODO: assign tags have a long form where the contents are interpolated and assigned to the variable
            Ok(XmlEvent::Empty(e)) if e.name().into_inner().starts_with(&tag.assign) => {
                assign_tag_handler(&e, callback, task, use_queue)?;
            }

            Ok(XmlEvent::Start(e)) if e.name().into_inner().starts_with(&tag.assign) => {
                open_assign = true;
                assign_tag_handler(&e, callback, task, use_queue)?;
            }

            Ok(XmlEvent::End(e)) if e.name().into_inner().starts_with(&tag.assign) => {
                if !open_assign {
                    return unexpected_closing_tag_error(&e);
                }

                open_assign = false;
            }

            // Handle <esi:vars> tags
            Ok(XmlEvent::Empty(e)) if e.name().into_inner().starts_with(&tag.vars) => {
                vars_tag_handler(&e, callback, task, use_queue)?;
            }

            Ok(XmlEvent::Start(e)) if e.name().into_inner().starts_with(&tag.vars) => {
                open_vars = true;
                vars_tag_handler(&e, callback, task, use_queue)?;
            }

            Ok(XmlEvent::End(e)) if e.name().into_inner().starts_with(&tag.vars) => {
                if !open_vars {
                    return unexpected_closing_tag_error(&e);
                }

                open_vars = false;
            }

            // when/choose
            Ok(XmlEvent::Start(ref e)) if e.name() == QName(&tag.choose) => {
                in_choose = true;
                *choose_depth += 1;
            }
            Ok(XmlEvent::End(ref e)) if e.name() == QName(&tag.choose) => {
                in_choose = false;
                *choose_depth -= 1;
                choose_tag_handler(when_branches, otherwise_events, callback, task, use_queue)?;
            }

            Ok(XmlEvent::Start(ref e)) if e.name() == QName(&tag.when) => {
                if *choose_depth == 0 {
                    // invalid when tag outside of choose
                    return unexpected_opening_tag_error(e);
                }

                let when_tag = parse_when(e)?;
                let mut when_events = Vec::new();
                do_parse(
                    reader,
                    callback,
                    &mut when_events,
                    true,
                    try_depth,
                    choose_depth,
                    current_arm,
                    tag,
                    &ContentType::Interpolated,
                )?;
                when_branches.push((when_tag, when_events));
            }
            Ok(XmlEvent::End(e)) if e.name() == QName(&tag.when) => {
                if *choose_depth == 0 {
                    return unexpected_closing_tag_error(&e);
                }

                return Ok(());
            }

            Ok(XmlEvent::Start(ref e)) if e.name() == QName(&tag.otherwise) => {
                if *choose_depth == 0 {
                    return unexpected_opening_tag_error(e);
                }
                do_parse(
                    reader,
                    callback,
                    otherwise_events,
                    true,
                    try_depth,
                    choose_depth,
                    current_arm,
                    tag,
                    &ContentType::Interpolated,
                )?;
            }
            Ok(XmlEvent::End(e)) if e.name() == QName(&tag.otherwise) => {
                if *choose_depth == 0 {
                    return unexpected_closing_tag_error(&e);
                }
                return Ok(());
            }

            Ok(XmlEvent::Eof) => {
                debug!("End of document");
                break;
            }
            Ok(e) => {
                if in_try || in_choose {
                    continue;
                }

                let event = if open_vars || content_type == &ContentType::Interpolated {
                    Event::InterpolatedContent(e.into_owned())
                } else {
                    Event::Content(e.into_owned())
                };
                if use_queue {
                    task.push(event);
                } else {
                    callback(event)?;
                }
            }
            _ => {}
        }
    }
    Ok(())
}

/// Parses an XML/HTML document looking for ESI tags in the specified namespace
///
/// This function reads from a buffered reader source and processes XML/HTML events,
/// calling the provided callback for each event that matches an ESI tag.
///
/// # Arguments
/// * `namespace` - The XML namespace to use for ESI tags (e.g. "esi")
/// * `reader` - Buffered reader containing the XML/HTML document to parse
/// * `callback` - Function called for each matching ESI tag event
///
/// # Returns
/// * `Result<()>` - Ok if parsing completed successfully, or Error if parsing failed
///
/// # Example
/// ```
/// use esi::{Reader, parse_tags};
///
/// let xml = r#"<esi:include src="http://example.com/footer.html"/>"#;
/// let mut reader = Reader::from_str(xml);
/// let mut callback = |event| { Ok(()) };
/// parse_tags("esi", &mut reader, &mut callback)?;
///
/// # Ok::<(), esi::ExecutionError>(())
/// ```
/// # Errors
/// Returns an `ExecutionError` if there is an error reading or parsing the document.
pub fn parse_tags<'a, R>(
    namespace: &str,
    reader: &mut Reader<R>,
    callback: &mut dyn FnMut(Event<'a>) -> Result<()>,
) -> Result<()>
where
    R: BufRead,
{
    debug!("Parsing document...");

    // Initialize the ESI tags
    let tags = TagNames::init(namespace);
    // set the initial depth of nested tags
    let mut try_depth = 0;
    let mut choose_depth = 0;
    let mut root = Vec::new();

    let mut current_arm: Option<TryTagArms> = None;

    do_parse(
        reader,
        callback,
        &mut root,
        false,
        &mut try_depth,
        &mut choose_depth,
        &mut current_arm,
        &tags,
        &ContentType::Normal,
    )?;
    debug!("Root: {root:?}");

    Ok(())
}

fn parse_include<'a>(elem: &BytesStart) -> Result<Tag<'a>> {
    let src = match elem
        .attributes()
        .flatten()
        .find(|attr| attr.key.into_inner() == b"src")
    {
        Some(attr) => String::from_utf8(attr.value.to_vec()).unwrap(),
        None => {
            return Err(ExecutionError::MissingRequiredParameter(
                String::from_utf8(elem.name().into_inner().to_vec()).unwrap(),
                "src".to_string(),
            ));
        }
    };

    let alt = elem
        .attributes()
        .flatten()
        .find(|attr| attr.key.into_inner() == b"alt")
        .map(|attr| String::from_utf8(attr.value.to_vec()).unwrap());

    let continue_on_error = elem
        .attributes()
        .flatten()
        .find(|attr| attr.key.into_inner() == b"onerror")
        .is_some_and(|attr| &attr.value.to_vec() == b"continue");

    Ok(Tag::Include {
        src,
        alt,
        continue_on_error,
    })
}

fn parse_assign<'a>(elem: &BytesStart) -> Result<Tag<'a>> {
    let name = match elem
        .attributes()
        .flatten()
        .find(|attr| attr.key.into_inner() == b"name")
    {
        Some(attr) => String::from_utf8(attr.value.to_vec()).unwrap(),
        None => {
            return Err(ExecutionError::MissingRequiredParameter(
                String::from_utf8(elem.name().into_inner().to_vec()).unwrap(),
                "name".to_string(),
            ));
        }
    };

    let value = match elem
        .attributes()
        .flatten()
        .find(|attr| attr.key.into_inner() == b"value")
    {
        Some(attr) => String::from_utf8(attr.value.to_vec()).unwrap(),
        None => {
            return Err(ExecutionError::MissingRequiredParameter(
                String::from_utf8(elem.name().into_inner().to_vec()).unwrap(),
                "value".to_string(),
            ));
        }
    };

    Ok(Tag::Assign { name, value })
}

fn parse_vars<'a>(elem: &BytesStart) -> Result<Tag<'a>> {
    let name = elem
        .attributes()
        .flatten()
        .find(|attr| attr.key.into_inner() == b"name")
        .map(|attr| String::from_utf8(attr.value.to_vec()).unwrap());

    Ok(Tag::Vars { name })
}

fn parse_when<'a>(elem: &BytesStart) -> Result<Tag<'a>> {
    let test = match elem
        .attributes()
        .flatten()
        .find(|attr| attr.key.into_inner() == b"test")
    {
        Some(attr) => String::from_utf8(attr.value.to_vec()).unwrap(),
        None => {
            return Err(ExecutionError::MissingRequiredParameter(
                String::from_utf8(elem.name().into_inner().to_vec()).unwrap(),
                "test".to_string(),
            ));
        }
    };

    let match_name = elem
        .attributes()
        .flatten()
        .find(|attr| attr.key.into_inner() == b"matchname")
        .map(|attr| String::from_utf8(attr.value.to_vec()).unwrap());

    Ok(Tag::When { test, match_name })
}

// Helper function to handle the end of a <esi:try> tag
// If the depth is 1, the `callback` closure is called with the `Tag::Try` event
// Otherwise, a new `Tag::Try` event is pushed to the `task` vector
fn try_end_handler<'a>(
    use_queue: bool,
    task: &mut Vec<Event<'a>>,
    attempt_events: &mut Vec<Event<'a>>,
    except_events: &mut Vec<Event<'a>>,
    callback: &mut dyn FnMut(Event<'a>) -> Result<()>,
) -> Result<()> {
    if use_queue {
        task.push(Event::ESI(Tag::Try {
            attempt_events: std::mem::take(attempt_events),
            except_events: std::mem::take(except_events),
        }));
    } else {
        callback(Event::ESI(Tag::Try {
            attempt_events: std::mem::take(attempt_events),
            except_events: std::mem::take(except_events),
        }))?;
    }

    Ok(())
}

// Helper function to handle <esi:include> tags
// If the depth is 0, the `callback` closure is called with the `Tag::Include` event
// Otherwise, a new `Tag::Include` event is pushed to the `task` vector
fn include_tag_handler<'e>(
    elem: &BytesStart,
    callback: &mut dyn FnMut(Event<'e>) -> Result<()>,
    task: &mut Vec<Event<'e>>,
    use_queue: bool,
) -> Result<()> {
    if use_queue {
        task.push(Event::ESI(parse_include(elem)?));
    } else {
        callback(Event::ESI(parse_include(elem)?))?;
    }

    Ok(())
}

// Helper function to handle <esi:assign> tags
// If the depth is 0, the `callback` closure is called with the `Tag::Assign` event
// Otherwise, a new `Tag::Assign` event is pushed to the `task` vector
fn assign_tag_handler<'e>(
    elem: &BytesStart,
    callback: &mut dyn FnMut(Event<'e>) -> Result<()>,
    task: &mut Vec<Event<'e>>,
    use_queue: bool,
) -> Result<()> {
    if use_queue {
        task.push(Event::ESI(parse_assign(elem)?));
    } else {
        callback(Event::ESI(parse_assign(elem)?))?;
    }

    Ok(())
}

// Helper function to handle <esi:vars> tags
// If the depth is 0, the `callback` closure is called with the `Tag::Assign` event
// Otherwise, a new `Tag::Vars` event is pushed to the `task` vector
fn vars_tag_handler<'e>(
    elem: &BytesStart,
    callback: &mut dyn FnMut(Event<'e>) -> Result<()>,
    task: &mut Vec<Event<'e>>,
    use_queue: bool,
) -> Result<()> {
    debug!("Handling <esi:vars> tag");
    let tag = parse_vars(elem)?;
    debug!("Parsed <esi:vars> tag: {tag:?}");
    if use_queue {
        task.push(Event::ESI(parse_vars(elem)?));
    } else {
        callback(Event::ESI(parse_vars(elem)?))?;
    }

    Ok(())
}

fn choose_tag_handler<'a>(
    when_branches: &mut Vec<(Tag<'a>, Vec<Event<'a>>)>,
    otherwise_events: &mut Vec<Event<'a>>,
    callback: &mut dyn FnMut(Event<'a>) -> Result<()>,
    task: &mut Vec<Event<'a>>,
    use_queue: bool,
) -> Result<()> {
    let choose_tag = Tag::Choose {
        when_branches: std::mem::take(when_branches),
        otherwise_events: std::mem::take(otherwise_events),
    };
    if use_queue {
        task.push(Event::ESI(choose_tag));
    } else {
        callback(Event::ESI(choose_tag))?;
    }

    Ok(())
}

// Helper function return UnexpectedClosingTag error
fn unexpected_closing_tag_error<T>(e: &T) -> Result<()>
where
    T: Deref<Target = [u8]>,
{
    Err(ExecutionError::UnexpectedClosingTag(
        String::from_utf8_lossy(e).to_string(),
    ))
}

// Helper function return UnexpectedClosingTag error
fn unexpected_opening_tag_error<T>(e: &T) -> Result<()>
where
    T: Deref<Target = [u8]>,
{
    Err(ExecutionError::UnexpectedOpeningTag(
        String::from_utf8_lossy(e).to_string(),
    ))
}