Skip to main content

isothrum_runner/
port.rs

1//! Two kinds of port number, kept apart by type so one is never stored or reported where the
2//! other is meant:
3//!
4//! - [`GuestPort`]: a port inside a machine (a container's target port, a VM's own port). Nothing
5//!   on this computer answers at it as it is.
6//! - [`HostPort`]: the port a published port is reached at, at the machine's host address. What
7//!   status, the port reservations and the free-port check carry.
8//!
9//! A guest port turns into the host port it is reached at only through its driver: the host port
10//! is the one its tool reports for it (Compose's `PublishedPort`, a Vagrant forward's host side),
11//! read by that driver's adapter, never its own number reused. Each type serializes as the bare
12//! number, and its schema is the bare number's, inlined, so the JSON and the schemas read as
13//! they did.
14
15use std::borrow::Cow;
16use std::fmt;
17
18use serde::{Deserialize, Serialize};
19
20/// A port inside a machine: a container's target port, a VM's own port. Reached from this
21/// computer only through the host port its driver gives it ([`HostPort`]).
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
23#[serde(transparent)]
24pub struct GuestPort(u16);
25
26/// The port a published port is reached at, at its machine's host address: on this computer's
27/// loopback where the engine forwards it here (Compose, a local VM). Only a host port is
28/// reserved, checked free or reported.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
30#[serde(transparent)]
31pub struct HostPort(u16);
32
33impl GuestPort {
34    /// The port `number` inside a machine (an engine's report, a test's value).
35    #[must_use]
36    pub const fn new(number: u16) -> GuestPort {
37        GuestPort(number)
38    }
39
40    /// Its number.
41    #[must_use]
42    pub const fn get(self) -> u16 {
43        self.0
44    }
45}
46
47impl HostPort {
48    /// The port `number` on the host (a socket bound, an engine's report, a recorded pick).
49    #[must_use]
50    pub const fn new(number: u16) -> HostPort {
51        HostPort(number)
52    }
53
54    /// Its number.
55    #[must_use]
56    pub const fn get(self) -> u16 {
57        self.0
58    }
59}
60
61/// The bare number's schema, inlined where the port appears (no definition of its own), so a
62/// schema that carries a port reads as it did with a `u16`.
63macro_rules! number_schema {
64    ($port:ident) => {
65        impl schemars::JsonSchema for $port {
66            fn inline_schema() -> bool {
67                true
68            }
69
70            fn schema_name() -> Cow<'static, str> {
71                Cow::Borrowed(stringify!($port))
72            }
73
74            fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
75                u16::json_schema(generator)
76            }
77        }
78    };
79}
80
81number_schema!(GuestPort);
82number_schema!(HostPort);
83
84impl fmt::Display for GuestPort {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        self.0.fmt(f)
87    }
88}
89
90impl fmt::Display for HostPort {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        self.0.fmt(f)
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn each_kind_reads_and_writes_as_the_bare_number() {
102        assert_eq!(serde_json::to_string(&HostPort::new(41873)).unwrap(), "41873");
103        assert_eq!(serde_json::to_string(&GuestPort::new(80)).unwrap(), "80");
104        assert_eq!(serde_json::from_str::<HostPort>("8080").unwrap(), HostPort::new(8080));
105    }
106
107    #[test]
108    fn each_kind_has_the_bare_numbers_schema() {
109        let number = serde_json::to_value(schemars::schema_for!(u16)).unwrap();
110        for schema in [schemars::schema_for!(HostPort), schemars::schema_for!(GuestPort)] {
111            let mut schema = serde_json::to_value(schema).unwrap();
112            let mut number = number.clone();
113            for s in [&mut schema, &mut number] {
114                let fields = s.as_object_mut().unwrap();
115                fields.remove("title");
116                fields.remove("description");
117            }
118            assert_eq!(schema, number);
119        }
120    }
121}