1use 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#[allow(clippy::manual_non_exhaustive)]
17#[derive(Clone, serde::Serialize, serde::Deserialize)]
18pub struct Host {
19 pub address: SocketAddr,
22
23 pub workers: Range<usize>,
27
28 _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#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
44pub enum Layout {
45 Solo {
47 n_workers: usize,
49 },
50
51 Multihost {
53 hosts: Vec<Host>,
56
57 local_host_idx: usize,
59 },
60}
61
62impl Layout {
63 pub fn new_solo(n_workers: usize) -> Layout {
65 assert_ne!(n_workers, 0);
66 Layout::Solo { n_workers }
67 }
68
69 pub fn new_multihost(
79 params: &[(SocketAddr, usize)],
80 local_address: SocketAddr,
81 ) -> Result<Layout, LayoutError> {
82 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 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 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 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 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 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 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 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 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 NoSuchAddress(SocketAddr),
228 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 {}