Skip to main content

feldera_types/
circuit.rs

1//! How the circuit of a pipeline is laid out across hosts. The controller of the pipeline and
2//! the engine that runs the circuit share this layout.
3
4use std::{
5    collections::HashSet,
6    error::Error as StdError,
7    fmt::{self, Debug, Display, Error as FmtError, Formatter},
8    iter::empty,
9    net::SocketAddr,
10    ops::Range,
11};
12
13use itertools::Either;
14
15/// A host for some workers in the [`Layout`] for a multi-host circuit.
16#[allow(clippy::manual_non_exhaustive)]
17#[derive(Clone, serde::Serialize, serde::Deserialize)]
18pub struct Host {
19    /// The IP address and TCP port on which the host listens and to which the
20    /// other hosts connect.
21    pub address: SocketAddr,
22
23    /// The worker thread IDs implemented on this host.  Worker thread IDs start
24    /// with 0 in the first host and increase sequentially from there.  A host
25    /// has `workers.len()` workers.
26    pub workers: Range<usize>,
27
28    /// Prevents `Host` and `Layout::Multihost` from being instantiated without
29    /// using the constructor (which checks the invariants).
30    _private: (),
31}
32
33impl Debug for Host {
34    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
35        f.debug_struct("Host")
36            .field("address", &self.address)
37            .field("workers", &self.workers)
38            .finish()
39    }
40}
41
42/// How a circuit is laid out across one or more machines.
43#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
44pub enum Layout {
45    /// A layout whose workers run on a single host.
46    Solo {
47        /// The number of worker threads.
48        n_workers: usize,
49    },
50
51    /// A layout across multiple machines.
52    Multihost {
53        /// Each host in the layout.  There should be two or more, each with a
54        /// unique network address.
55        hosts: Vec<Host>,
56
57        /// The index within `hosts` of the current host.
58        local_host_idx: usize,
59    },
60}
61
62impl Layout {
63    /// Returns a new solo layout with `n_workers` worker threads.
64    pub fn new_solo(n_workers: usize) -> Layout {
65        assert_ne!(n_workers, 0);
66        Layout::Solo { n_workers }
67    }
68
69    /// Returns a new multihost layout with as many hosts as specified in
70    /// `params`.  Each tuple in `params` specifies a host's unique network
71    /// address and the number of workers to run on that host.  `local_address`
72    /// must be one of the addresses in `params`.
73    ///
74    /// To execute such a multihost circuit, one must create a `Runtime` for it
75    /// on every host in `params`, passing the same `params` in each case.  Each
76    /// host must pass its own `local_address`.  The `Runtime` on each host
77    /// listens on its own address and connects to all the other addresses.
78    pub fn new_multihost(
79        params: &[(SocketAddr, usize)],
80        local_address: SocketAddr,
81    ) -> Result<Layout, LayoutError> {
82        // Check that the addresses are unique.
83        let mut uniq = HashSet::new();
84        if let Some((duplicate, _)) = params.iter().find(|(address, _)| !uniq.insert(address)) {
85            return Err(LayoutError::DuplicateAddress(*duplicate));
86        }
87
88        // Find `local_address` in `params`.
89        let local_host_idx = params
90            .iter()
91            .position(|(address, _)| *address == local_address)
92            .ok_or(LayoutError::NoSuchAddress(local_address))?;
93
94        if params.len() == 1 {
95            Ok(Self::new_solo(params[0].1))
96        } else {
97            let mut hosts = Vec::with_capacity(params.len());
98            let mut total_workers = 0;
99            for (address, n_workers) in params {
100                assert_ne!(*n_workers, 0);
101                hosts.push(Host {
102                    address: *address,
103                    workers: total_workers..total_workers + *n_workers,
104                    _private: (),
105                });
106                total_workers += *n_workers;
107            }
108            Ok(Layout::Multihost {
109                hosts,
110                local_host_idx,
111            })
112        }
113    }
114
115    /// Returns the range of IDs for the workers on the local machine.
116    pub fn local_workers(&self) -> Range<usize> {
117        match self {
118            Self::Solo { n_workers } => 0..*n_workers,
119            Self::Multihost {
120                hosts,
121                local_host_idx,
122                ..
123            } => hosts[*local_host_idx].workers.clone(),
124        }
125    }
126
127    /// Returns an iterator over `Host`s in this layout other than this one.  If
128    /// this is a single-host layout, this will be an empty iterator.
129    pub fn other_hosts(&self) -> impl Iterator<Item = &Host> {
130        match self {
131            Self::Solo { .. } => Either::Left(empty()),
132            Self::Multihost {
133                hosts,
134                local_host_idx,
135            } => Either::Right(
136                hosts
137                    .iter()
138                    .enumerate()
139                    .filter_map(|(i, host)| (i != *local_host_idx).then_some(host)),
140            ),
141        }
142    }
143
144    /// Returns an iterator across the ranges of workers on all the hosts in
145    /// this layout.  A single-host layout will have a single range with all the
146    /// workers, a two-host layout will have two ranges, and so on.
147    pub fn all_hosts(&self) -> impl Iterator<Item = Range<usize>> {
148        match self {
149            Self::Solo { n_workers } => Either::Left(std::iter::once(0..*n_workers)),
150            Self::Multihost { hosts, .. } => {
151                Either::Right(hosts.iter().map(|host| host.workers.clone()))
152            }
153        }
154    }
155
156    /// Returns the network address for the current machine, or `None` if this
157    /// is a solo layout.
158    pub fn local_address(&self) -> Option<SocketAddr> {
159        match self {
160            Self::Solo { .. } => None,
161            Self::Multihost {
162                hosts,
163                local_host_idx,
164                ..
165            } => Some(hosts[*local_host_idx].address),
166        }
167    }
168
169    /// Returns the total number of worker threads in this layout.
170    pub fn n_workers(&self) -> usize {
171        match self {
172            Self::Solo { n_workers } => *n_workers,
173            Self::Multihost { hosts, .. } => hosts.iter().map(|host| host.workers.len()).sum(),
174        }
175    }
176
177    pub fn is_multihost(&self) -> bool {
178        matches!(self, Self::Multihost { .. })
179    }
180
181    pub fn is_solo(&self) -> bool {
182        matches!(self, Self::Solo { .. })
183    }
184
185    pub fn n_hosts(&self) -> usize {
186        match self {
187            Layout::Solo { .. } => 1,
188            Layout::Multihost { hosts, .. } => hosts.len(),
189        }
190    }
191
192    pub fn local_host_idx(&self) -> usize {
193        match self {
194            Layout::Solo { .. } => 0,
195            Layout::Multihost { local_host_idx, .. } => *local_host_idx,
196        }
197    }
198
199    /// Returns the host index corresponding to the given `worker_idx`.
200    pub fn worker_idx_to_host_idx(&self, worker_idx: usize) -> Option<usize> {
201        self.all_hosts()
202            .position(|workers| workers.contains(&worker_idx))
203    }
204
205    /// Returns [`HostInfo`] for this host when running in multihost mode,
206    /// or `None` for solo pipelines.
207    ///
208    /// [`HostInfo`]: crate::checkpoint::HostInfo
209    pub fn host_info(&self) -> Option<crate::checkpoint::HostInfo> {
210        match self {
211            Layout::Solo { .. } => None,
212            Layout::Multihost {
213                hosts,
214                local_host_idx,
215            } => Some(crate::checkpoint::HostInfo {
216                host_idx: *local_host_idx,
217                n_hosts: hosts.len(),
218            }),
219        }
220    }
221}
222
223#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
224pub enum LayoutError {
225    /// The socket address passed to `new_multihost()` isn't in the list of
226    /// hosts.
227    NoSuchAddress(SocketAddr),
228    /// The list of socket addresses passed to `new_multihost()` contains a
229    /// duplicate.
230    DuplicateAddress(SocketAddr),
231}
232
233impl Display for LayoutError {
234    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
235        match self {
236            Self::NoSuchAddress(address) => write!(f, "address {address} not in list of hosts"),
237            Self::DuplicateAddress(address) => {
238                write!(f, "duplicate address {address} in list of hosts")
239            }
240        }
241    }
242}
243
244impl StdError for LayoutError {}