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
use seaplane::api::compute::v1::{Architecture, Flight as FlightModel, ImageReference};

use crate::{
    cli::{
        cmds::flight::{str_to_image_ref, SeaplaneFlightCommonArgMatches, FLIGHT_MINIMUM_DEFAULT},
        validator::validate_flight_name,
    },
    error::{CliErrorKind, Result},
    ops::generate_flight_name,
};

/// Represents the "Source of Truth" i.e. it combines all the CLI options, ENV vars, and config
/// values into a single structure that can be used later to build models for the API or local
/// structs for serializing
// TODO: we may not want to derive this we implement circular references
#[derive(Debug, Clone)]
pub struct FlightCtx {
    pub image: Option<ImageReference>,
    pub name_id: String,
    pub minimum: u64,
    pub maximum: Option<u64>,
    pub architecture: Vec<Architecture>,
    pub api_permission: bool,
    pub reset_maximum: bool,
    // True if we randomly generated the name. False if the user provided it
    pub generated_name: bool,
}

impl Default for FlightCtx {
    fn default() -> Self {
        Self {
            name_id: generate_flight_name(),
            image: None,
            minimum: FLIGHT_MINIMUM_DEFAULT,
            maximum: None,
            architecture: Vec::new(),
            api_permission: false,
            reset_maximum: false,
            generated_name: true,
        }
    }
}

impl FlightCtx {
    /// Builds a FlightCtx from a string value using the inline flight spec syntax:
    ///
    /// name=FOO,image=nginx:latest,api-permission,architecture=amd64,minimum=1,maximum,2
    ///
    /// Where only image=... is required
    pub fn from_inline_flight(inline_flight: &str) -> Result<FlightCtx> {
        if inline_flight.contains(' ') {
            return Err(CliErrorKind::InlineFlightHasSpace.into_err());
        }

        let mut fctx = FlightCtx::default();

        let parts = inline_flight.split(',');

        macro_rules! parse_item {
            ($item:expr, $f:expr) => {{
                let mut item = $item.split('=');
                item.next();
                if let Some(value) = item.next() {
                    if value.is_empty() {
                        return Err(
                            CliErrorKind::InlineFlightMissingValue($item.to_string()).into_err()
                        );
                    }
                    $f(value)
                } else {
                    Err(CliErrorKind::InlineFlightMissingValue($item.to_string()).into_err())
                }
            }};
            ($item:expr) => {{
                parse_item!($item, |n| { Ok(n) })
            }};
        }

        for part in parts {
            match part.trim() {
                // @TODO technically nameFOOBAR=.. is valid... oh well
                name if part.starts_with("name") => {
                    fctx.name_id = parse_item!(name, |n: &str| {
                        if validate_flight_name(n).is_err() {
                            Err(CliErrorKind::InlineFlightInvalidName(n.to_string()).into_err())
                        } else {
                            Ok(n.to_string())
                        }
                    })?;
                    fctx.generated_name = false;
                }
                // @TODO technically imageFOOBAR=.. is valid... oh well
                img if part.starts_with("image") => {
                    fctx.image = Some(str_to_image_ref(parse_item!(img)?)?);
                }
                // @TODO technically maxFOOBAR=.. is valid... oh well
                max if part.starts_with("max") => {
                    fctx.maximum = Some(parse_item!(max)?.parse()?);
                }
                // @TODO technically minFOOBAR=.. is valid... oh well
                min if part.starts_with("min") => {
                    fctx.minimum = parse_item!(min)?.parse()?;
                }
                // @TODO technically archFOOBAR=.. is valid... oh well
                arch if part.starts_with("arch") => {
                    fctx.architecture.push(parse_item!(arch)?.parse()?);
                }
                "api-permission" | "api-permissions" => {
                    fctx.api_permission = true;
                }
                // @TODO technically api-permissionFOOBAR=.. is valid... oh well
                perm if part.starts_with("api-permission") => {
                    let _ = parse_item!(perm, |perm: &str| {
                        fctx.api_permission = match perm {
                            t if t.eq_ignore_ascii_case("true") => true,
                            f if f.eq_ignore_ascii_case("false") => true,
                            _ => {
                                return Err(CliErrorKind::InlineFlightUnknownItem(
                                    perm.to_string(),
                                )
                                .into_err());
                            }
                        };
                        Ok(())
                    });
                }
                _ => {
                    return Err(CliErrorKind::InlineFlightUnknownItem(part.to_string()).into_err());
                }
            }
        }

        if fctx.image.is_none() {
            return Err(CliErrorKind::InlineFlightMissingImage.into_err());
        }

        Ok(fctx)
    }

