cargo_lambda_metadata/cargo/
watch.rs

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
use cargo_options::Run;
use clap::Args;
use matchit::{InsertError, MatchError, Router};
use serde::{
    de::{Error, Visitor},
    ser::SerializeSeq,
    Deserialize, Serialize,
};
use serde_json::{json, Value};
use std::{collections::HashMap, path::PathBuf};

use crate::{
    cargo::{count_common_options, serialize_common_options},
    env::{EnvOptions, Environment},
    error::MetadataError,
    lambda::Timeout,
};

use cargo_lambda_remote::tls::TlsOptions;

#[cfg(windows)]
const DEFAULT_INVOKE_ADDRESS: &str = "127.0.0.1";

#[cfg(not(windows))]
const DEFAULT_INVOKE_ADDRESS: &str = "::";

const DEFAULT_INVOKE_PORT: u16 = 9000;

#[derive(Args, Clone, Debug, Default, Deserialize)]
#[command(
    name = "watch",
    visible_alias = "start",
    after_help = "Full command documentation: https://www.cargo-lambda.info/commands/watch.html"
)]
pub struct Watch {
    /// Ignore any code changes, and don't reload the function automatically
    #[arg(long, visible_alias = "no-reload")]
    #[serde(default)]
    pub ignore_changes: bool,

    /// Start the Lambda runtime APIs without starting the function.
    /// This is useful if you start (and debug) your function in your IDE.
    #[arg(long)]
    #[serde(default)]
    pub only_lambda_apis: bool,

    #[arg(short = 'a', long, default_value = DEFAULT_INVOKE_ADDRESS)]
    #[serde(default = "default_invoke_address")]
    /// Address where users send invoke requests
    pub invoke_address: String,

    /// Address port where users send invoke requests
    #[arg(short = 'p', long, default_value_t = DEFAULT_INVOKE_PORT)]
    #[serde(default = "default_invoke_port")]
    pub invoke_port: u16,

    /// Print OpenTelemetry traces after each function invocation
    #[arg(long)]
    #[serde(default)]
    pub print_traces: bool,

    /// Wait for the first invocation to compile the function
    #[arg(long, short)]
    #[serde(default)]
    pub wait: bool,

    /// Disable the default CORS configuration
    #[arg(long)]
    #[serde(default)]
    pub disable_cors: bool,

    /// How long the invoke request waits for a response
    #[arg(long)]
    #[serde(default)]
    pub timeout: Option<Timeout>,

    #[command(flatten)]
    #[serde(flatten)]
    pub cargo_opts: Run,

    #[command(flatten)]
    #[serde(flatten)]
    pub env_options: EnvOptions,

    #[command(flatten)]
    #[serde(flatten)]
    pub tls_options: TlsOptions,

    #[arg(skip)]
    #[serde(default)]
    pub router: Option<FunctionRouter>,
}

impl Watch {
    pub fn manifest_path(&self) -> PathBuf {
        self.cargo_opts
            .manifest_path
            .clone()
            .unwrap_or_else(|| "Cargo.toml".into())
    }

    /// Returns the package name if there is only one package in the list of `packages`,
    /// otherwise None.
    pub fn package(&self) -> Option<String> {
        if self.cargo_opts.packages.len() > 1 {
            return None;
        }
        self.cargo_opts.packages.first().map(|s| s.to_string())
    }

    pub fn lambda_environment(
        &self,
        base: &HashMap<String, String>,
    ) -> Result<Environment, MetadataError> {
        self.env_options.lambda_environment(base)
    }
}

impl Serialize for Watch {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct;

        // Count non-empty fields
        let field_count = self.ignore_changes as usize
            + self.only_lambda_apis as usize
            + !self.invoke_address.is_empty() as usize
            + (self.invoke_port != 0) as usize
            + self.print_traces as usize
            + self.wait as usize
            + self.disable_cors as usize
            + self.timeout.is_some() as usize
            + self.router.is_some() as usize
            + self.cargo_opts.manifest_path.is_some() as usize
            + self.cargo_opts.release as usize
            + self.cargo_opts.ignore_rust_version as usize
            + self.cargo_opts.unit_graph as usize
            + !self.cargo_opts.packages.is_empty() as usize
            + !self.cargo_opts.bin.is_empty() as usize
            + !self.cargo_opts.example.is_empty() as usize
            + !self.cargo_opts.args.is_empty() as usize
            + count_common_options(&self.cargo_opts.common)
            + self.env_options.count_fields()
            + self.tls_options.count_fields();

        let mut state = serializer.serialize_struct("Watch", field_count)?;

