aviso 2.0.0-rc.2

Core client library for aviso-server, ECMWF's notification service.
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
// (C) Copyright 2024- ECMWF and individual contributors.
//
// This software is licensed under the terms of the Apache Licence Version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation nor
// does it submit to any jurisdiction.

//! Declarative YAML configuration for triggers.
//!
//! [`TriggerConfig`] is the serde-derived target the CLI and the
//! future Python bindings use to deserialise listener triggers from a
//! YAML config file. Each variant carries its body as a named payload
//! struct (`EchoConfig`, `LogConfig`, `CommandTriggerConfig`,
//! `WebhookTriggerConfig`) rather than inline-struct variants, so
//! `#[serde(deny_unknown_fields)]` on each payload struct catches
//! misspelled keys reliably (serde-rs issue #2123 makes the same
//! attribute on the outer tagged enum unreliable when the tag matches
//! a known variant). Unknown `type:` values fail automatically via
//! serde's "unknown variant" error without any extra attribute.
//!
//! # Example
//!
//! ```yaml
//! triggers:
//!   - type: webhook
//!     url: "https://hooks.example.org/notify"
//!     headers:
//!       Authorization: "Bearer {{ env.HOOK_TOKEN }}"
//!     body_template: '{"seq": {{ notification.sequence }}}'
//!     timeout: 30s
//!     retries: 3
//!   - type: log
//!     path: "/var/log/aviso/notifications.log"
//!     retries: 2
//! ```
//!
//! Each `TriggerConfig` deserialises into a [`Trigger`] builder via
//! [`TriggerConfig::into_trigger`].

use std::collections::BTreeMap;
use std::path::PathBuf;
use std::time::Duration;

use super::{HttpMethod, Trigger};

/// Declarative trigger configuration deserialised from YAML.
///
/// Tagged on the `type:` field. Each variant carries a named payload
/// struct so `#[serde(deny_unknown_fields)]` on the struct catches
/// misspelled keys within a matched variant; the outer-enum form
/// does not (serde-rs issue #2123). Unknown `type:` values fail
/// automatically as serde "unknown variant" errors. New variants
/// land additively under `#[non_exhaustive]`.
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum TriggerConfig {
    /// Echo trigger: writes the notification as compact JSON to
    /// standard output.
    Echo(EchoConfig),
    /// Log trigger: appends each notification as a line of compact
    /// JSON to a user-specified file.
    Log(LogConfig),
    /// Command trigger: spawns a `/bin/sh -c <rendered>` child per
    /// notification, exposing notification fields as `AVISO_*`
    /// environment variables. Unix-only (`#[cfg(unix)]`).
    #[cfg(unix)]
    Command(CommandTriggerConfig),
    /// Webhook trigger: sends an HTTP request per notification to a
    /// user-configured URL.
    Webhook(WebhookTriggerConfig),
    /// Teams trigger: sugar over [`Self::Webhook`] that auto-builds an
    /// Adaptive Card body for Microsoft Teams Workflows endpoints.
    /// Operators wanting richer card customisation use [`Self::Webhook`]
    /// directly with a hand-written `body_template`.
    Teams(TeamsTriggerConfig),
    /// Post trigger: HTTP POST with the server-emitted `CloudEvent`
    /// envelope as the body. In the production watch path the raw
    /// envelope captured at the SSE parser is forwarded verbatim
    /// (`type`, `source`, `time`, `dataschema`, etc. all reach the
    /// receiver as the server emitted them); outside the watch path
    /// (test fixtures), a minimal envelope is reconstructed from the
    /// lib's narrowed fields. Custom headers supported; body shape
    /// is fixed (no `body_template` field). For arbitrary body
    /// shapes use [`Self::Webhook`] directly.
    Post(PostTriggerConfig),
}

/// YAML payload for [`TriggerConfig::Echo`].
#[non_exhaustive]
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EchoConfig {
    /// Retry count; `N` allows up to `N` additional attempts after
    /// the first failure. Default `0`.
    #[serde(default)]
    pub retries: u32,
    /// Required flag. When `true` (default), a final failure
    /// terminates the watch with
    /// [`crate::ClientError::TriggerFailed`]; when `false`, the
    /// failure is logged at `WARN` and the watch continues.
    #[serde(default = "default_required")]
    pub required: bool,
}

