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
//! Common event types expected on wasmbus. These are the inner types generally sent in the `data`
//! attribute of a cloudevent
// TODO: These should probably be generated from a schema which we add into the actual cloud event

use std::{collections::HashMap, convert::TryFrom};

use cloudevents::{AttributesReader, Data, Event as CloudEvent, EventBuilder, EventBuilderV10};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::model::Manifest;

use super::data::*;

/// The source used for cloud events that wadm emits
pub const WADM_SOURCE: &str = "wadm";

// NOTE: this macro is a helper so we don't have to copy/paste these impls for each type. The first
// argument is the struct name you are generating for and the second argument is the event type as
// expected in the cloud event.
//
// There is an optional variant that lets you pull a attribute from the cloud event (third arg) and
// set it to the value in the struct (fourth arg)
macro_rules! event_impl {
    ($t:ident, $type_name:expr) => {
        impl EventType for $t {
            const TYPE: &'static str = $type_name;
        }

        impl From<$t> for Event {
            fn from(value: $t) -> Event {
                Event::$t(value)
            }
        }

        impl std::convert::TryFrom<cloudevents::Event> for $t {
            type Error = ConversionError;

            fn try_from(mut value: cloudevents::Event) -> Result<Self, Self::Error> {
                if $t::TYPE != value.ty() {
                    return Err(ConversionError::WrongEvent(value));
                }
                let (_, _, data) = value.take_data();
                let data = data.ok_or(ConversionError::NoData)?;
                match data {
                    Data::Binary(raw) => serde_json::from_reader(std::io::Cursor::new(raw))
                        .map_err(ConversionError::from),
                    Data::Json(v) => serde_json::from_value(v).map_err(ConversionError::from),
                    Data::String(_) => Err(ConversionError::NoData),
                }
            }
        }
    };

    ($t:ident, $type_name:expr, $event_attr:ident, $data_attr:ident) => {
        impl EventType for $t {
            const TYPE: &'static str = $type_name;
        }

        impl std::convert::TryFrom<cloudevents::Event> for $t {
            type Error = ConversionError;

            fn try_from(mut value: cloudevents::Event) -> Result<Self, Self::Error> {
                if $t::TYPE != value.ty() {
                    return Err(ConversionError::WrongEvent(value));
                }
                let (_, _, data) = value.take_data();
                let data = data.ok_or(ConversionError::NoData)?;
                let mut parsed: Self = match data {
                    Data::Binary(raw) => serde_json::from_reader(std::io::Cursor::new(raw))
                        .map_err(ConversionError::from),
                    Data::Json(v) => serde_json::from_value(v).map_err(ConversionError::from),
                    Data::String(_) => Err(ConversionError::NoData),
                }?;

                parsed.$data_attr = value.$event_attr().to_string();
                Ok(parsed)
            }
        }
    };
}

/// A trait which all events must implement that specifies the string type of the event
pub trait EventType {
    const TYPE: &'static str;
}

/// A lattice event
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub enum Event {
    ActorStarted(ActorStarted),
    ActorsStarted(ActorsStarted),
    ActorsStartFailed(ActorsStartFailed),
    ActorStopped(ActorStopped),
    ActorsStopped(ActorsStopped),
    ProviderStarted(ProviderStarted),
    ProviderStopped(ProviderStopped),
    ProviderStartFailed(ProviderStartFailed),
    ProviderHealthCheckPassed(ProviderHealthCheckPassed),
    ProviderHealthCheckFailed(ProviderHealthCheckFailed),
    ProviderHealthCheckStatus(ProviderHealthCheckStatus),
    HostStarted(HostStarted),
    HostStopped(HostStopped),
    HostHeartbeat(HostHeartbeat),
    LinkdefSet(LinkdefSet),
    LinkdefDeleted(LinkdefDeleted),
    // NOTE(thomastaylor312): We may change where and how these get published, but it makes sense
    // for now to have them here even though they aren't technically lattice events
    ManifestPublished(ManifestPublished),
    ManifestUnpublished(ManifestUnpublished),
}

