tor-config 0.42.0

Low-level configuration for the Arti Tor implementation
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
//! Helper for defining sub-builders that map a serializable type (typically String)
//! to a configuration type.

/// Define a map type, and an associated builder struct, suitable for use in a configuration object.
///
/// We use this macro when we want a configuration structure to contain a key-to-value map,
/// and therefore we want its associated builder structure to contain
/// a map from the same key type to a value-builder type.
///
/// The key of the map type must implement `Serialize`, `Clone`, and `Debug`.
/// The value of the map type must have an associated "Builder"
/// type formed by appending `Builder` to its name.
/// This Builder type must implement `Serialize`, `Deserialize`, `Clone`, and `Debug`,
/// and it must have a `build(&self)` method returning `Result<value, ConfigBuildError>`.
///
/// # Syntax and behavior
///
/// ```ignore
/// define_map_builder! {
///     BuilderAttributes
///     pub struct BuilderName =>
///
///     MapAttributes
///     pub type MapName = ContainerType<KeyType, ValueType>;
///
///     defaults: defaults_func(); // <--- this line is optional
/// }
/// ```
///
/// In the example above,
///
/// * BuilderName, MapName, and ContainerType may be replaced with any identifier;
/// * BuilderAttributes and MapAttributes can be replaced with any set of attributes
///   (such sa doc comments, `#derive`, and so on);
/// * The `pub`s may be replaced with any visibility;
/// * and `KeyType` and `ValueType` may be replaced with any appropriate types.
///    * `ValueType` must have a corresponding `ValueTypeBuilder`.
///    * `ValueTypeBuilder` must implement
///      [`ExtendBuilder`](crate::extend_builder::ExtendBuilder).
///
/// Given this syntax, this macro will define "MapType" as an alias for
/// `Container<KeyType,ValueType>`,
/// and "BuilderName" as a builder type for that container.
///
/// "BuilderName" will implement:
///  * `Deref` and `DerefMut` with a target type of `Container<KeyType, ValueTypeBuilder>`
///  * `Default`, `Clone`, and `Debug`.
///  * `Serialize` and `Deserialize`
///  * A `build()` function that invokes `build()` on every value in its contained map.
///
/// (Note that in order to work as a sub-builder within our configuration system,
/// "BuilderName" should be the same as "MapName" concatenated with "Builder.")
///
/// The `defaults_func()`, if provided, must be
/// a function returning `ContainerType<KeyType, ValueType>`.
/// The values returned by `default_func()` map are used to implement
/// `Default` and `Deserialize` for `BuilderName`,
/// extending from the defaults with `ExtendStrategy::ReplaceLists`.
/// If no `defaults_func` is given, `ContainerType::default()` is used.
///
/// # Example
///
/// ```
/// # use derive_builder::Builder;
/// # use derive_deftly::Deftly;
/// # use std::collections::BTreeMap;
/// # use tor_config::{ConfigBuildError, define_map_builder, derive_deftly_template_ExtendBuilder};
/// # use serde::{Serialize, Deserialize};
/// # use tor_config::extend_builder::{ExtendBuilder,ExtendStrategy};
/// #[derive(Clone, Debug, Builder, Deftly, Eq, PartialEq)]
/// #[derive_deftly(ExtendBuilder)]
/// #[builder(build_fn(error = "ConfigBuildError"))]
/// #[builder(derive(Debug, Serialize, Deserialize))]
/// pub struct ConnectionsConfig {
///     #[builder(sub_builder)]
///     #[deftly(extend_builder(sub_builder))]
///     conns: ConnectionMap
/// }
///
/// define_map_builder! {
///     pub struct ConnectionMapBuilder =>
///     pub type ConnectionMap = BTreeMap<String, ConnConfig>;
/// }
///
/// #[derive(Clone, Debug, Builder, Deftly, Eq, PartialEq)]
/// #[derive_deftly(ExtendBuilder)]
/// #[builder(build_fn(error = "ConfigBuildError"))]
/// #[builder(derive(Debug, Serialize, Deserialize))]
/// pub struct ConnConfig {
///     #[builder(default="true")]
///     enabled: bool,
///     port: u16,
/// }
///
/// let defaults: ConnectionsConfigBuilder = toml::from_str(r#"
/// [conns."socks"]
/// enabled = true
/// port = 9150
///
/// [conns."http"]
/// enabled = false
/// port = 1234
///
/// [conns."wombat"]
/// port = 5050
/// "#).unwrap();
/// let user_settings: ConnectionsConfigBuilder = toml::from_str(r#"
/// [conns."http"]
/// enabled = false
/// [conns."quokka"]
/// enabled = true
/// port = 9999
/// "#).unwrap();
///
/// let mut cfg = defaults.clone();
/// cfg.extend_from(user_settings, ExtendStrategy::ReplaceLists);
/// let cfg = cfg.build().unwrap();
/// assert_eq!(cfg, ConnectionsConfig {
///     conns: vec![
///         ("http".into(), ConnConfig { enabled: false, port: 1234}),
///         ("quokka".into(), ConnConfig { enabled: true, port: 9999}),
///         ("socks".into(), ConnConfig { enabled: true, port: 9150}),
///         ("wombat".into(), ConnConfig { enabled: true, port: 5050}),
///     ].into_iter().collect(),
/// });
/// ```
///
/// In the example above, the `derive_map_builder` macro expands to something like:
///
/// ```ignore
/// pub type ConnectionMap = BTreeMap<String, ConnConfig>;
///
/// #[derive(Clone,Debug,Serialize,Educe)]
/// #[educe(Deref,DerefMut)]
/// pub struct ConnectionMapBuilder(BTreeMap<String, ConnConfigBuilder);
///
/// impl ConnectionMapBuilder {
///     fn build(&self) -> Result<ConnectionMap, ConfigBuildError> {
///         ...
///     }
/// }
/// impl Default for ConnectionMapBuilder { ... }
/// impl Deserialize for ConnectionMapBuilder { ... }
/// impl ExtendBuilder for ConnectionMapBuilder { ... }
/// ```
///
/// # Notes and rationale
///
/// We use this macro, instead of using a Map directly in our configuration object,
/// so that we can have a separate Builder type with a reasonable build() implementation.
///
/// We don't support complicated keys; instead we require that the keys implement Deserialize.
/// If we ever need to support keys with their own builders,
/// we'll have to define a new macro.
///
/// We use `ExtendBuilder` to implement Deserialize with defaults,
/// so that the provided configuration options can override
/// only those parts of the default configuration tree
/// that they actually replace.
#[macro_export]
macro_rules! define_map_builder {
    {
        $(#[ $b_m:meta ])*
        $b_v:vis struct $btype:ident =>
        $(#[ $m:meta ])*
        $v:vis type $maptype:ident = $coltype:ident < $keytype:ty , $valtype: ty >;
        $( defaults: $defaults:expr; )?
    } => {
        $crate::deps::paste!{$crate::define_map_builder! {
            $(#[$b_m])*
            $b_v struct $btype =>
            $(#[$m])*
            $v type $maptype = {
                map: $coltype < $keytype , $valtype >,
                builder_map: $coltype < $keytype, [<$valtype Builder>] > ,
            }
            $( defaults: $defaults; )?
        }}
    };
    // This _undocumented_ internal syntax allows us to take the map types explicitly,
    // so that we can accept derive-deftly outputs.
    //
    // Syntax:
    // ```
    //   «#[builder_attrs]»
    //   «vis» struct «FooMapBuilder» =>
    //   «#[maptype_attrs]»
    //   «vis» type «FooMap» = {
    //       map: «maptype»,
    //       builder_map: «builder_map_type»,
    //   }
    //   ⟦ defaults: «default_expr» ; ⟧
    // ```
    //
    // The defaults line and the attributes are optional.
    // This (undocumented) syntax is identical to the documented variant above,
    // except in the braced section after the `=` and before the optional `defaults`.
    // In that section,
    // the `maptype` is the type of the map which we are trying to build,
    // (for example, `HashMap<String, WombatCfg>`),
    // and the `builder_map` is the type of the map which instantiates the builder
    // (for example, `HashMap<String, WombatCfgBuilder>`).
    {
        $(#[ $b_m:meta ])*
        $b_v:vis struct $btype:ident =>
        $(#[ $m:meta ])*
        $v:vis type $maptype:ident = {
            map: $mtype:ty,
            builder_map: $bmtype:ty $(,)?
        }
        $( defaults: $defaults:expr; )?
    } =>
    {$crate::deps::paste!{
        $(#[ $m ])*
        $v type $maptype = $mtype ;

        $(#[ $b_m ])*
        #[derive(Clone,Debug,$crate::deps::serde::Serialize, $crate::deps::educe::Educe)]
        #[educe(Deref, DerefMut)]
        #[serde(transparent)]
        $b_v struct $btype( $bmtype );

        impl $btype {
            /// Construct the final map.
            $b_v fn build(&self) -> ::std::result::Result<$maptype, $crate::ConfigBuildError> {
                self.0
                    .iter()
                    .map(|(k,v)| Ok((k.clone(), v.build()?)))
                    .collect()
            }
        }
        $(
            // This section is expanded when we have a defaults_fn().
            impl ::std::default::Default for $btype {
                fn default() -> Self {
                    Self($defaults)
                }
            }
            impl<'de> $crate::deps::serde::Deserialize<'de> for $btype {
                fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
                where
                    D: $crate::deps::serde::Deserializer<'de> {
                        use $crate::deps::serde::Deserialize;
                        // To deserialize into this type, we create a builder holding the defaults,
                        // and we create a builder holding the values from the deserializer.
                        // We then use ExtendBuilder to extend the defaults with the deserialized values.
                        let deserialized = <$bmtype as Deserialize>::deserialize(deserializer)?;
                        let mut defaults = $btype::default();
                        $crate::extend_builder::ExtendBuilder::extend_from(
                            &mut defaults,
                            Self(deserialized),
                            $crate::extend_builder::ExtendStrategy::ReplaceLists);
                        Ok(defaults)
                    }
            }
        )?
        $crate::define_map_builder!{@if_empty { $($defaults)? } {
            // This section is expanded when we don't have a defaults_fn().
            impl ::std::default::Default for $btype {
                fn default() -> Self {
                    Self(Default::default())
                }
            }
            // We can't conditionally derive() here, since Rust doesn't like macros that expand to
            // attributes.
            impl<'de> $crate::deps::serde::Deserialize<'de> for $btype {
                fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
                where
                    D: $crate::deps::serde::Deserializer<'de> {
                    use $crate::deps::serde::Deserialize;
                    Ok(Self(<$bmtype as Deserialize>::deserialize(deserializer)?))
                }
            }
        }}
        impl $crate::extend_builder::ExtendBuilder for $btype
        {
            fn extend_from(&mut self, other: Self, strategy: $crate::extend_builder::ExtendStrategy) {
                $crate::extend_builder::ExtendBuilder::extend_from(&mut self.0, other.0, strategy);
            }
        }
    }};
    {@if_empty {} {$($x:tt)*}} => {$($x)*};
    {@if_empty {$($y:tt)*} {$($x:tt)*}} => {};
}

#[cfg(test)]
mod test {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_time_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->

    use crate::ConfigBuildError;
    use derive_builder::Builder;
    use derive_deftly::Deftly;
    use serde::{Deserialize, Serialize};
    use std::collections::BTreeMap;

    #[derive(Clone, Debug, Eq, PartialEq, Builder)]
    #[builder(derive(Deserialize, Serialize, Debug))]
    #[builder(build_fn(error = "ConfigBuildError"))]
    struct Outer {
        #[builder(sub_builder(fn_name = "build"))]
        #[builder_field_attr(serde(default))]
        things: ThingMap,
    }

    #[derive(Clone, Debug, Eq, PartialEq, Builder, Deftly)]
    #[derive_deftly(ExtendBuilder)]
    #[builder(derive(Deserialize, Serialize, Debug))]
    #[builder(build_fn(error = "ConfigBuildError"))]
    struct Inner {
        #[builder(default)]
        fun: bool,
        #[builder(default)]
        explosive: bool,
    }

    define_map_builder! {
        struct ThingMapBuilder =>
        type ThingMap = BTreeMap<String, Inner>;
    }

    #[test]
    fn parse_and_build() {
        let builder: OuterBuilder = toml::from_str(
            r#"
[things.x]
fun = true
explosive = false

[things.yy]
explosive = true
fun = true
"#,
        )
        .unwrap();

        let built = builder.build().unwrap();
        assert_eq!(
            built.things.get("x").unwrap(),
            &Inner {
                fun: true,
                explosive: false
            }
        );
        assert_eq!(
            built.things.get("yy").unwrap(),
            &Inner {
                fun: true,
                explosive: true
            }
        );
    }

    #[test]
    fn build_directly() {
        let mut builder = OuterBuilder::default();
        let mut bld = InnerBuilder::default();
        bld.fun(true);
        builder.things().insert("x".into(), bld);
        let built = builder.build().unwrap();
        assert_eq!(
            built.things.get("x").unwrap(),
            &Inner {
                fun: true,
                explosive: false
            }
        );
    }

    define_map_builder! {
        struct ThingMap2Builder =>
        type ThingMap2 = BTreeMap<String, Inner>;
        defaults: thingmap2_default();
    }
    fn thingmap2_default() -> BTreeMap<String, InnerBuilder> {
        let mut map = BTreeMap::new();
        {
            let mut bld = InnerBuilder::default();
            bld.fun(true);
            map.insert("x".to_string(), bld);
        }
        {
            let mut bld = InnerBuilder::default();
            bld.explosive(true);
            map.insert("y".to_string(), bld);
        }
        map
    }
    #[test]
    fn with_defaults() {
        let mut tm2 = ThingMap2Builder::default();
        tm2.get_mut("x").unwrap().explosive(true);
        let mut bld = InnerBuilder::default();
        bld.fun(true);
        tm2.insert("zz".into(), bld);
        let built = tm2.build().unwrap();

        assert_eq!(
            built.get("x").unwrap(),
            &Inner {
                fun: true,
                explosive: true
            }
        );
        assert_eq!(
            built.get("y").unwrap(),
            &Inner {
                fun: false,
                explosive: true
            }
        );
        assert_eq!(
            built.get("zz").unwrap(),
            &Inner {
                fun: true,
                explosive: false
            }
        );

        let tm2: ThingMap2Builder = toml::from_str(
            r#"
            [x]
            explosive = true
            [zz]
            fun = true
            "#,
        )
        .unwrap();
        let built2 = tm2.build().unwrap();
        assert_eq!(built, built2);
    }
}