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
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::{schema::DeployWorkloadToken, AppId};

// TODO: Figure out token type.
pub type RawToken = String;

/// Id of the node - aka server.
pub type NodeId = Uuid;

/// Id of a single Webassembly instance.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct InstanceId(Uuid);

impl InstanceId {
    pub fn new_random() -> Self {
        Self(Uuid::new_v4())
    }

    pub fn to_uuid(&self) -> Uuid {
        self.0
    }

    pub fn from_uuid(uuid: Uuid) -> Self {
        Self(uuid)
    }
}

impl std::fmt::Display for InstanceId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::str::FromStr for InstanceId {
    type Err = uuid::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(Uuid::parse_str(s)?))
    }
}

impl From<uuid::Uuid> for InstanceId {
    fn from(uuid: uuid::Uuid) -> Self {
        Self(uuid)
    }
}

impl From<InstanceId> for uuid::Uuid {
    fn from(id: InstanceId) -> Self {
        id.0
    }
}

/// Metadata for a running instance.
#[derive(Debug, Clone, Serialize)]
pub struct InstanceMeta {
    /// Token used to create the instance.
    ///
    /// Allows associating the instance with an agent.
    pub token: DeployWorkloadToken,

    /// Unique, randomly generated UUID for the instance.
    pub id: InstanceId,

    /// The ID of the app
    pub app_id: Option<AppId>,

    /// Id for the agent that authorized a workload.
    ///
    /// Usually a user id from the backend.
    pub agent_id: String,
}

impl InstanceMeta {
    pub fn new_for_token(token: DeployWorkloadToken, app_id: Option<AppId>) -> Self {
        Self {
            agent_id: token.data.subject().to_string(),
            token,
            id: InstanceId::new_random(),
            app_id,
        }
    }
}