slumber_core 5.3.0

Core library for Slumber. Not intended for external use.
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
//! Deserialization helpers for collection types. This does *not* use serde,
//! and instead relies on [saphyr] for YAML parsing and hand-written
//! deserialization. This allows us to provide much better error messages, and
//! also enables source span tracking.
//!
//! This module only provides deserialization; serialization is still handled
//! by serde/serde_yaml, because there's no need for error messages and the
//! derive macros are sufficient to generate the corresponding YAML.

use crate::{
    collection::{
        Authentication, Collection, Folder, Profile, ProfileId,
        QueryParameterValue, Recipe, RecipeBody, RecipeId, RecipeTree,
        ValueTemplate, recipe_tree::RecipeNode,
    },
    http::HttpMethod,
};
use indexmap::IndexMap;
use saphyr::{Scalar, YamlData};
use slumber_template::Template;
use slumber_util::{
    deserialize_enum, impl_deserialize_from,
    yaml::{
        self, DeserializeYaml, Expected, Field, LocatedError, SourceMap,
        SourcedYaml, StructDeserializer, yaml_parse_panic,
    },
};

impl_deserialize_from!(ProfileId, String);
impl_deserialize_from!(RecipeId, String);

impl DeserializeYaml for Collection {
    fn expected() -> Expected {
        Expected::Mapping
    }

    fn deserialize(
        yaml: SourcedYaml,
        source_map: &SourceMap,
    ) -> yaml::Result<Self> {
        let mut deserializer = StructDeserializer::new(yaml)?;

        // Drop all fields starting with `.`
        deserializer.mapping.retain(|key, _| {
            !key.data.as_str().is_some_and(|s| s.starts_with('.'))
        });

        let collection = Self {
            name: deserializer.get(Field::new("name").opt(), source_map)?,
            profiles: deserializer
                .get::<Adopt<_>>(Field::new("profiles").opt(), source_map)?
                .0,
            // Internally we call these recipes, but extensive market research
            // shows that `requests` is more intuitive to the user
            recipes: deserializer
                .get(Field::new("requests").opt(), source_map)?,
        };
        deserializer.done()?;
        Ok(collection)
    }
}

/// Deserialize a map of profiles. This needs a custom implementation because:
/// - To call [HasId::set_id] on each value
/// - We have to enforce that at most one profile is set as default
impl DeserializeYaml for Adopt<IndexMap<ProfileId, Profile>> {
    fn expected() -> Expected {
        Expected::Mapping
    }

    fn deserialize(
        mut yaml: SourcedYaml,
        source_map: &SourceMap,
    ) -> yaml::Result<Self> {
        yaml.drop_dot_fields();

        // Enforce that only one profile can be the default
        let mut default_profile: Option<ProfileId> = None;

        yaml.try_into_mapping()?
            .into_iter()
            .map(|(k, v)| {
                let value_location = v.location;
                let key = ProfileId::deserialize(k, source_map)?;
                let mut value = Profile::deserialize(v, source_map)?;
                value.set_id(key.clone());

                // Check if another profile is already the default
                if value.default {
                    if let Some(default) = default_profile.take() {
                        return Err(LocatedError::other(
                            CerealError::MultipleDefaultProfiles {
                                first: default,
                                second: key,
                            },
                            value_location,
                        ));
                    }

                    default_profile = Some(key.clone());
                }

                Ok((key, value))
            })
            .collect::<yaml::Result<_>>()
            .map(Adopt)
    }
}

impl DeserializeYaml for Profile {
    fn expected() -> Expected {
        Expected::Mapping
    }

    fn deserialize(
        yaml: SourcedYaml,
        source_map: &SourceMap,
    ) -> yaml::Result<Self> {
        let location = yaml.location.resolve(source_map);
        let mut deserializer = StructDeserializer::new(yaml)?;
        let profile = Self {
            id: ProfileId::default(), // Will be set by parent based on key
            location,
            name: deserializer.get(Field::new("name").opt(), source_map)?,
            default: deserializer
                .get(Field::new("default").opt(), source_map)?,
            data: deserializer.get(Field::new("data").opt(), source_map)?,
        };
        deserializer.done()?;
        Ok(profile)
    }
}

impl DeserializeYaml for RecipeTree {
    fn expected() -> Expected {
        Expected::Mapping
    }