impl Default for EchoConfig {
    /// Constructs an [`EchoConfig`] with the same field values
    /// serde fills in for omitted YAML fields: `retries = 0`,
    /// `required = true`. Programmatic constructors (the CLI's
    /// inline-listen path that builds a `ListenerSpec` without
    /// parsing YAML) need this so a `TriggerConfig::Echo(...)`
    /// value can be created from outside the `aviso` crate
    /// despite `EchoConfig` being `#[non_exhaustive]`.
    fn default() -> Self {
        Self {
            retries: 0,
            required: true,
        }
    }
}

/// YAML payload for [`TriggerConfig::Log`].
#[non_exhaustive]
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LogConfig {
    /// Path to the log file. Opened with `append(true).create(true)`
    /// at first dispatch and held for the trigger's lifetime.
    pub path: PathBuf,
    /// Retry count; `N` allows up to `N` additional attempts after
    /// the first failure. Default `0`.
    #[serde(default)]
    pub retries: u32,
    /// Required flag. When `true` (default), a final failure
    /// terminates the watch; when `false`, the failure is logged at
    /// `WARN` and the watch continues.
    #[serde(default = "default_required")]
    pub required: bool,
}

/// YAML payload for [`TriggerConfig::Command`]. Unix-only.
#[cfg(unix)]
#[non_exhaustive]
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CommandTriggerConfig {
    /// Command template; rendered through the in-crate template
    /// engine and passed to `/bin/sh -c`.
    pub command: String,
    /// Extra environment variables to set on the child process.
    /// User-supplied entries override the dispatcher-injected
    /// `AVISO_*` keys when both are present.
    #[serde(default)]
    pub env: BTreeMap<String, String>,
    /// Working directory for the child process. When absent the
    /// child inherits the current directory.
    #[serde(default)]
    pub working_dir: Option<PathBuf>,
    /// Per-trigger timeout. Parsed as a humantime duration string
    /// (`30s`, `2m`, `1h30m`, `500ms`). Absent means no timeout.
    #[serde(default, with = "humantime_serde::option")]
    pub timeout: Option<Duration>,
    /// Retry count; default `0`.
    #[serde(default)]
    pub retries: u32,
    /// Required flag; default `true`.
    #[serde(default = "default_required")]
    pub required: bool,
    /// Fail-fast policy on terminal failures; default `true`. For
    /// commands, terminal failures under `fail_fast = true` are
    /// `TriggerError::Command` (non-zero exit) and
    /// `TriggerError::Template` (template engine rejection). I/O
    /// errors and timeouts stay retryable.
    #[serde(default = "default_fail_fast")]
    pub fail_fast: bool,
}

/// YAML payload for [`TriggerConfig::Webhook`].
#[non_exhaustive]
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WebhookTriggerConfig {
    /// URL template; rendered through the in-crate template engine
    /// at dispatch time.
    pub url: String,
    /// HTTP method. Defaults to `POST` when absent.
    #[serde(default)]
    pub method: Option<HttpMethod>,
    /// Headers to attach to the request. Header names are taken
    /// literally; header values are template-rendered at dispatch.
    #[serde(default)]
    pub headers: BTreeMap<String, String>,
    /// Optional body template. When absent, the body defaults to
    /// the notification serialised as compact JSON.
    #[serde(default)]
    pub body_template: Option<String>,
    /// Per-trigger timeout. Parsed as a humantime duration string
    /// (`30s`, `2m`, `1h30m`, `500ms`). When absent the webhook
    /// uses [`crate::watch::DEFAULT_WEBHOOK_TIMEOUT`].
    #[serde(default, with = "humantime_serde::option")]
    pub timeout: Option<Duration>,
    /// Retry count; default `0`.
    #[serde(default)]
    pub retries: u32,
    /// Required flag; default `true`.
    #[serde(default = "default_required")]
    pub required: bool,
    /// Fail-fast policy on terminal failures; default `true`. For
    /// webhooks, terminal failures under `fail_fast = true` are:
    /// `TriggerError::Webhook` with a 4xx HTTP status (the receiver
    /// is rejecting the request); `TriggerError::WebhookBuild` (the
    /// HTTP client rejected the rendered request: malformed URL or
    /// invalid header value); and `TriggerError::Template` (the
    /// template engine rejected the input). 5xx, transport errors,
    /// I/O errors, and timeouts stay retryable.
    #[serde(default = "default_fail_fast")]
    pub fail_fast: bool,
}

