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
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

//! Mz-specific library for interacting with `tracing`.

use proptest::arbitrary::Arbitrary;
use proptest::prelude::{BoxedStrategy, Strategy};
use serde::{de, Deserialize, Serializer};
use std::fmt::Formatter;
use std::str::FromStr;
use tracing_subscriber::EnvFilter;

pub mod params;

#[derive(Debug, Clone)]
struct ValidatedEnvFilterString(String);

/// Wraps [`EnvFilter`] to provide a [`Clone`] implementation.
pub struct CloneableEnvFilter {
    filter: EnvFilter,
    validated: ValidatedEnvFilterString,
}

impl AsRef<EnvFilter> for CloneableEnvFilter {
    fn as_ref(&self) -> &EnvFilter {
        &self.filter
    }
}

impl From<CloneableEnvFilter> for EnvFilter {
    fn from(value: CloneableEnvFilter) -> Self {
        value.filter
    }
}

impl PartialEq for CloneableEnvFilter {
    fn eq(&self, other: &Self) -> bool {
        format!("{}", self) == format!("{}", other)
    }
}

impl Eq for CloneableEnvFilter {}

impl Clone for CloneableEnvFilter {
    fn clone(&self) -> Self {
        // TODO: implement Clone on `EnvFilter` upstream
        Self {
            // While EnvFilter has the undocumented property of roundtripping through
            // its String format, it seems safer to always create a new EnvFilter from
            // the same validated input when cloning.
            filter: EnvFilter::from_str(&self.validated.0).expect("validated"),
            validated: self.validated.clone(),
        }
    }
}

impl FromStr for CloneableEnvFilter {
    type Err = tracing_subscriber::filter::ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let filter: EnvFilter = s.parse()?;
        Ok(CloneableEnvFilter {
            filter,
            validated: ValidatedEnvFilterString(s.to_string()),
        })
    }
}

impl std::fmt::Display for CloneableEnvFilter {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.filter)
    }
}

impl std::fmt::Debug for CloneableEnvFilter {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.filter)
    }
}

impl Arbitrary for CloneableEnvFilter {
    type Strategy = BoxedStrategy<Self>;
    type Parameters = ();

    fn arbitrary_with(_: Self::Parameters) -> Self::Strategy {
        // there are much more complex EnvFilters we could try building if that seems
        // worthwhile to explore
        proptest::sample::select(vec!["info", "debug", "warn", "error", "off"])
            .prop_map(|x| CloneableEnvFilter::from_str(x).expect("valid EnvFilter"))
            .boxed()
    }
}

impl serde::Serialize for CloneableEnvFilter {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&format!("{}", self))
    }
}

impl<'de> Deserialize<'de> for CloneableEnvFilter {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Self::from_str(s.as_str()).map_err(|x| de::Error::custom(x.to_string()))
    }
}
use tracing_subscriber::filter::Directive;

/// Wraps [`Directive`] to provide a serde implementations.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct SerializableDirective(Directive);

impl From<SerializableDirective> for Directive {
    fn from(value: SerializableDirective) -> Self {
        value.0
    }
}

impl From<Directive> for SerializableDirective {
    fn from(value: Directive) -> Self {
        SerializableDirective(value)
    }
}

impl FromStr for SerializableDirective {
    type Err = tracing_subscriber::filter::ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let dir: Directive = s.parse()?;
        Ok(SerializableDirective(dir))
    }
}

impl std::fmt::Display for SerializableDirective {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Arbitrary for SerializableDirective {
    type Strategy = BoxedStrategy<Self>;
    type Parameters = ();

    fn arbitrary_with(_: Self::Parameters) -> Self::Strategy {
        // there are much more complex EnvFilters we could try building if that seems
        // worthwhile to explore
        proptest::sample::select(vec!["info", "debug", "warn", "error", "off"])
            .prop_map(|x| SerializableDirective::from_str(x).expect("valid Directive"))
            .boxed()
    }
}

impl serde::Serialize for SerializableDirective {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&format!("{}", self))
    }
}

impl<'de> Deserialize<'de> for SerializableDirective {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Self::from_str(s.as_str()).map_err(|x| de::Error::custom(x.to_string()))
    }
}

#[cfg(test)]
mod test {
    use crate::{CloneableEnvFilter, SerializableDirective};
    use std::str::FromStr;

    // TODO(guswynn): we probably want to test round-tripping through the
    // `RustType` impl as well

    #[mz_ore::test]
    fn roundtrips() {
        let filter = CloneableEnvFilter::from_str(
            "abc=debug,def=trace,[123],foo,baz[bar{a=b}]=debug,[{13=37}]=trace,info",
        )
        .expect("valid");
        assert_eq!(
            format!("{}", filter),
            format!(
                "{}",
                CloneableEnvFilter::from_str(&format!("{}", filter)).expect("valid")
            )
        );
    }

    #[mz_ore::test]
    fn roundtrips_directive() {
        let dir = SerializableDirective::from_str("abc=debug").expect("valid");
        assert_eq!(
            format!("{}", dir),
            format!(
                "{}",
                SerializableDirective::from_str(&format!("{}", dir)).expect("valid")
            )
        );
    }
}