    fn deserialize(
        yaml: SourcedYaml,
        source_map: &SourceMap,
    ) -> yaml::Result<Self> {
        let location = yaml.location;
        let recipes: Adopt<IndexMap<RecipeId, RecipeNode>> =
            Adopt::deserialize(yaml, source_map)?;
        // Build a tree from the map
        RecipeTree::new(recipes.0)
            .map_err(|error| LocatedError::other(error, location))
    }
}

/// Deserialize a map of profiles. This needs a custom implementation to call
/// [HasId::set_id] on each value. This is used for both the root `requests`
/// field and each inner folder.
impl DeserializeYaml for Adopt<IndexMap<RecipeId, RecipeNode>> {
    fn expected() -> Expected {
        Expected::Mapping
    }

    fn deserialize(
        yaml: SourcedYaml,
        source_map: &SourceMap,
    ) -> yaml::Result<Self> {
        yaml.try_into_mapping()?
            .into_iter()
            .map(|(k, v)| {
                let key = RecipeId::deserialize(k, source_map)?;
                let mut value = RecipeNode::deserialize(v, source_map)?;
                value.set_id(key.clone());
                Ok((key, value))
            })
            .collect::<yaml::Result<_>>()
            .map(Adopt)
    }
}

impl DeserializeYaml for RecipeNode {
    fn expected() -> Expected {
        Expected::Mapping
    }

    fn deserialize(
        yaml: SourcedYaml,
        source_map: &SourceMap,
    ) -> yaml::Result<Self> {
        // Recipe nodes are untagged enums. They're written very frequently,
        // have distinct required fields that we can key on, and there's minimal
        // risk that we'll need to add new variants. Forcing users to require a
        // tag on every node is annoying so we can just omit it.

        // Get a reference to the mapping without moving it
        let YamlData::Mapping(mapping) = &yaml.data else {
            return Err(LocatedError::unexpected(Expected::Mapping, yaml));
        };

        let has = |key| mapping.contains_key(&SourcedYaml::value_from_str(key));

        // Do a little heuristicking to guess what the variant is. This gives
        // slightly better error messages
        if has("method") || has("url") {
            Recipe::deserialize(yaml, source_map).map(RecipeNode::Recipe)
        } else if has("requests") {
            Folder::deserialize(yaml, source_map).map(RecipeNode::Folder)
        } else {
            Err(LocatedError::other(
                CerealError::UnknownRecipeNodeVariant,
                yaml.location,
            ))
        }
    }
}

impl DeserializeYaml for Recipe {
    fn expected() -> Expected {
        Expected::Mapping
    }

    fn deserialize(
        yaml: SourcedYaml,
        source_map: &SourceMap,
    ) -> yaml::Result<Self> {
        let location = yaml.location.resolve(source_map);
        let mut deserializer = StructDeserializer::new(yaml)?;
        let recipe = Recipe {
            id: RecipeId::default(), // Will be set by parent based on key
            location,
            name: deserializer.get(Field::new("name").opt(), source_map)?,
            persist: deserializer
                .get(Field::new("persist").or(true), source_map)?,
            method: deserializer.get(Field::new("method"), source_map)?,
            url: deserializer.get(Field::new("url"), source_map)?,
            body: deserializer.get(Field::new("body").opt(), source_map)?,
            authentication: deserializer
                .get(Field::new("authentication").opt(), source_map)?,
            query: deserializer.get(Field::new("query").opt(), source_map)?,
            // Lower-case all headers for consistency. HTTP/1.1 headers are
            // case-insensitive and HTTP/2 enforces lower casing.
            headers: deserializer
                .get::<IndexMap<String, Template>>(
                    Field::new("headers").opt(),
                    source_map,
                )?
                .into_iter()
                .map(|(k, v)| (k.to_lowercase(), v))
                .collect(),
        };
        deserializer.done()?;
        Ok(recipe)
    }
}

impl DeserializeYaml for Folder {
    fn expected() -> Expected {
        Expected::Mapping
    }