/// YAML payload for [`TriggerConfig::Teams`]. Operator-friendly
/// shortcut for Microsoft Teams Workflows endpoints. Produces a
/// [`crate::watch::TriggerKind::Teams`] at `into_trigger` time; the
/// teams dispatcher builds an Adaptive Card from the notification's
/// runtime data and delegates to the webhook HTTP machinery for the
/// actual send (so retry classification, response capture, and
/// error mapping match the webhook trigger).
#[non_exhaustive]
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TeamsTriggerConfig {
    /// Workflow URL. Template-rendered at dispatch time;
    /// `{{ env.TEAMS_WEBHOOK_URL }}` is the canonical secret-bearing pattern.
    pub url: String,
    /// Optional title template for the Adaptive Card's first `TextBlock`.
    /// Defaults to `aviso {{ notification.event_type }} #{{ notification.sequence }}`.
    #[serde(default = "default_teams_title")]
    pub title_template: String,
    /// Per-trigger timeout. Parsed as a humantime duration string.
    #[serde(default, with = "humantime_serde::option")]
    pub timeout: Option<Duration>,
    /// Retry count; default `0`.
    #[serde(default)]
    pub retries: u32,
    /// Required flag; default `true`.
    #[serde(default = "default_required")]
    pub required: bool,
    /// Fail-fast policy; default `true`. Inherits the webhook classifier.
    #[serde(default = "default_fail_fast")]
    pub fail_fast: bool,
}

fn default_teams_title() -> String {
    super::teams::DEFAULT_TEAMS_TITLE_TEMPLATE.to_string()
}

/// YAML payload for [`TriggerConfig::Post`]. Migration-friendly shape
/// for operators coming from pyaviso's `post` trigger: URL plus
/// optional custom headers; no `body_template` field because the body
/// is the server's `CloudEvent` envelope, forwarded verbatim from the
/// SSE wire when available and reconstructed from the lib's narrowed
/// fields only as a test-fixture fallback.
#[non_exhaustive]
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PostTriggerConfig {
    /// URL template; rendered through the in-crate template engine at
    /// dispatch time.
    pub url: String,
    /// Headers to attach to the request. Header names are taken
    /// literally; header values are template-rendered at dispatch.
    #[serde(default)]
    pub headers: BTreeMap<String, String>,
    /// Per-trigger timeout. Parsed as a humantime duration string.
    #[serde(default, with = "humantime_serde::option")]
    pub timeout: Option<Duration>,
    /// Retry count; default `0`.
    #[serde(default)]
    pub retries: u32,
    /// Required flag; default `true`.
    #[serde(default = "default_required")]
    pub required: bool,
    /// Fail-fast policy; default `true`. Inherits the webhook classifier.
    #[serde(default = "default_fail_fast")]
    pub fail_fast: bool,
}