    /// Builds a FlightCtx from ArgMatches using some `prefix` if any to search for args
    pub fn from_flight_common(
        matches: &SeaplaneFlightCommonArgMatches,
        prefix: &str,
    ) -> Result<FlightCtx> {
        let matches = matches.0;
        let mut generated_name = false;
        // We generate a random name if one is not provided
        let name = matches
            .get_one::<String>(&format!("{prefix}name"))
            .map(ToOwned::to_owned)
            .unwrap_or_else(|| {
                generated_name = true;
                generate_flight_name()
            });

        // We have to use if let in order to use the ? operator
        let image = if let Some(s) = matches.get_one::<String>(&format!("{prefix}image")) {
            Some(str_to_image_ref(s)?)
        } else {
            None
        };

        Ok(FlightCtx {
            image,
            name_id: name,
            minimum: matches
                .get_one(&format!("{prefix}minimum"))
                .copied()
                .unwrap_or(FLIGHT_MINIMUM_DEFAULT),
            maximum: matches.get_one(&format!("{prefix}maximum")).copied(),
            architecture: matches
                .get_many::<Architecture>(&format!("{prefix}architecture"))
                .unwrap_or_default()
                .copied()
                .collect(),
            // because of clap overrides we only have to check api_permissions
            api_permission: matches.contains_id(&format!("{prefix}api-permission")),
            reset_maximum: matches.contains_id(&format!("{prefix}no-maximum")),
            generated_name,
        })
    }

