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
use serde::{Deserialize, Serialize, Serializer};
use std::collections::{HashMap, HashSet};

/// Container name
pub type Name = crate::common::name::Name;
/// Container identification
pub type Container = crate::common::container::Container;
/// Container exit code
pub type ExitCode = i32;
/// Manifest
pub type Manifest = crate::npk::manifest::Manifest;
/// String that never contains a null byte
pub type NonNulString = crate::common::non_nul_string::NonNulString;
/// Process id
pub type Pid = u32;
/// Repository id
pub type RepositoryId = String;
/// Unix signal
pub type Signal = u32;
/// Version
pub type Version = crate::common::version::Version;
/// Container statistics
pub type ContainerStats = HashMap<String, serde_json::Value>;

/// Message
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[allow(missing_docs)]
#[serde(untagged)]
pub enum Message {
    Connect { connect: Connect },
    ConnectAck { connect_ack: ConnectAck },
    ConnectNack { connect_nack: ConnectNack },
    Request { request: Request },
    Response { response: Response },
    Notification { notification: Notification },
}

/// Notification / Event
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum Notification {
    CGroup(Container, CgroupNotification),
    Exit(Container, ExitStatus),
    Install(Container),
    Shutdown,
    Started(Container),
    Uninstall(Container),
}

/// Cgroup event
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum CgroupNotification {
    Memory(MemoryNotification),
}

/// CGroup memory event data
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub struct MemoryNotification {
    pub low: Option<u64>,
    pub high: Option<u64>,
    pub max: Option<u64>,
    pub oom: Option<u64>,
    pub oom_kill: Option<u64>,
}

/// Connect
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub struct Connect {
    /// API version
    pub version: Version,
    /// Subscribe this connection to notifications
    pub subscribe_notifications: bool,
}

/// Connection ack
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub struct ConnectAck;

/// Connection nack
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum ConnectNack {
    InvalidProtocolVersion { version: Version },
    PermissionDenied,
}

/// Request
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum Request {
    Inspect {
        container: Container,
    },
    Ident,
    Install {
        repository: RepositoryId,
        size: u64,
    },
    Kill {
        container: Container,
        signal: i32,
    },
    List,
    Mount {
        containers: Vec<Container>,
    },
    Repositories,
    Shutdown,
    Start {
        container: Container,
        arguments: Vec<NonNulString>,
        environment: HashMap<NonNulString, NonNulString>,
    },
    TokenCreate {
        target: Name,
        #[serde(with = "base64")]
        shared: Vec<u8>,
    },
    TokenVerify {
        token: Token,
        user: Name,
        #[serde(with = "base64")]
        shared: Vec<u8>,
    },
    Umount {
        containers: Vec<Container>,
    },
    Uninstall {
        container: Container,
        wipe: bool,
    },
}

/// Token
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct Token(Vec<u8>);