impl TriggerConfig {
    /// Convert the declarative config into a strongly-typed
    /// [`Trigger`] builder, applying all per-variant defaults.
    #[must_use]
    pub fn into_trigger(self) -> Trigger {
        match self {
            Self::Echo(cfg) => Trigger::echo().retries(cfg.retries).required(cfg.required),
            Self::Log(cfg) => Trigger::log(cfg.path)
                .retries(cfg.retries)
                .required(cfg.required),
            #[cfg(unix)]
            Self::Command(cfg) => {
                let mut t = Trigger::command(cfg.command);
                for (k, v) in cfg.env {
                    t = t.env(k, v);
                }
                if let Some(d) = cfg.working_dir {
                    t = t.working_dir(d);
                }
                if let Some(d) = cfg.timeout {
                    t = t.timeout(d);
                }
                t.retries(cfg.retries)
                    .required(cfg.required)
                    .fail_fast(cfg.fail_fast)
            }
            Self::Webhook(cfg) => {
                let mut t = Trigger::webhook(cfg.url);
                if let Some(m) = cfg.method {
                    t = t.method(m);
                }
                for (k, v) in cfg.headers {
                    t = t.header(k, v);
                }
                if let Some(b) = cfg.body_template {
                    t = t.body_template(b);
                }
                if let Some(d) = cfg.timeout {
                    t = t.timeout(d);
                }
                t.retries(cfg.retries)
                    .required(cfg.required)
                    .fail_fast(cfg.fail_fast)
            }
            Self::Teams(cfg) => {
                let mut t = Trigger::teams(cfg.url).title_template(cfg.title_template);
                if let Some(d) = cfg.timeout {
                    t = t.timeout(d);
                }
                t.retries(cfg.retries)
                    .required(cfg.required)
                    .fail_fast(cfg.fail_fast)
            }
            Self::Post(cfg) => {
                let mut t = Trigger::post(cfg.url);
                for (k, v) in cfg.headers {
                    t = t.post_header(k, v);
                }
                if let Some(d) = cfg.timeout {
                    t = t.timeout(d);
                }
                t.retries(cfg.retries)
                    .required(cfg.required)
                    .fail_fast(cfg.fail_fast)
            }
        }
    }
}

fn default_required() -> bool {
    true
}

fn default_fail_fast() -> bool {
    true
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::panic,
    reason = "test code: unwrap on YAML deserialisation success and panic on unexpected variant are the standard test diagnostics"
)]
mod tests {
    use super::{EchoConfig, HttpMethod, TriggerConfig};
    use crate::watch::trigger::kind::TriggerKind;

    fn parse(yaml: &str) -> TriggerConfig {
        serde_norway::from_str::<TriggerConfig>(yaml).unwrap()
    }

    fn parse_err(yaml: &str) -> serde_norway::Error {
        serde_norway::from_str::<TriggerConfig>(yaml).unwrap_err()
    }

    #[test]
    fn echo_config_default_matches_yaml_serde_defaults_field_for_field() {
        let from_default = EchoConfig::default();
        let from_yaml: EchoConfig = serde_norway::from_str("{}").unwrap();
        assert_eq!(
            from_default.retries, 0,
            "Default::default must produce retries = 0 to match the serde default for an omitted field",
        );
        assert!(
            from_default.required,
            "Default::default must produce required = true to match the YAML default; without this, programmatic constructors of EchoConfig (the CLI inline-listen path) silently get a non-required trigger when the YAML deserialiser would have produced a required one, breaking the at-least-once contract",
        );
        assert_eq!(
            from_default.retries, from_yaml.retries,
            "Default::default and serde::from_str(\"{{}}\") MUST agree on retries; if they diverge, switching between YAML and programmatic construction silently changes operator-observable behavior",
        );
        assert_eq!(
            from_default.required, from_yaml.required,
            "Default::default and serde::from_str(\"{{}}\") MUST agree on required; if they diverge, switching between YAML and programmatic construction silently changes operator-observable behavior",
        );
    }

    #[test]
    fn yaml_deserialise_echo_with_defaults() {
        let cfg = parse("type: echo\n");
        match cfg {
            TriggerConfig::Echo(echo) => {
                assert_eq!(echo.retries, 0);
                assert!(echo.required);
            }
            other => panic!("expected Echo, got {other:?}"),
        }
    }

    #[test]
    fn yaml_deserialise_echo_with_overrides() {
        let cfg = parse("type: echo\nretries: 5\nrequired: false\n");
        match cfg {
            TriggerConfig::Echo(echo) => {
                assert_eq!(echo.retries, 5);
                assert!(!echo.required);
            }
            other => panic!("expected Echo, got {other:?}"),
        }
    }

    #[test]
    fn yaml_deserialise_log_with_path() {
        let cfg = parse("type: log\npath: /tmp/foo.log\n");
        match cfg {
            TriggerConfig::Log(log) => {
                assert_eq!(log.path.to_str(), Some("/tmp/foo.log"));
                assert_eq!(log.retries, 0);
                assert!(log.required);
            }
            other => panic!("expected Log, got {other:?}"),
        }
    }