        // Only serialize bool fields that are true
        if self.ignore_changes {
            state.serialize_field("ignore_changes", &true)?;
        }
        if self.only_lambda_apis {
            state.serialize_field("only_lambda_apis", &true)?;
        }
        if !self.invoke_address.is_empty() {
            state.serialize_field("invoke_address", &self.invoke_address)?;
        }
        if self.invoke_port != 0 {
            state.serialize_field("invoke_port", &self.invoke_port)?;
        }
        if self.print_traces {
            state.serialize_field("print_traces", &true)?;
        }
        if self.wait {
            state.serialize_field("wait", &true)?;
        }
        if self.disable_cors {
            state.serialize_field("disable_cors", &true)?;
        }

        // Only serialize Some values for Options
        if let Some(timeout) = &self.timeout {
            state.serialize_field("timeout", timeout)?;
        }
        if let Some(router) = &self.router {
            state.serialize_field("router", router)?;
        }

        // Flatten the fields from cargo_opts and env_options
        self.env_options.serialize_fields::<S>(&mut state)?;
        self.tls_options.serialize_fields::<S>(&mut state)?;

        if let Some(manifest_path) = &self.cargo_opts.manifest_path {
            state.serialize_field("manifest_path", manifest_path)?;
        }
        if self.cargo_opts.release {
            state.serialize_field("release", &true)?;
        }
        if self.cargo_opts.ignore_rust_version {
            state.serialize_field("ignore_rust_version", &true)?;
        }
        if self.cargo_opts.unit_graph {
            state.serialize_field("unit_graph", &true)?;
        }
        if !self.cargo_opts.packages.is_empty() {
            state.serialize_field("packages", &self.cargo_opts.packages)?;
        }
        if !self.cargo_opts.bin.is_empty() {
            state.serialize_field("bin", &self.cargo_opts.bin)?;
        }
        if !self.cargo_opts.example.is_empty() {
            state.serialize_field("example", &self.cargo_opts.example)?;
        }
        if !self.cargo_opts.args.is_empty() {
            state.serialize_field("args", &self.cargo_opts.args)?;
        }
        serialize_common_options::<S>(&mut state, &self.cargo_opts.common)?;

        state.end()
    }
}

fn default_invoke_address() -> String {
    DEFAULT_INVOKE_ADDRESS.to_string()
}

fn default_invoke_port() -> u16 {
    DEFAULT_INVOKE_PORT
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct WatchConfig {
    pub router: Option<FunctionRouter>,
}

#[derive(Clone, Debug, Default)]
pub struct FunctionRouter {
    inner: Router<FunctionRoutes>,
    pub(crate) raw: Vec<(String, FunctionRoutes)>,
}

impl FunctionRouter {
    pub fn at(&self, path: &str, method: &str) -> Result<&str, MatchError> {
        let matched = self.inner.at(path)?;
        matched.value.at(method).ok_or(MatchError::NotFound)
    }

    pub fn insert(&mut self, path: &str, routes: FunctionRoutes) -> Result<(), InsertError> {
        self.inner.insert(path, routes)
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum FunctionRoutes {
    Single(String),
    Multiple(HashMap<String, String>),
}

impl FunctionRoutes {
    pub fn at(&self, method: &str) -> Option<&str> {
        match self {
            FunctionRoutes::Single(function) => Some(function),
            FunctionRoutes::Multiple(routes) => routes.get(method).map(|s| s.as_str()),
        }
    }
}

struct FunctionRouterVisitor;

impl<'de> Visitor<'de> for FunctionRouterVisitor {
    type Value = FunctionRouter;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("a map or sequence of function routes")
    }

    fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::MapAccess<'de>,
    {
        let routes: HashMap<String, FunctionRoutes> =
            Deserialize::deserialize(serde::de::value::MapAccessDeserializer::new(map))?;
        let mut inner = Router::new();

        for (path, route) in &routes {
            inner.insert(path, route.clone()).map_err(|e| {
                serde::de::Error::custom(format!("Failed to insert route {path}: {e}"))
            })?;
        }

        let raw: Vec<(String, FunctionRoutes)> = routes.into_iter().collect();
        Ok(FunctionRouter { inner, raw })
    }

    fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::SeqAccess<'de>,
    {
        let raw: Vec<(String, FunctionRoutes)> =
            Deserialize::deserialize(serde::de::value::SeqAccessDeserializer::new(seq))?;
        let mut inner = Router::new();

        for (path, route) in &raw {
            inner.insert(path, route.clone()).map_err(|e| {
                serde::de::Error::custom(format!("Failed to insert route {path}: {e}"))
            })?;
        }

        Ok(FunctionRouter { inner, raw })
    }
}

impl<'de> Deserialize<'de> for FunctionRouter {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_any(FunctionRouterVisitor)
    }
}

impl Serialize for FunctionRouter {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.raw.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for FunctionRoutes {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = Value::deserialize(deserializer)?;
        match value {
            Value::String(s) => Ok(FunctionRoutes::Single(s)),
            Value::Array(arr) => {
                let mut routes = HashMap::new();
                for item in arr {
                    let obj = item.as_object().ok_or_else(|| {
                        Error::custom("Array items must be objects with method and function fields")
                    })?;

                    let method = obj
                        .get("method")
                        .and_then(|m| m.as_str())
                        .ok_or_else(|| Error::custom("Missing or invalid method field"))?;

                    let function = obj
                        .get("function")
                        .and_then(|f| f.as_str())
                        .ok_or_else(|| Error::custom("Missing or invalid function field"))?;

                    routes.insert(method.to_string(), function.to_string());
                }
                Ok(FunctionRoutes::Multiple(routes))
            }
            _ => Err(Error::custom(
                "Function routes must be either a string or an array of objects with method and function fields",
            )),
        }
    }
}

impl Serialize for FunctionRoutes {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            FunctionRoutes::Single(function) => function.serialize(serializer),
            FunctionRoutes::Multiple(routes) => {
                let mut seq = serializer.serialize_seq(Some(routes.len()))?;
                for (method, function) in routes {
                    let mut map = serde_json::Map::new();
                    map.insert("method".to_string(), json!(method));
                    map.insert("function".to_string(), json!(function));
                    seq.serialize_element(&Value::Object(map))?;
                }
                seq.end()
            }
        }
    }
}