impl TryFrom<CloudEvent> for Event {
    type Error = ConversionError;

    fn try_from(value: CloudEvent) -> Result<Self, Self::Error> {
        match value.ty() {
            ActorStarted::TYPE => ActorStarted::try_from(value).map(Event::ActorStarted),
            ActorsStarted::TYPE => ActorsStarted::try_from(value).map(Event::ActorsStarted),
            ActorsStartFailed::TYPE => {
                ActorsStartFailed::try_from(value).map(Event::ActorsStartFailed)
            }
            ActorStopped::TYPE => ActorStopped::try_from(value).map(Event::ActorStopped),
            ActorsStopped::TYPE => ActorsStopped::try_from(value).map(Event::ActorsStopped),
            ProviderStarted::TYPE => ProviderStarted::try_from(value).map(Event::ProviderStarted),
            ProviderStopped::TYPE => ProviderStopped::try_from(value).map(Event::ProviderStopped),
            ProviderStartFailed::TYPE => {
                ProviderStartFailed::try_from(value).map(Event::ProviderStartFailed)
            }
            ProviderHealthCheckPassed::TYPE => {
                ProviderHealthCheckPassed::try_from(value).map(Event::ProviderHealthCheckPassed)
            }
            ProviderHealthCheckFailed::TYPE => {
                ProviderHealthCheckFailed::try_from(value).map(Event::ProviderHealthCheckFailed)
            }
            ProviderHealthCheckStatus::TYPE => {
                ProviderHealthCheckStatus::try_from(value).map(Event::ProviderHealthCheckStatus)
            }
            HostStarted::TYPE => HostStarted::try_from(value).map(Event::HostStarted),
            HostStopped::TYPE => HostStopped::try_from(value).map(Event::HostStopped),
            HostHeartbeat::TYPE => HostHeartbeat::try_from(value).map(Event::HostHeartbeat),
            LinkdefSet::TYPE => LinkdefSet::try_from(value).map(Event::LinkdefSet),
            LinkdefDeleted::TYPE => LinkdefDeleted::try_from(value).map(Event::LinkdefDeleted),
            ManifestPublished::TYPE => {
                ManifestPublished::try_from(value).map(Event::ManifestPublished)
            }
            ManifestUnpublished::TYPE => {
                ManifestUnpublished::try_from(value).map(Event::ManifestUnpublished)
            }
            _ => Err(ConversionError::WrongEvent(value)),
        }
    }
}

impl TryFrom<Event> for CloudEvent {
    type Error = anyhow::Error;

    fn try_from(value: Event) -> Result<Self, Self::Error> {
        let ty = match value {
            Event::ActorStarted(_) => ActorStarted::TYPE,
            Event::ActorsStarted(_) => ActorsStarted::TYPE,
            Event::ActorsStartFailed(_) => ActorsStartFailed::TYPE,
            Event::ActorStopped(_) => ActorStopped::TYPE,
            Event::ActorsStopped(_) => ActorsStopped::TYPE,
            Event::ProviderStarted(_) => ProviderStarted::TYPE,
            Event::ProviderStopped(_) => ProviderStopped::TYPE,
            Event::ProviderStartFailed(_) => ProviderStartFailed::TYPE,
            Event::ProviderHealthCheckPassed(_) => ProviderHealthCheckPassed::TYPE,
            Event::ProviderHealthCheckFailed(_) => ProviderHealthCheckFailed::TYPE,
            Event::ProviderHealthCheckStatus(_) => ProviderHealthCheckStatus::TYPE,
            Event::HostStarted(_) => HostStarted::TYPE,
            Event::HostStopped(_) => HostStopped::TYPE,
            Event::HostHeartbeat(_) => HostHeartbeat::TYPE,
            Event::LinkdefSet(_) => LinkdefSet::TYPE,
            Event::LinkdefDeleted(_) => LinkdefDeleted::TYPE,
            Event::ManifestPublished(_) => ManifestPublished::TYPE,
            Event::ManifestUnpublished(_) => ManifestUnpublished::TYPE,
        };

        EventBuilderV10::new()
            .id(uuid::Uuid::new_v4().to_string())
            .source(WADM_SOURCE)
            .time(chrono::Utc::now())
            .data("application/json", serde_json::to_value(value)?)
            .ty(ty)
            .build()
            .map_err(anyhow::Error::from)
    }
}

