plane_common/types/
mod.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
use crate::{
    names::{AnyNodeName, BackendName, ControllerName, DroneName},
    util::{random_prefixed_string, random_token},
    PlaneClient,
};
pub use backend_state::{BackendState, BackendStatus, TerminationKind, TerminationReason};
use bollard::auth::DockerCredentials;
use chrono::Duration;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::{collections::HashMap, fmt::Display, ops::Deref, path::PathBuf, str::FromStr};

pub mod backend_state;

#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq, Hash, Eq)]
pub struct NodeId(i32);

impl From<i32> for NodeId {
    fn from(i: i32) -> Self {
        Self(i)
    }
}

impl NodeId {
    pub fn as_i32(&self) -> i32 {
        self.0
    }
}

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

#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, Hash, valuable::Valuable)]
pub struct ClusterName(String);

impl ClusterName {
    pub fn is_https(&self) -> bool {
        let port = self.0.split_once(':').map(|x| x.1);
        port.is_none() || port == Some("443")
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

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

impl FromStr for ClusterName {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut parts = s.splitn(2, ':');
        let host = parts.next().ok_or("missing hostname or ip")?;
        let port = parts.next();

        url::Host::parse(host).map_err(|_| "invalid hostname or ip")?;
        if let Some(port) = port {
            port.parse::<u16>().map_err(|_| "invalid port")?;
        }

        Ok(Self(s.to_string()))
    }
}

#[derive(
    Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, valuable::Valuable,
)]
pub struct DronePoolName(String);