#[cfg(test)]
mod tests {

    use cargo_options::CommonOptions;
    use serde_json::{json, Value};
    use std::path::PathBuf;

    use super::*;

    #[test]
    fn test_router_deserialize() {
        let router: FunctionRouter = toml::from_str(
            r#"
            "/api/v1/users" = [
                { function = "get_user", method = "GET" },
                { function = "create_user", method = "POST" }
            ]
            "/api/v1/all_methods" = "all_methods"
        "#,
        )
        .unwrap();

        assert_eq!(
            router.inner.at("/api/v1/users").unwrap().value,
            &FunctionRoutes::Multiple(HashMap::from([
                ("GET".to_string(), "get_user".to_string()),
                ("POST".to_string(), "create_user".to_string()),
            ]))
        );

        assert_eq!(
            router.inner.at("/api/v1/all_methods").unwrap().value,
            &FunctionRoutes::Single("all_methods".to_string())
        );
    }

    #[test]
    fn test_router_get() {
        let router = FunctionRouter::default();
        assert_eq!(router.at("/api/v1/users", "GET"), Err(MatchError::NotFound));

        let mut inner = Router::new();
        inner
            .insert(
                "/api/v1/users",
                FunctionRoutes::Single("user_handler".to_string()),
            )
            .unwrap();
        let router = FunctionRouter {
            inner,
            ..Default::default()
        };
        assert_eq!(router.at("/api/v1/users", "GET"), Ok("user_handler"));
        assert_eq!(router.at("/api/v1/users", "POST"), Ok("user_handler"));

        let mut inner = Router::new();
        inner
            .insert(
                "/api/v1/users",
                FunctionRoutes::Multiple(HashMap::from([
                    ("GET".to_string(), "get_user".to_string()),
                    ("POST".to_string(), "create_user".to_string()),
                ])),
            )
            .unwrap();
        let router = FunctionRouter {
            inner,
            ..Default::default()
        };
        assert_eq!(router.at("/api/v1/users", "GET"), Ok("get_user"));
        assert_eq!(router.at("/api/v1/users", "POST"), Ok("create_user"));
        assert_eq!(router.at("/api/v1/users", "PUT"), Err(MatchError::NotFound));
    }

    #[test]
    fn test_router_serialize() {
        let config = r#"
            "/api/v1/users" = [
                { function = "get_user", method = "GET" },
                { function = "create_user", method = "POST" }
            ]
            "/api/v1/all_methods" = "all_methods"
        "#;
        let router: FunctionRouter = toml::from_str(config).unwrap();

        let json = serde_json::to_value(&router).unwrap();

        let new_router: FunctionRouter = serde_json::from_value(json).unwrap();
        assert_eq!(new_router.raw, router.raw);

        assert_eq!(
            new_router.inner.at("/api/v1/users").unwrap().value,
            &FunctionRoutes::Multiple(HashMap::from([
                ("GET".to_string(), "get_user".to_string()),
                ("POST".to_string(), "create_user".to_string()),
            ]))
        );

        assert_eq!(
            new_router.inner.at("/api/v1/all_methods").unwrap().value,
            &FunctionRoutes::Single("all_methods".to_string())
        );
    }