// Custom serialize that just delegates to the underlying event type
impl Serialize for Event {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Event::ActorStarted(evt) => evt.serialize(serializer),
            Event::ActorsStarted(evt) => evt.serialize(serializer),
            Event::ActorsStartFailed(evt) => evt.serialize(serializer),
            Event::ActorStopped(evt) => evt.serialize(serializer),
            Event::ActorsStopped(evt) => evt.serialize(serializer),
            Event::ProviderStarted(evt) => evt.serialize(serializer),
            Event::ProviderStopped(evt) => evt.serialize(serializer),
            Event::ProviderStartFailed(evt) => evt.serialize(serializer),
            Event::ProviderHealthCheckPassed(evt) => evt.serialize(serializer),
            Event::ProviderHealthCheckFailed(evt) => evt.serialize(serializer),
            Event::ProviderHealthCheckStatus(evt) => evt.serialize(serializer),
            Event::HostStarted(evt) => evt.serialize(serializer),
            Event::HostStopped(evt) => evt.serialize(serializer),
            Event::HostHeartbeat(evt) => evt.serialize(serializer),
            Event::LinkdefSet(evt) => evt.serialize(serializer),
            Event::LinkdefDeleted(evt) => evt.serialize(serializer),
            Event::ManifestPublished(evt) => evt.serialize(serializer),
            Event::ManifestUnpublished(evt) => evt.serialize(serializer),
        }
    }
}

impl Event {
    /// Convenience shorthand for calling `TryFrom` on cloudevent
    pub fn new(evt: CloudEvent) -> Result<Event, ConversionError> {
        Event::try_from(evt)
    }

    /// Returns the underlying raw cloudevent type for the event
    pub fn raw_type(&self) -> &str {
        match self {
            Event::ActorStarted(_) => ActorStarted::TYPE,
            Event::ActorsStarted(_) => ActorsStarted::TYPE,
            Event::ActorsStartFailed(_) => ActorsStartFailed::TYPE,
            Event::ActorStopped(_) => ActorStopped::TYPE,
            Event::ActorsStopped(_) => ActorsStopped::TYPE,
            Event::ProviderStarted(_) => ProviderStarted::TYPE,
            Event::ProviderStopped(_) => ProviderStopped::TYPE,
            Event::ProviderStartFailed(_) => ProviderStopped::TYPE,
            Event::ProviderHealthCheckPassed(_) => ProviderHealthCheckPassed::TYPE,
            Event::ProviderHealthCheckFailed(_) => ProviderHealthCheckFailed::TYPE,
            Event::ProviderHealthCheckStatus(_) => ProviderHealthCheckStatus::TYPE,
            Event::HostStarted(_) => HostStarted::TYPE,
            Event::HostStopped(_) => HostStopped::TYPE,
            Event::HostHeartbeat(_) => HostHeartbeat::TYPE,
            Event::LinkdefSet(_) => LinkdefSet::TYPE,
            Event::LinkdefDeleted(_) => LinkdefDeleted::TYPE,
            Event::ManifestPublished(_) => ManifestPublished::TYPE,
            Event::ManifestUnpublished(_) => ManifestUnpublished::TYPE,
        }
    }
}