    #[cfg(unix)]
    #[test]
    fn yaml_deserialise_command_with_full_fields() {
        let yaml = r#"
type: command
command: "echo hi"
env:
  KEY1: value1
  KEY2: value2
working_dir: /tmp
timeout: 30s
retries: 2
required: false
fail_fast: false
"#;
        let cfg = parse(yaml);
        match cfg {
            TriggerConfig::Command(cmd) => {
                assert_eq!(cmd.command, "echo hi");
                assert_eq!(cmd.env.len(), 2);
                assert_eq!(cmd.env.get("KEY1").map(String::as_str), Some("value1"));
                assert_eq!(
                    cmd.working_dir.as_deref().and_then(std::path::Path::to_str),
                    Some("/tmp")
                );
                assert_eq!(cmd.timeout, Some(std::time::Duration::from_secs(30)));
                assert_eq!(cmd.retries, 2);
                assert!(!cmd.required);
                assert!(!cmd.fail_fast);
            }
            other => panic!("expected Command, got {other:?}"),
        }
    }

    #[test]
    fn yaml_deserialise_webhook_with_full_fields() {
        let yaml = r#"
type: webhook
url: "https://hooks.example.org/notify"
method: PUT
headers:
  X-Foo: bar
  Authorization: "Bearer secret"
body_template: '{"k":"v"}'
timeout: 1m30s
retries: 3
required: false
fail_fast: false
"#;
        let cfg = parse(yaml);
        match cfg {
            TriggerConfig::Webhook(wh) => {
                assert_eq!(wh.url, "https://hooks.example.org/notify");
                assert_eq!(wh.method, Some(HttpMethod::Put));
                assert_eq!(wh.headers.len(), 2);
                assert_eq!(wh.body_template.as_deref(), Some("{\"k\":\"v\"}"));
                assert_eq!(wh.timeout, Some(std::time::Duration::from_secs(90)));
                assert_eq!(wh.retries, 3);
                assert!(!wh.required);
                assert!(!wh.fail_fast);
            }
            other => panic!("expected Webhook, got {other:?}"),
        }
    }

    #[test]
    fn yaml_deserialise_timeout_humantime_formats() {
        for (input, expected_secs) in [("30s", 30), ("2m", 120), ("1h", 3600), ("1h30m", 5400)] {
            let yaml = format!("type: webhook\nurl: https://x\ntimeout: {input}\n");
            let cfg = parse(&yaml);
            match cfg {
                TriggerConfig::Webhook(wh) => assert_eq!(
                    wh.timeout,
                    Some(std::time::Duration::from_secs(expected_secs)),
                    "input: {input}"
                ),
                other => panic!("expected Webhook, got {other:?}"),
            }
        }
    }

    #[test]
    fn yaml_deserialise_timeout_milliseconds_format() {
        let cfg = parse("type: webhook\nurl: https://x\ntimeout: 500ms\n");
        match cfg {
            TriggerConfig::Webhook(wh) => {
                assert_eq!(wh.timeout, Some(std::time::Duration::from_millis(500)));
            }
            other => panic!("expected Webhook, got {other:?}"),
        }
    }

    #[test]
    fn yaml_deserialise_unknown_type_fails_with_clear_message() {
        let err = parse_err("type: comand\n");
        let message = err.to_string();
        assert!(
            message.contains("comand") || message.contains("unknown variant"),
            "error should name the bad variant: {message}"
        );
    }

    #[test]
    fn yaml_deserialise_unknown_field_within_echo_fails() {
        let err = parse_err("type: echo\nbogus_field: 1\n");
        let message = err.to_string();
        assert!(
            message.contains("bogus_field") || message.contains("unknown field"),
            "error should name the bad field: {message}"
        );
    }