    fn deserialize(
        yaml: SourcedYaml,
        source_map: &SourceMap,
    ) -> yaml::Result<Self> {
        let location = yaml.location.resolve(source_map);
        let mut deserializer = StructDeserializer::new(yaml)?;
        let folder = Folder {
            id: RecipeId::default(), // Will be set by parent based on key
            location,
            name: deserializer.get(Field::new("name").opt(), source_map)?,
            // `requests` matches the root field name
            children: deserializer
                .get::<Adopt<_>>(Field::new("requests").opt(), source_map)?
                .0,
        };
        deserializer.done()?;
        Ok(folder)
    }
}

impl DeserializeYaml for HttpMethod {
    fn expected() -> Expected {
        Expected::String
    }

    fn deserialize(
        yaml: SourcedYaml,
        source_map: &SourceMap,
    ) -> yaml::Result<Self> {
        let location = yaml.location;
        let s = String::deserialize(yaml, source_map)?;
        s.parse()
            .map_err(|error| LocatedError::other(error, location))
    }
}

impl DeserializeYaml for QueryParameterValue {
    fn expected() -> Expected {
        Expected::OneOf(&[&Expected::String, &Expected::Sequence])
    }

    /// Deserialize from a single template or a list of templates
    fn deserialize(
        yaml: SourcedYaml,
        source_map: &SourceMap,
    ) -> yaml::Result<Self> {
        if yaml.data.is_sequence() {
            // Deserialize vec
            DeserializeYaml::deserialize(yaml, source_map).map(Self::Many)
        } else {
            // Deserialize template
            DeserializeYaml::deserialize(yaml, source_map).map(Self::One)
        }
    }
}

impl DeserializeYaml for Authentication {
    fn expected() -> Expected {
        Expected::Mapping
    }

    fn deserialize(
        yaml: SourcedYaml,
        source_map: &SourceMap,
    ) -> yaml::Result<Self> {
        deserialize_enum! {
            yaml,
            "basic" => |yaml: SourcedYaml| {
                let mut deserializer = StructDeserializer::new(yaml)?;
                Ok(Authentication::Basic {
                    username: deserializer.get(Field::new("username"), source_map)?,
                    password: deserializer.get(Field::new("password").opt(), source_map)?,
                })
            },
            "bearer" => |yaml: SourcedYaml| {
                let mut deserializer = StructDeserializer::new(yaml)?;
                Ok(Authentication::Bearer {
                    token: deserializer.get(Field::new("token"), source_map)?,
                })
            },
        }
    }
}

impl DeserializeYaml for RecipeBody {
    fn expected() -> Expected {
        Expected::OneOf(&[&Expected::String, &Expected::Mapping])
    }

    fn deserialize(
        yaml: SourcedYaml,
        source_map: &SourceMap,
    ) -> yaml::Result<Self> {
        /// Deserialize a struct with a single "data" field
        fn deserialize_data<T: DeserializeYaml>(
            yaml: SourcedYaml<'_>,
            source_map: &SourceMap,
        ) -> yaml::Result<T> {
            let mut deserializer = StructDeserializer::new(yaml)?;
            let data = deserializer.get(Field::new("data"), source_map)?;
            deserializer.done()?;
            Ok(data)
        }

        // Mapping deserializes as some sort of structured body. It should have
        // a `type` and `data` field
        if yaml.data.is_mapping() {
            deserialize_enum! {
                yaml,
                "json" => |yaml| {
                    Ok(Self::Json(deserialize_data(yaml, source_map)?))
                },
                "form_urlencoded" => |yaml| {
                    Ok(Self::FormUrlencoded(deserialize_data(yaml, source_map)?))
                },
                "form_multipart" => |yaml| {
                    Ok(Self::FormMultipart(deserialize_data(yaml, source_map)?))
                },
                "stream" => |yaml| {
                    Ok(Self::Stream(deserialize_data(yaml, source_map)?))
                },
            }
        } else {
            // Otherwise it's a raw body - deserialize as a template
            Template::deserialize(yaml, source_map).map(Self::Raw)
        }
    }
}

impl DeserializeYaml for ValueTemplate {
    fn expected() -> Expected {
        Expected::OneOf(&[
            &Expected::Null,
            &Expected::Boolean,
            &Expected::Number,
            &Expected::String,
            &Expected::Sequence,
            &Expected::Mapping,
        ])
    }