    /// Creates a new seaplane::api::compute::v1::Flight from the contained values
    pub fn model(&self) -> FlightModel {
        // Create the new Flight model from the CLI inputs
        let mut flight_model = FlightModel::builder()
            .name(self.name_id.clone())
            .minimum(self.minimum);

        #[cfg(feature = "unstable")]
        {
            flight_model = flight_model.api_permission(self.api_permission);
        }

        if let Some(image) = self.image.clone() {
            flight_model = flight_model.image_reference(image);
        }

        // We have to conditionally set the `maximum` because the builder takes a `u64` but we have
        // an `Option<u64>` so can't just blindly overwrite it like we do with `minimum` above.
        if let Some(n) = self.maximum {
            flight_model = flight_model.maximum(n);
        }

        // Add all the architectures. In the CLI they're a Vec but in the Model they're a HashSet
        // which is the reason for the slightly awkward loop
        for arch in &self.architecture {
            flight_model = flight_model.add_architecture(*arch);
        }

        // Create a new Flight struct we can add to our local JSON "DB"
        flight_model
            .build()
            .expect("Failed to build Flight from inputs")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn from_inline_flight_valid() {
        assert!(FlightCtx::from_inline_flight(
            "image=demos/nginx:latest,name=foo,maximum=2,minimum=2,api-permission,architecture=amd64"
        )
        .is_ok());
        assert!(FlightCtx::from_inline_flight(
            "image=demos/nginx:latest,name=foo,maximum=2,minimum=2,api-permission"
        )
        .is_ok());
        assert!(FlightCtx::from_inline_flight(
            "image=demos/nginx:latest,name=foo,maximum=2,minimum=2"
        )
        .is_ok());
        assert!(FlightCtx::from_inline_flight("image=demos/nginx:latest,name=foo").is_ok());
        assert!(FlightCtx::from_inline_flight("image=demos/nginx:latest").is_ok());
        assert!(FlightCtx::from_inline_flight(
            "image=demos/nginx:latest,name=foo,max=2,minimum=2,api-permission,architecture=amd64"
        )
        .is_ok());
        assert!(FlightCtx::from_inline_flight(
            "image=demos/nginx:latest,name=foo,maximum=2,min=2,api-permission"
        )
        .is_ok());
        assert!(FlightCtx::from_inline_flight("image=demos/nginx:latest,api-permissions").is_ok());
        assert!(FlightCtx::from_inline_flight("image=demos/nginx:latest,arch=amd64").is_ok());
        assert!(FlightCtx::from_inline_flight("image=demos/nginx:latest,arch=arm64").is_ok());
        assert!(
            FlightCtx::from_inline_flight("image=demos/nginx:latest,api-permission=true").is_ok(),
        );
        assert!(
            FlightCtx::from_inline_flight("image=demos/nginx:latest,api-permission=false").is_ok()
        );
    }

    #[test]
    fn from_inline_flight_invalid() {
        assert_eq!(FlightCtx::from_inline_flight(
            "image= demos/nginx:latest,name=foo,maximum=2,minimum=2,api-permission,architecture=amd64"
        )
        .unwrap_err().kind(), &CliErrorKind::InlineFlightHasSpace);
        assert_eq!(
            FlightCtx::from_inline_flight(
                "image=demos/nginx:latest, name=foo,maximum=2,minimum=2,api-permission"
            )
            .unwrap_err()
            .kind(),
            &CliErrorKind::InlineFlightHasSpace
        );
        assert_eq!(
            FlightCtx::from_inline_flight("name=foo,maximum=2,minimum=2")
                .unwrap_err()
                .kind(),
            &CliErrorKind::InlineFlightMissingImage
        );
        assert_eq!(
            FlightCtx::from_inline_flight(",image=demos/nginx:latest,name=foo")
                .unwrap_err()
                .kind(),
            &CliErrorKind::InlineFlightUnknownItem("".into())
        );
        assert_eq!(
            FlightCtx::from_inline_flight("image=demos/nginx:latest,")
                .unwrap_err()
                .kind(),
            &CliErrorKind::InlineFlightUnknownItem("".into())
        );
        assert_eq!(
            FlightCtx::from_inline_flight("image=demos/nginx:latest,foo")
                .unwrap_err()
                .kind(),
            &CliErrorKind::InlineFlightUnknownItem("foo".into())
        );
        assert_eq!(
            FlightCtx::from_inline_flight("image=demos/nginx:latest,name=invalid_name")
                .unwrap_err()
                .kind(),
            &CliErrorKind::InlineFlightInvalidName("invalid_name".into())
        );
        assert!(FlightCtx::from_inline_flight("image=demos/nginx:latest,max=2.3")
            .unwrap_err()
            .kind()
            .is_parse_int(),);
        assert!(FlightCtx::from_inline_flight("image=demos/nginx:latest,max=foo")
            .unwrap_err()
            .kind()
            .is_parse_int());
        assert!(FlightCtx::from_inline_flight("image=demos/nginx:latest,arch=foo")
            .unwrap_err()
            .kind()
            .is_strum_parse(),);
        assert_eq!(
            FlightCtx::from_inline_flight("image=demos/nginx:latest,name")
                .unwrap_err()
                .kind(),
            &CliErrorKind::InlineFlightMissingValue("name".into())
        );
        assert_eq!(
            FlightCtx::from_inline_flight("image=demos/nginx:latest,name=foo,arch")
                .unwrap_err()
                .kind(),
            &CliErrorKind::InlineFlightMissingValue("arch".into())
        );
        assert_eq!(
            FlightCtx::from_inline_flight("image,name=foo")
                .unwrap_err()
                .kind(),
            &CliErrorKind::InlineFlightMissingValue("image".into())
        );
        assert_eq!(
            FlightCtx::from_inline_flight("image=demos/nginx:latest,name=foo,min=")
                .unwrap_err()
                .kind(),
            &CliErrorKind::InlineFlightMissingValue("min".into())
        );
        assert_eq!(
            FlightCtx::from_inline_flight("image=demos/nginx:latest,name=foo,max=")
                .unwrap_err()
                .kind(),
            &CliErrorKind::InlineFlightMissingValue("max".into())
        );
    }
}