    #[test]
    fn yaml_deserialise_unknown_field_within_log_fails() {
        let err = parse_err("type: log\npath: /tmp/x\nbogus_field: 1\n");
        let message = err.to_string();
        assert!(
            message.contains("bogus_field") || message.contains("unknown field"),
            "error should name the bad field: {message}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn yaml_deserialise_unknown_field_within_command_fails() {
        let err = parse_err("type: command\ncommand: \"true\"\nbogus_field: 1\n");
        let message = err.to_string();
        assert!(
            message.contains("bogus_field") || message.contains("unknown field"),
            "error should name the bad field: {message}"
        );
    }

    #[test]
    fn yaml_deserialise_unknown_field_within_webhook_fails() {
        let err = parse_err("type: webhook\nurl: https://x\nbogus_field: 1\n");
        let message = err.to_string();
        assert!(
            message.contains("bogus_field") || message.contains("unknown field"),
            "error should name the bad field: {message}"
        );
    }

    #[test]
    fn yaml_method_uppercase_required() {
        let cfg = parse("type: webhook\nurl: https://x\nmethod: POST\n");
        match cfg {
            TriggerConfig::Webhook(wh) => assert_eq!(wh.method, Some(HttpMethod::Post)),
            other => panic!("expected Webhook, got {other:?}"),
        }
    }

    #[test]
    fn yaml_method_lowercase_fails() {
        let err = parse_err("type: webhook\nurl: https://x\nmethod: post\n");
        let message = err.to_string();
        assert!(
            message.contains("unknown variant") || message.contains("post"),
            "lowercase method should fail: {message}"
        );
    }

    #[test]
    fn yaml_to_trigger_round_trip_echo() {
        let cfg = parse("type: echo\nretries: 3\nrequired: false\n");
        let trigger = cfg.into_trigger();
        assert_eq!(trigger.retries, 3);
        assert!(!trigger.required);
        assert!(matches!(trigger.kind, TriggerKind::Echo { .. }));
    }

    #[test]
    fn yaml_to_trigger_round_trip_webhook_applies_method_header_body() {
        let yaml = r#"
type: webhook
url: "https://hooks.example.org/notify"
method: PATCH
headers:
  X-Custom: value
body_template: '{"x":1}'
timeout: 5s
retries: 1
"#;
        let cfg = parse(yaml);
        let trigger = cfg.into_trigger();
        assert_eq!(trigger.retries, 1);
        assert!(trigger.required);
        assert_eq!(trigger.timeout, Some(std::time::Duration::from_secs(5)));
        assert!(matches!(trigger.kind, TriggerKind::Webhook(_)));
    }

    #[test]
    fn yaml_deserialise_teams_with_defaults() {
        let cfg = parse("type: teams\nurl: \"https://example/workflow\"\n");
        match cfg {
            TriggerConfig::Teams(teams) => {
                assert_eq!(teams.url, "https://example/workflow");
                assert!(
                    teams.title_template.contains("notification.event_type"),
                    "default title template must reference notification.event_type: {}",
                    teams.title_template
                );
                assert_eq!(teams.retries, 0);
                assert!(teams.required);
            }
            other => panic!("expected Teams, got {other:?}"),
        }
    }

    #[test]
    fn yaml_deserialise_teams_with_explicit_title_template() {
        let yaml = r#"
type: teams
url: "{{ env.TEAMS_WEBHOOK_URL }}"
title_template: "custom: {{ notification.event_type }} #{{ notification.sequence }}"
retries: 2
timeout: 10s
"#;
        let cfg = parse(yaml);
        match cfg {
            TriggerConfig::Teams(teams) => {
                assert_eq!(teams.url, "{{ env.TEAMS_WEBHOOK_URL }}");
                assert_eq!(
                    teams.title_template,
                    "custom: {{ notification.event_type }} #{{ notification.sequence }}"
                );
                assert_eq!(teams.retries, 2);
                assert_eq!(teams.timeout, Some(std::time::Duration::from_secs(10)));
            }
            other => panic!("expected Teams, got {other:?}"),
        }
    }

    #[test]
    fn yaml_teams_to_trigger_produces_teams_kind() {
        let yaml = r#"
type: teams
url: "https://example/workflow"
title_template: "aviso fires"
"#;
        let cfg = parse(yaml);
        let trigger = cfg.into_trigger();
        assert!(
            matches!(trigger.kind, TriggerKind::Teams(_)),
            "type: teams must produce TriggerKind::Teams (was a webhook desugaring before; now a proper kind that builds the Adaptive Card from the notification at dispatch time)"
        );
        assert_eq!(trigger.retries, 0);
        assert!(trigger.required);
    }
}