    #[test]
    fn test_watch_serialization() {
        let watch = Watch {
            invoke_address: "127.0.0.1".to_string(),
            invoke_port: 9000,
            env_options: EnvOptions {
                env_file: Some(PathBuf::from("/tmp/env")),
                env_var: Some(vec!["FOO=BAR".to_string()]),
            },
            tls_options: TlsOptions::new(
                Some(PathBuf::from("/tmp/cert.pem")),
                Some(PathBuf::from("/tmp/key.pem")),
                Some(PathBuf::from("/tmp/ca.pem")),
            ),
            cargo_opts: Run {
                common: CommonOptions {
                    quiet: false,
                    jobs: None,
                    keep_going: false,
                    profile: None,
                    features: vec!["feature1".to_string()],
                    all_features: false,
                    no_default_features: true,
                    target: vec!["x86_64-unknown-linux-gnu".to_string()],
                    target_dir: Some(PathBuf::from("/tmp/target")),
                    message_format: vec!["json".to_string()],
                    verbose: 1,
                    color: Some("auto".to_string()),
                    frozen: true,
                    locked: true,
                    offline: true,
                    config: vec!["config.toml".to_string()],
                    unstable_flags: vec!["flag1".to_string()],
                    timings: None,
                },
                manifest_path: None,
                release: false,
                ignore_rust_version: false,
                unit_graph: false,
                packages: vec![],
                bin: vec![],
                example: vec![],
                args: vec![],
            },
            ..Default::default()
        };

        let json = serde_json::to_value(&watch).unwrap();
        assert_eq!(json["invoke_address"], "127.0.0.1");
        assert_eq!(json["invoke_port"], 9000);
        assert_eq!(json["env_file"], "/tmp/env");
        assert_eq!(json["env_var"], json!(["FOO=BAR"]));
        assert_eq!(json["tls_cert"], "/tmp/cert.pem");
        assert_eq!(json["tls_key"], "/tmp/key.pem");
        assert_eq!(json["tls_ca"], "/tmp/ca.pem");
        assert_eq!(json["features"], json!(["feature1"]));
        assert_eq!(json["no_default_features"], true);
        assert_eq!(json["target"], json!(["x86_64-unknown-linux-gnu"]));
        assert_eq!(json["target_dir"], "/tmp/target");
        assert_eq!(json["message_format"], json!(["json"]));
        assert_eq!(json["verbose"], 1);
        assert_eq!(json["color"], "auto");
        assert_eq!(json["frozen"], true);
        assert_eq!(json["locked"], true);
        assert_eq!(json["offline"], true);
        assert_eq!(json["config"], json!(["config.toml"]));
        assert_eq!(json["unstable_flags"], json!(["flag1"]));
        assert_eq!(json["timings"], Value::Null);

        let deserialized: Watch = serde_json::from_value(json).unwrap();

        assert_eq!(deserialized.invoke_address, watch.invoke_address);
        assert_eq!(deserialized.invoke_port, watch.invoke_port);
        assert_eq!(
            deserialized.env_options.env_file,
            watch.env_options.env_file
        );
        assert_eq!(deserialized.env_options.env_var, watch.env_options.env_var);
        assert_eq!(
            deserialized.tls_options.tls_cert,
            watch.tls_options.tls_cert
        );
        assert_eq!(deserialized.tls_options.tls_key, watch.tls_options.tls_key);
        assert_eq!(deserialized.tls_options.tls_ca, watch.tls_options.tls_ca);
        assert_eq!(
            deserialized.cargo_opts.common.features,
            watch.cargo_opts.common.features
        );
        assert_eq!(
            deserialized.cargo_opts.common.no_default_features,
            watch.cargo_opts.common.no_default_features
        );
        assert_eq!(
            deserialized.cargo_opts.common.target,
            watch.cargo_opts.common.target
        );
        assert_eq!(
            deserialized.cargo_opts.common.target_dir,
            watch.cargo_opts.common.target_dir
        );
        assert_eq!(
            deserialized.cargo_opts.common.message_format,
            watch.cargo_opts.common.message_format
        );
        assert_eq!(
            deserialized.cargo_opts.common.verbose,
            watch.cargo_opts.common.verbose
        );
        assert_eq!(
            deserialized.cargo_opts.common.color,
            watch.cargo_opts.common.color
        );
        assert_eq!(
            deserialized.cargo_opts.common.frozen,
            watch.cargo_opts.common.frozen
        );
        assert_eq!(
            deserialized.cargo_opts.common.locked,
            watch.cargo_opts.common.locked
        );
        assert_eq!(
            deserialized.cargo_opts.common.offline,
            watch.cargo_opts.common.offline
        );
        assert_eq!(
            deserialized.cargo_opts.common.config,
            watch.cargo_opts.common.config
        );
        assert_eq!(
            deserialized.cargo_opts.common.unstable_flags,
            watch.cargo_opts.common.unstable_flags
        );
        assert_eq!(
            deserialized.cargo_opts.common.timings,
            watch.cargo_opts.common.timings
        );
    }
}