    fn deserialize(
        yaml: SourcedYaml,
        source_map: &SourceMap,
    ) -> yaml::Result<Self> {
        match yaml.data {
            YamlData::Representation(_, _, _)
            | YamlData::BadValue
            | YamlData::Alias(_) => yaml_parse_panic(),
            YamlData::Value(Scalar::Null) => Ok(Self::Null),
            YamlData::Value(Scalar::Boolean(b)) => Ok(Self::Boolean(b)),
            YamlData::Value(Scalar::Integer(i)) => Ok(Self::Integer(i)),
            YamlData::Value(Scalar::FloatingPoint(f)) => Ok(Self::Float(f.0)),
            // Parse string as a template
            YamlData::Value(Scalar::String(s)) => {
                // Template will be unpacked here if appropriate
                let template = s.parse::<Self>().map_err(|error| {
                    LocatedError::other(error, yaml.location)
                })?;
                Ok(template)
            }
            YamlData::Sequence(sequence) => {
                let values = sequence
                    .into_iter()
                    .map(|yaml| Self::deserialize(yaml, source_map))
                    .collect::<yaml::Result<_>>()?;
                Ok(Self::Array(values))
            }
            YamlData::Mapping(mapping) => {
                let fields = mapping
                    .into_iter()
                    .map(|(key, value)| {
                        let key = Template::deserialize(key, source_map)?;
                        let value = Self::deserialize(value, source_map)?;
                        Ok((key, value))
                    })
                    .collect::<yaml::Result<_>>()?;
                Ok(Self::Object(fields))
            }
            YamlData::Tagged(_, _) => {
                Err(LocatedError::unexpected(Self::expected(), yaml))
            }
        }
    }
}

/// A Slumber-specific error that can occur while deserializing a YAML value.
/// Generic YAML errors are defined in [slumber_util::yaml::YamlError]. This
/// only holds errors specific to collection deserialization.
#[derive(Debug, thiserror::Error)]
enum CerealError {
    #[error(
        "Cannot set profile `{second}` as default; `{first}` is already default"
    )]
    MultipleDefaultProfiles { first: ProfileId, second: ProfileId },

    /// We couldn't guess the variant of a recipe node based on its fields
    #[error(
        "Requests must have a `method` and `url` field; \
        folders must have a `requests` field"
    )]
    UnknownRecipeNodeVariant,
}

/// A type that has an `id` field. This is ripe for a derive macro, maybe a fun
/// project some day?
pub trait HasId {
    type Id;

    fn id(&self) -> &Self::Id;

    fn set_id(&mut self, id: Self::Id);
}

impl HasId for Profile {
    type Id = ProfileId;

    fn id(&self) -> &Self::Id {
        &self.id
    }

    fn set_id(&mut self, id: Self::Id) {
        self.id = id;
    }
}

impl HasId for RecipeNode {
    type Id = RecipeId;

    fn id(&self) -> &Self::Id {
        match self {
            Self::Folder(folder) => &folder.id,
            Self::Recipe(recipe) => &recipe.id,
        }
    }

    fn set_id(&mut self, id: Self::Id) {
        match self {
            Self::Folder(folder) => folder.id = id,
            Self::Recipe(recipe) => recipe.id = id,
        }
    }
}

impl HasId for Recipe {
    type Id = RecipeId;

    fn id(&self) -> &Self::Id {
        &self.id
    }

    fn set_id(&mut self, id: Self::Id) {
        self.id = id;
    }
}

/// Workaround for the orphan rule
#[derive(Debug, Default)]
struct Adopt<T>(T);

/// Predicate for skip_serializing_if
#[expect(clippy::trivially_copy_pass_by_ref)]
pub fn is_true(b: &bool) -> bool {
    *b
}

/// Predicate for skip_serializing_if
#[expect(clippy::trivially_copy_pass_by_ref)]
pub fn is_false(b: &bool) -> bool {
    !b
}