/// An error returned when attempting to convert a cloudevent to the desired type. If the event type
/// doesn't match, `WrongEvent` is returned with the original event
#[derive(Debug, Error)]
pub enum ConversionError {
    /// An unrecognized event was found when trying to convert it to the event type. Returns the
    /// original cloudevents event
    #[error("Wrong event type")]
    WrongEvent(CloudEvent),
    /// If an event of the right type was found, but no data was contained within that event
    #[error("No data found")]
    NoData,
    /// An error occured while trying to deserialize the data
    #[error("Error when deserializing: {0}")]
    Deser(#[from] serde_json::Error),
}

//
// EVENTS START HERE
//

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ActorStarted {
    pub annotations: HashMap<String, String>,
    // Commented out for now because the host broken it and we actually don't use this right now
    // pub api_version: usize,
    pub claims: ActorClaims,
    pub image_ref: String,
    // TODO: Parse as UUID?
    pub instance_id: String,
    // TODO: Parse as nkey?
    pub public_key: String,
    #[serde(default)]
    pub host_id: String,
}

event_impl!(
    ActorStarted,
    "com.wasmcloud.lattice.actor_started",
    source,
    host_id
);

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ActorsStarted {
    pub annotations: HashMap<String, String>,
    // Commented out for now because the host broken it and we actually don't use this right now
    // pub api_version: usize,
    pub claims: ActorClaims,
    pub image_ref: String,
    pub count: usize,
    // TODO: Parse as nkey?
    pub public_key: String,
    #[serde(default)]
    pub host_id: String,
}

event_impl!(
    ActorsStarted,
    "com.wasmcloud.lattice.actors_started",
    source,
    host_id
);

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ActorsStartFailed {
    pub annotations: HashMap<String, String>,
    pub image_ref: String,
    // TODO: Parse as nkey?
    pub public_key: String,
    #[serde(default)]
    pub host_id: String,
    pub error: String,
}

event_impl!(
    ActorsStartFailed,
    "com.wasmcloud.lattice.actors_start_failed",
    source,
    host_id
);

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ActorStopped {
    #[serde(default)]
    pub annotations: HashMap<String, String>,
    pub instance_id: String,
    // TODO: Parse as nkey?
    pub public_key: String,
    #[serde(default)]
    pub host_id: String,
}

event_impl!(
    ActorStopped,
    "com.wasmcloud.lattice.actor_stopped",
    source,
    host_id
);

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ActorsStopped {
    #[serde(default)]
    pub annotations: HashMap<String, String>,
    // TODO: Parse as nkey?
    pub public_key: String,
    #[serde(default)]
    pub host_id: String,
    /// Number of actors stopped from this command
    pub count: usize,
    /// Remaining number of this actor running on the host
    pub remaining: usize,
}

event_impl!(
    ActorsStopped,
    "com.wasmcloud.lattice.actors_stopped",
    source,
    host_id
);

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ProviderStarted {
    pub annotations: HashMap<String, String>,
    pub claims: ProviderClaims,
    pub contract_id: String,
    pub image_ref: String,
    // TODO: parse as UUID?
    pub instance_id: String,
    pub link_name: String,
    // TODO: parse as nkey?
    pub public_key: String,
    #[serde(default)]
    pub host_id: String,
}

event_impl!(
    ProviderStarted,
    "com.wasmcloud.lattice.provider_started",
    source,
    host_id
);

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ProviderStartFailed {
    pub error: String,
    pub link_name: String,
    pub provider_ref: String,
    #[serde(default)]
    pub host_id: String,
}

event_impl!(
    ProviderStartFailed,
    "com.wasmcloud.lattice.provider_start_failed",
    source,
    host_id
);

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ProviderStopped {
    #[serde(default)]
    // TODO(thomastaylor312): Yep, there was a spelling bug in the host is 0.62.1. Revert this once
    // 0.62.2 is out
    #[serde(rename = "annotaions")]
    pub annotations: HashMap<String, String>,
    pub contract_id: String,
    // TODO: parse as UUID?
    pub instance_id: String,
    pub link_name: String,
    // TODO: parse as nkey?
    pub public_key: String,
    // We should probably do an actual enum here, but elixir definitely isn't doing it
    pub reason: String,
    #[serde(default)]
    pub host_id: String,
}

event_impl!(
    ProviderStopped,
    "com.wasmcloud.lattice.provider_stopped",
    source,
    host_id
);

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ProviderHealthCheckPassed {
    #[serde(flatten)]
    pub data: ProviderHealthCheckInfo,
    #[serde(default)]
    pub host_id: String,
}

event_impl!(
    ProviderHealthCheckPassed,
    "com.wasmcloud.lattice.health_check_passed",
    source,
    host_id
);

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ProviderHealthCheckFailed {
    #[serde(flatten)]
    pub data: ProviderHealthCheckInfo,
    #[serde(default)]
    pub host_id: String,
}

event_impl!(
    ProviderHealthCheckFailed,
    "com.wasmcloud.lattice.health_check_failed",
    source,
    host_id
);

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ProviderHealthCheckStatus {
    #[serde(flatten)]
    pub data: ProviderHealthCheckInfo,
    #[serde(default)]
    pub host_id: String,
}

event_impl!(
    ProviderHealthCheckStatus,
    "com.wasmcloud.lattice.health_check_status",
    source,
    host_id
);

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct LinkdefSet {
    #[serde(flatten)]
    pub linkdef: Linkdef,
}

event_impl!(LinkdefSet, "com.wasmcloud.lattice.linkdef_set");

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct LinkdefDeleted {
    #[serde(flatten)]
    pub linkdef: Linkdef,
}

event_impl!(LinkdefDeleted, "com.wasmcloud.lattice.linkdef_deleted");

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct HostStarted {
    pub labels: HashMap<String, String>,
    pub friendly_name: String,
    // TODO: Parse as nkey?
    #[serde(default)]
    pub id: String,
}

event_impl!(
    HostStarted,
    "com.wasmcloud.lattice.host_started",
    source,
    id
);

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct HostStopped {
    pub labels: HashMap<String, String>,
    // TODO: Parse as nkey?
    #[serde(default)]
    pub id: String,
}

event_impl!(
    HostStopped,
    "com.wasmcloud.lattice.host_stopped",
    source,
    id
);

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct HostHeartbeat {
    pub actors: HashMap<String, usize>,
    pub friendly_name: String,
    pub labels: HashMap<String, String>,
    #[serde(default)]
    pub annotations: HashMap<String, String>,
    pub providers: Vec<ProviderInfo>,
    pub uptime_human: String,
    pub uptime_seconds: usize,
    pub version: semver::Version,
    // TODO: Parse as nkey?
    #[serde(default)]
    pub id: String,
}

event_impl!(
    HostHeartbeat,
    "com.wasmcloud.lattice.host_heartbeat",
    source,
    id
);

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ManifestPublished {
    #[serde(flatten)]
    pub manifest: Manifest,
}

event_impl!(ManifestPublished, "com.wadm.manifest_published");

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ManifestUnpublished {
    pub name: String,
}

event_impl!(ManifestUnpublished, "com.wadm.manifest_unpublished");

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