impl DronePoolName {
    pub fn is_default(&self) -> bool {
        self == &Self::default()
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl From<String> for DronePoolName {
    fn from(s: String) -> Self {
        DronePoolName(s)
    }
}

impl From<&str> for DronePoolName {
    fn from(s: &str) -> Self {
        DronePoolName(s.to_string())
    }
}

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

impl Deref for DronePoolName {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[derive(Clone, Copy, Serialize, Deserialize, Debug, Default, valuable::Valuable, PartialEq)]
pub enum PullPolicy {
    #[default]
    IfNotPresent,
    Always,
    Never,
}

#[serde_with::serde_as]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(transparent)]
pub struct DockerCpuPeriod(
    #[serde_as(as = "serde_with::DurationMicroSeconds<u64>")] std::time::Duration,
);

impl valuable::Valuable for DockerCpuPeriod {
    fn as_value(&self) -> valuable::Value {
        valuable::Value::U128(self.0.as_micros())
    }

    fn visit(&self, visit: &mut dyn valuable::Visit) {
        visit.visit_value(self.as_value())
    }
}

impl Default for DockerCpuPeriod {
    fn default() -> Self {
        Self(std::time::Duration::from_millis(100))
    }
}

impl From<&DockerCpuPeriod> for std::time::Duration {
    fn from(value: &DockerCpuPeriod) -> Self {
        value.0
    }
}

#[serde_with::serde_as]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(transparent)]
pub struct DockerCpuTimeLimit(
    #[serde_as(as = "serde_with::DurationSeconds<u64>")] pub std::time::Duration,
);

impl valuable::Valuable for DockerCpuTimeLimit {
    fn as_value(&self) -> valuable::Value {
        valuable::Value::U64(self.0.as_secs())
    }

    fn visit(&self, visit: &mut dyn valuable::Visit) {
        visit.visit_value(self.as_value())
    }
}

#[serde_with::serde_as]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, valuable::Valuable)]
pub struct ResourceLimits {
    /// Period of cpu time (de/serializes as microseconds)
    pub cpu_period: Option<DockerCpuPeriod>,

    /// Proportion of period used by container
    pub cpu_period_percent: Option<u8>,

    /// Total cpu time allocated to container
    pub cpu_time_limit: Option<DockerCpuTimeLimit>,

    /// Maximum amount of memory container can use (in bytes)
    pub memory_limit_bytes: Option<i64>,

    /// Maximum disk space container can use (in bytes)
    pub disk_limit_bytes: Option<i64>,
}

impl ResourceLimits {
    pub fn cpu_quota(&self) -> Option<std::time::Duration> {
        let pc = self.cpu_period_percent?;
        let cpu_period = self.cpu_period.clone().unwrap_or_default();

        let quota = cpu_period.0.mul_f64((pc as f64) / 100.0);
        Some(quota)
    }
}

#[derive(Clone, Serialize, Deserialize, Debug, valuable::Valuable, PartialEq)]
#[serde(untagged)]
pub enum DockerRegistryAuth {
    UsernamePassword { username: String, password: String },
}

impl From<DockerRegistryAuth> for DockerCredentials {
    fn from(
        DockerRegistryAuth::UsernamePassword { username, password }: DockerRegistryAuth,
    ) -> Self {
        DockerCredentials {
            username: Some(username),
            password: Some(password),
            ..Default::default()
        }
    }
}

// A spawn requestor can provide a mount parameter, which can be a string or a boolean.
#[derive(Debug, Clone, Serialize, Deserialize, valuable::Valuable, PartialEq)]
#[serde(untagged)]
pub enum Mount {
    Bool(bool),
    Path(PathBuf),
}

#[derive(Clone, Serialize, Deserialize, Debug, valuable::Valuable, PartialEq)]
pub struct DockerExecutorConfig {
    pub image: String,
    pub pull_policy: Option<PullPolicy>,
    pub credentials: Option<DockerRegistryAuth>,
    #[serde(default)]
    pub env: HashMap<String, String>,
    #[serde(default)]
    pub resource_limits: ResourceLimits,
    pub mount: Option<Mount>,
    pub network_name: Option<String>,
}

impl DockerExecutorConfig {
    pub fn from_image_with_defaults<T: Into<String>>(image: T) -> Self {
        Self {
            image: image.into(),
            pull_policy: None,
            env: HashMap::default(),
            resource_limits: ResourceLimits::default(),
            credentials: None,
            mount: None,
            network_name: None,
        }
    }
}

#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct SpawnConfig {
    /// ID to assign to the new backend. Must be unique.
    /// This should only be used if you really need it, otherwise you can leave it blank
    /// and let Plane assign a unique ID automatically. This may be removed from
    /// future versions of Plane.
    pub id: Option<BackendName>,

    /// Cluster to spawn to. Uses the controller default if not provided.
    pub cluster: Option<ClusterName>,

    /// The drone pool to use for the connect request.
    #[serde(default)]
    pub pool: DronePoolName,

    /// Config to use to spawn the backend process.
    pub executable: Value,

    /// If provided, the maximum amount of time the backend will be allowed to
    /// stay alive. Time counts from when the backend is scheduled.
    pub lifetime_limit_seconds: Option<i32>,

    /// If provided, the maximum amount of time the backend will be allowed to
    /// stay alive with no inbound connections to it.
    pub max_idle_seconds: Option<i32>,

    /// If true, the backend will have a single connection token associated with it at spawn
    /// time instead of dynamic tokens for each user.
    #[serde(default)]
    pub use_static_token: bool,

    pub subdomain: Option<Subdomain>,
}

#[derive(
    Clone, Serialize, Deserialize, Debug, Default, PartialEq, Eq, Hash, valuable::Valuable,
)]
pub struct KeyConfig {
    /// If provided, and a running backend was created with the same key,
    /// namespace, and tag, we will connect to that backend instead
    /// of creating a new one.
    pub name: String,

    /// Namespace of the key. If not specified, the default namespace (empty string)
    /// is used.
    #[serde(default)]
    pub namespace: String,

    /// If we request a connection to a key and the backend for that key
    /// is running, we will only connect to it if the tag matches the tag
    /// of the connection request that created it.
    #[serde(default)]
    pub tag: String,
}

impl KeyConfig {
    pub fn new_random() -> Self {
        Self {
            name: random_prefixed_string("lk"),
            ..Default::default()
        }
    }
}

#[derive(Clone, Serialize, Deserialize, Debug, Default)]
pub struct ConnectRequest {
    /// Configuration for the key to use.
    #[serde(default)]
    pub key: Option<KeyConfig>,

    /// Config to use if we need to create a new backend to connect to.
    pub spawn_config: Option<SpawnConfig>,

    /// Username or other identifier to associate with the generated connection URL.
    /// Passed to the backend through the X-Plane-User header.
    pub user: Option<String>,

    /// Arbitrary JSON object to pass along with each request to the backend.
    /// Passed to the backend through the X-Plane-Auth header.
    #[serde(default)]
    pub auth: Map<String, Value>,
}