/// Expose this for RecipeTree's tests
#[cfg(test)]
pub use tests::deserialize_recipe_tree;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::collection::RecipeBody;
    use indexmap::indexmap;
    use rstest::rstest;
    use serde_json::json;
    use serde_yaml::Mapping;
    use slumber_util::{
        assert_err,
        yaml::{YamlErrorKind, deserialize_yaml, yaml_enum, yaml_mapping},
    };

    /// Test error cases for deserializing a profile map
    #[rstest]
    #[case::multiple_default(
        yaml_mapping([
            ("profile1", yaml_mapping([
                ("default", serde_yaml::Value::Bool(true)),
                ("data", yaml_mapping([("a", "1")]))
            ])),
            ("profile2", yaml_mapping([
                ("default", serde_yaml::Value::Bool(true)),
                ("data", yaml_mapping([("a", "2")]))
            ])),
        ]),
        "Cannot set profile `profile2` as default; `profile1` is already default",
    )]
    fn test_deserialize_profiles_error(
        #[case] yaml: impl Into<serde_yaml::Value>,
        #[case] expected_error: &str,
    ) {
        assert_err!(
            deserialize_yaml::<Adopt<IndexMap<ProfileId, Profile>>>(
                yaml.into()
            )
            .map_err(LocatedError::into_error),
            expected_error
        );
    }

    /// Test serializing and deserializing recipe bodies. Round trips should all
    /// be no-ops. We use serde_yaml instead of serde_test because the handling
    /// of enums is a bit different, and we specifically only care about YAML.
    #[rstest]
    #[case::raw(
        RecipeBody::Raw("{{ user_id }}".into()),
        "{{ user_id }}"
    )]
    #[case::json(
        RecipeBody::json(json!({"user": "{{ user_id }}"})).unwrap(),
        yaml_enum("json", [("data", yaml_mapping([("user", "{{ user_id }}")]))]),
    )]
    #[case::json_nested(
        RecipeBody::json(json!(r#"{"warning": "NOT an object"}"#)).unwrap(),
        yaml_enum("json", [("data", r#"{"warning": "NOT an object"}"#)]),
    )]
    #[case::form_urlencoded(
        RecipeBody::FormUrlencoded(indexmap! {
            "username".into() => "{{ username }}".into(),
            "password".into() => "{{ prompt('Password', sensitive=true) }}".into(),
        }),
        yaml_enum("form_urlencoded", [("data", yaml_mapping([
            ("username", "{{ username }}"),
            ("password", "{{ prompt('Password', sensitive=true) }}"),
        ]))]),
    )]
    fn test_serde_recipe_body(
        #[case] body: RecipeBody,
        #[case] yaml: impl Into<serde_yaml::Value>,
    ) {
        let yaml = yaml.into();
        assert_eq!(
            serde_yaml::to_value(&body).unwrap(),
            yaml,
            "Serialization mismatch"
        );
        assert_eq!(
            deserialize_yaml::<RecipeBody>(yaml).unwrap(),
            body,
            "Deserialization mismatch"
        );
    }

    /// Test various errors when deserializing a recipe body. We use serde_yaml
    /// instead of serde_test because the handling of enums is a bit different,
    /// and we specifically only care about YAML.
    #[rstest]
    #[case::array(
        Vec::<i32>::new(),
        "Expected string, received sequence"
    )]
    #[case::map(
        Mapping::default(),
        "Expected field `type` with one of \
        \"json\", \"form_urlencoded\", \"form_multipart\""
    )]
    // `Raw` variant is *not* accessible by tag
    #[case::raw_tag(
        yaml_enum("raw", [("data", "data")]),
        "Expected one of \"json\", \"form_urlencoded\", \"form_multipart\", \
        \"stream\", received \"raw\"",
    )]
    #[case::form_urlencoded_missing_data(
        yaml_enum("form_urlencoded", [] as [(_, serde_yaml::Value); 0]),
        "Expected field `data` with mapping"
    )]
    fn test_deserialize_recipe_body_error(
        #[case] yaml: impl Into<serde_yaml::Value>,
        #[case] expected_error: &str,
    ) {
        assert_err!(
            deserialize_yaml::<RecipeBody>(yaml.into())
                .map_err(LocatedError::into_error),
            expected_error
        );
    }

    /// Test deserializing an empty file. It should return an empty collection
    #[test]
    fn test_deserialize_empty() {
        assert_eq!(Collection::parse("").unwrap(), Collection::default());
    }

    /// Helper for deserializing in RecipeTree's tests. We export this
    pub fn deserialize_recipe_tree(
        yaml: serde_yaml::Value,
    ) -> Result<RecipeTree, YamlErrorKind> {
        deserialize_yaml(yaml).map_err(|error| error.error)
    }
}