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
use std::fmt;

/// A LimitTracker enforces a particular limit within the parser. It keeps
/// track of utilization so that we can report how close to a limit we
/// approached over the lifetime of the tracker.
/// ```rust
/// use apollo_parser::Parser;
///
/// let query = "
/// {
///     animal
///     ...snackSelection
///     ... on Pet {
///       playmates {
///         count
///       }
///     }
/// }
/// ";
/// // Create a new instance of a parser given a query and a
/// // recursion limit
/// let parser = Parser::new(query).recursion_limit(4);
/// // Parse the query, and return a SyntaxTree.
/// let ast = parser.parse();
/// // Retrieve the limits
/// let usage = ast.recursion_limit();
/// // Print out some of the usage details to see what happened during
/// // our parse. `limit` just reports the limit we set, `high` is the
/// // high-water mark of recursion usage.
/// println!("{:?}", usage);
/// println!("{:?}", usage.limit);
/// println!("{:?}", usage.high);
/// // Check that are no errors. These are not part of the AST.
/// assert_eq!(0, ast.errors().len());
///
/// // Get the document root node
/// let doc = ast.document();
/// // ... continue
/// ```
#[derive(PartialEq, Eq, Clone, Copy)]
pub struct LimitTracker {
    current: usize,
    /// High Water mark for this limit
    pub high: usize,
    /// Limit.
    pub limit: usize,
}

impl Default for LimitTracker {
    fn default() -> Self {
        Self {
            current: 0,
            high: 0,
            limit: 4_096, // Recursion limit derived from router experimentation
        }
    }
}

impl LimitTracker {
    pub fn new(limit: usize) -> Self {
        Self {
            current: 0,
            high: 0,
            limit,
        }
    }

    pub fn limited(&self) -> bool {
        self.current > self.limit
    }

    pub fn consume(&mut self) {
        self.current += 1;
        if self.current > self.high {
            self.high = self.current;
        }
    }

    pub fn reset(&mut self) {
        self.current = 0;
    }
}

impl fmt::Debug for LimitTracker {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "recursion limit: {}, high: {}", self.limit, self.high)
    }
}