    const NON_SUPPORTED_EVENT: &str = r#"
    {
        "data": {
            "oci_url": "wasmcloud.azurecr.io/httpserver:0.16.0",
            "public_key": "VAG3QITQQ2ODAOWB5TTQSDJ53XK3SHBEIFNK4AYJ5RKAX2UNSCAPHA5M"
        },
        "datacontenttype": "application/json",
        "id": "2435a9d8-8ff9-4715-8d21-2f0dc128ec48",
        "source": "NB6PMW4RGLBP3NAVUVO2IH34VFJFSX7LF7TJOQCDU4GGUGF3P57SZLPX",
        "specversion": "1.0",
        "time": "2023-02-14T19:21:09.018468Z",
        "type": "com.wasmcloud.lattice.refmap_set"
    }
    "#;

    #[test]
    fn test_non_supported_event() {
        let raw: cloudevents::Event = serde_json::from_str(NON_SUPPORTED_EVENT).unwrap();

        let err = Event::new(raw).expect_err("Should have errored on a non-supported event");

        assert!(
            matches!(err, ConversionError::WrongEvent(_)),
            "Should have returned wrong event error"
        );
    }

    #[test]
    fn test_all_supported_events() {
        let raw = std::fs::read("./test/data/events.json").expect("Unable to load test data");

        let all_events: Vec<cloudevents::Event> = serde_json::from_slice(&raw).unwrap();

        for evt in all_events.into_iter() {
            println!("EVT {:?}", evt);
            Event::new(evt).expect("Should be able to parse event");
        }
    }
}