impl AsRef<[u8]> for Token {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl From<Vec<u8>> for Token {
    fn from(value: Vec<u8>) -> Self {
        Token(value)
    }
}

/// Token verification result
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum VerificationResult {
    /// Verification succeeded
    Ok,
    /// Verification failed
    Invalid,
    /// Token is expired
    Expired,
    /// Token time is in the future
    Future,
}

/// Container information
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct ContainerData {
    /// Container manifest
    pub manifest: Manifest,
    /// Repository in which the container is installed
    pub repository: RepositoryId,
    /// Mount state
    pub mounted: bool,
    /// Process if the container is started
    pub process: Option<Process>,
}

/// Process information
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Process {
    /// Process id
    pub pid: Pid,
    /// Process uptime in nanoseconds
    pub uptime: u64,
    /// Container statistics
    pub statistics: ContainerStats,
}

/// Mount result
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum MountResult {
    Ok { container: Container },
    Error { container: Container, error: Error },
}

/// Unmount result
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum UmountResult {
    Ok { container: Container },
    Error { container: Container, error: Error },
}

/// Start result
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum StartResult {
    Ok { container: Container },
    Error { container: Container, error: Error },
}

/// Kill result
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum KillResult {
    Ok { container: Container },
    Error { container: Container, error: Error },
}

/// Installation result
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum InstallResult {
    Ok { container: Container },
    Error { error: Error },
}

/// Uninstallation result
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum UninstallResult {
    Ok { container: Container },
    Error { container: Container, error: Error },
}

/// Inspect result
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum InspectResult {
    Ok {
        container: Container,
        data: Box<ContainerData>,
    },
    Error {
        container: Container,
        error: Error,
    },
}

/// Response
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum Response {
    Ident(Container),
    Inspect(InspectResult),
    Install(InstallResult),
    Kill(KillResult),
    List(Vec<Container>),
    Mount(Vec<MountResult>),
    PermissionDenied(Request),
    Repositories(HashSet<RepositoryId>),
    Shutdown,
    Start(StartResult),
    Token(Token),
    TokenVerification(VerificationResult),
    Umount(Vec<UmountResult>),
    Uninstall(UninstallResult),
}

/// Container exit status
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExitStatus {
    /// Process exited with exit code
    Exit {
        /// Exit code
        code: ExitCode,
    },
    /// Process was terminated by a signal
    Signalled {
        /// Signal
        signal: Signal,
    },
}

impl ExitStatus {
    /// Exit success
    pub const SUCCESS: ExitCode = 0;

    /// Was termination successful? Signal termination is not considered a success,
    /// and success is defined as a zero exit status.
    pub fn success(&self) -> bool {
        matches!(self, ExitStatus::Exit { code } if *code == Self::SUCCESS)
    }

    /// Returns the exit code of the process, if any.
    pub fn code(&self) -> Option<ExitCode> {
        match self {
            ExitStatus::Exit { code } => Some(*code),
            ExitStatus::Signalled { .. } => None,
        }
    }
}

impl std::fmt::Display for ExitStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ExitStatus::Exit { code } => write!(f, "Exit({code})"),
            ExitStatus::Signalled { signal } => write!(f, "Signalled({signal})"),
        }
    }
}

/// API error
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(missing_docs)]
pub enum Error {
    Configuration {
        context: String,
    },
    DuplicateContainer {
        container: Container,
    },
    InvalidContainer {
        container: Container,
    },
    InvalidArguments {
        cause: String,
    },
    MountBusy {
        container: Container,
    },
    UmountBusy {
        container: Container,
    },
    StartContainerStarted {
        container: Container,
    },
    StartContainerResource {
        container: Container,
    },
    StartContainerMissingResource {
        container: Container,
        resource: Name,
        version: String,
    },
    StartContainerFailed {
        container: Container,
        error: String,
    },
    StopContainerNotStarted {
        container: Container,
    },
    InvalidRepository {
        repository: RepositoryId,
    },
    InstallDuplicate {
        container: Container,
    },
    CriticalContainer {
        container: Container,
        status: ExitStatus,
    },
    Unexpected {
        error: String,
    },
}

impl Serialize for Token {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        if self.0.len() == 40 {
            base64::serialize(&self.0, serializer)
        } else {
            Err(serde::ser::Error::custom("invalid length"))
        }
    }
}

impl<'de> Deserialize<'de> for Token {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let token = base64::deserialize(deserializer)?;
        if token.len() == 40 {
            Ok(Token(token))
        } else {
            Err(serde::de::Error::custom("invalid length"))
        }
    }
}

mod base64 {
    use base64::{engine::general_purpose::STANDARD as Base64, Engine as _};
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    pub fn serialize<S: Serializer>(v: &Vec<u8>, s: S) -> Result<S::Ok, S::Error> {
        let base64 = Base64.encode(v);
        String::serialize(&base64, s)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
        let base64 = String::deserialize(d)?;
        Base64
            .decode(base64.as_bytes())
            .map_err(serde::de::Error::custom)
    }
}