#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, Hash, valuable::Valuable)]
pub struct BearerToken(String);

const STATIC_TOKEN_PREFIX: &str = "s.";

impl BearerToken {
    pub fn new_random_static() -> Self {
        Self(format!("{}{}", STATIC_TOKEN_PREFIX, random_token()))
    }

    pub fn is_static(&self) -> bool {
        self.0.starts_with(STATIC_TOKEN_PREFIX)
    }
}

impl From<String> for BearerToken {
    fn from(s: String) -> Self {
        Self(s)
    }
}

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

#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, valuable::Valuable)]
pub struct SecretToken(String);

impl From<String> for SecretToken {
    fn from(s: String) -> Self {
        Self(s)
    }
}

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

impl SecretToken {
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct ConnectResponse {
    pub backend_id: BackendName,

    /// Whether the backend is a new one spawned due to the request.
    pub spawned: bool,

    pub status: BackendStatus,

    pub token: BearerToken,

    pub url: String,

    /// Subdomain associated with the backend, if any.
    pub subdomain: Option<Subdomain>,

    pub secret_token: Option<SecretToken>,

    pub status_url: String,

    /// The drone that spawned this backend, if the request resulted in a spawn.
    pub drone: Option<DroneName>,
}

impl ConnectResponse {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        backend_id: BackendName,
        cluster: &ClusterName,
        spawned: bool,
        status: BackendStatus,
        token: BearerToken,
        secret_token: Option<SecretToken>,
        subdomain: Option<Subdomain>,
        client: &PlaneClient,
        drone: Option<DroneName>,
    ) -> Self {
        let protocol = if cluster.is_https() { "https" } else { "http" };
        let url = if let Some(subdomain) = &subdomain {
            format!("{}://{}.{}/{}/", protocol, subdomain, cluster, token)
        } else {
            format!("{}://{}/{}/", protocol, cluster, token)
        };

        let status_url = client.backend_status_url(&backend_id).to_string();

        Self {
            backend_id,
            spawned,
            status,
            token,
            url,
            subdomain,
            secret_token,
            status_url,
            drone,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Debug)]
pub enum NodeKind {
    Proxy,
    Drone,
    AcmeDnsServer,
}

impl Display for NodeKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let result = serde_json::to_value(self);
        match result {
            Ok(Value::String(v)) => write!(f, "{}", v),
            _ => unreachable!(),
        }
    }
}

impl TryFrom<String> for NodeKind {
    type Error = serde_json::Error;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        serde_json::from_value(Value::String(s))
    }
}

#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct RevokeRequest {
    pub backend_id: BackendName,
    pub user: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DrainResult {
    pub updated: bool,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct DroneState {
    pub ready: bool,
    pub draining: bool,
    #[serde(with = "crate::serialization::serialize_duration_as_seconds")]
    pub last_heartbeat_age: Duration,
    pub backend_count: u32,
    pub node: NodeState,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct NodeState {
    pub name: AnyNodeName,
    pub plane_version: String,
    pub plane_hash: String,
    pub controller: ControllerName,
    #[serde(with = "crate::serialization::serialize_duration_as_seconds")]
    pub controller_heartbeat_age: Duration,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct ClusterState {
    pub drones: Vec<DroneState>,
    pub proxies: Vec<NodeState>,
}

#[derive(thiserror::Error, Debug)]
#[error("Invalid subdomain: {0}")]
pub struct InvalidSubdomain(String);

#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, Hash, valuable::Valuable)]
pub struct Subdomain(String);

impl std::str::FromStr for Subdomain {
    type Err = InvalidSubdomain;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // Subdomains can consist of a-z, 0-9, and '-' but not as the first or last char
        let valid_subdomain = s.chars().all(|c| c.is_alphanumeric() || c == '-')
            && !s.starts_with('-')
            && !s.ends_with('-');
        if valid_subdomain {
            Ok(Subdomain(s.to_string()))
        } else {
            Err(InvalidSubdomain(s.to_string()))
        }
    }
}

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

impl TryFrom<String> for Subdomain {
    type Error = InvalidSubdomain;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        s.parse::<Subdomain>()
    }
}

impl Deref for Subdomain {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}