Diffinery

homeflare/celldpublic

celld/crates/celld/startup.rs
304 lines · 10.5 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3//! Process startup primitives shared by the standalone and eventual managed
4//! celld adapters.
5//!
6//! Listener policy is copied from celld's production startup path. Keeping it
7//! outside the executor matters: the socket is reserved before storage or V8
8//! work starts, and the executor receives an already-validated peer address.
9
10use anyhow::{anyhow, Context};
11use std::fmt;
12use std::net::{IpAddr, Ipv4Addr, SocketAddr};
13use tokio::net::{TcpListener, TcpSocket};
14use tracing::warn;
15
16const AUTO_LISTEN_START: u16 = 8080;
17const AUTO_LISTEN_END: u16 = 8099;
18
19/// `TcpListener::bind` inherits socket2's historical backlog of 128. That is
20/// smaller than a routine reconnect cohort at the target fleet density: 1,200
21/// chat clients returning together filled every node's accept queue and
22/// produced connection resets while the runtime itself remained healthy.
23/// Request the common Linux `somaxconn` default; the kernel still applies its
24/// configured ceiling.
25const LISTEN_BACKLOG: u32 = 4_096;
26
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub enum Listen {
29 AutoLoopback,
30 Explicit(String),
31}
32
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct RuntimeSettings {
35 pub listen: Listen,
36 pub advertise: Option<String>,
37 pub unsafe_public_advertise: bool,
38}
39
40/// How peers should reach this node.
41///
42/// A hostname is allowed because container and PaaS environments often hand
43/// out a stable name and an unstable or ambiguous IP. The name is deliberately
44/// not resolved here: reachability is defined from each peer's network.
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub enum Advertise {
47 Addr(SocketAddr),
48 Name { host: String, port: u16 },
49}
50
51impl Advertise {
52 pub fn scope(&self) -> &'static str {
53 match self {
54 Self::Addr(address) => advertise_scope(address.ip()),
55 Self::Name { .. } => "resolved by each peer",
56 }
57 }
58
59 pub fn is_public_ip(&self) -> bool {
60 matches!(self, Self::Addr(address) if advertise_scope(address.ip()) == "operator-routed network")
61 }
62}
63
64impl fmt::Display for Advertise {
65 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
66 match self {
67 Self::Addr(address) => write!(formatter, "{address}"),
68 Self::Name { host, port } => write!(formatter, "{host}:{port}"),
69 }
70 }
71}
72
73fn advertise_scope(address: IpAddr) -> &'static str {
74 match address {
75 IpAddr::V4(address) if address.is_loopback() => "same host only",
76 IpAddr::V4(address) if address.is_private() || is_shared_overlay(address) => {
77 "private network"
78 }
79 IpAddr::V4(address) if address.is_link_local() => "local link only",
80 IpAddr::V6(address) if address.is_loopback() => "same host only",
81 IpAddr::V6(address) if address.is_unique_local() => "private network",
82 IpAddr::V6(address) if address.is_unicast_link_local() => "local link only",
83 _ => "operator-routed network",
84 }
85}
86
87/// RFC 6598 shared address space is not globally routable. Overlay networks
88/// such as Tailscale allocate peer addresses from this exact `100.64.0.0/10`
89/// block, so treating it as public rejects the private overlay operators are
90/// otherwise instructed to use.
91fn is_shared_overlay(address: Ipv4Addr) -> bool {
92 let octets = address.octets();
93 octets[0] == 100 && (64..=127).contains(&octets[1])
94}
95
96#[derive(Debug)]
97pub struct BoundListener {
98 pub listener: TcpListener,
99 pub listen: SocketAddr,
100 pub advertise: Advertise,
101}
102
103/// Descriptors one resident cell holds: its SQLite database, WAL, and shared-
104/// memory file, plus what replication keeps open for them. Measured at ~7 on
105/// Linux; budgeted at 8.
106const FDS_PER_CELL: u64 = 8;
107
108/// Below this the node cannot reach the density the runtime is designed for,
109/// so say so at startup rather than at the failing activation.
110const MIN_RESIDENT_CELLS: u64 = 1_000;
111
112/// Raise the descriptor limit to its hard ceiling, and warn when even that
113/// bounds residency.
114#[cfg(unix)]
115pub fn raise_file_limit() {
116 let mut limit = libc::rlimit {
117 rlim_cur: 0,
118 rlim_max: 0,
119 };
120 if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } != 0 {
121 return;
122 }
123 if limit.rlim_cur < limit.rlim_max {
124 let raised = libc::rlimit {
125 rlim_cur: limit.rlim_max,
126 ..limit
127 };
128 unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &raised) };
129 // Re-read rather than assume the raise took: macOS reports an
130 // unlimited hard limit, refuses it as a soft limit, and caps the
131 // process at kern.maxfilesperproc.
132 if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } != 0 {
133 return;
134 }
135 }
136 let cells = limit.rlim_cur / FDS_PER_CELL;
137 if cells < MIN_RESIDENT_CELLS {
138 warn!(
139 event = "file_limit_bounds_residency",
140 open_files = limit.rlim_cur,
141 resident_cells = cells,
142 "the open-file limit caps this node near {cells} resident cells; \
143 raise it (ulimit -n {}, or LimitNOFILE= in the unit file)",
144 MIN_RESIDENT_CELLS * FDS_PER_CELL
145 );
146 }
147}
148
149#[cfg(not(unix))]
150pub fn raise_file_limit() {}
151
152fn bind_tcp_listener(address: SocketAddr) -> std::io::Result<TcpListener> {
153 let socket = match address {
154 SocketAddr::V4(_) => TcpSocket::new_v4()?,
155 SocketAddr::V6(_) => TcpSocket::new_v6()?,
156 };
157 #[cfg(unix)]
158 socket.set_reuseaddr(true)?;
159 socket.bind(address)?;
160 socket.listen(LISTEN_BACKLOG)
161}
162
163pub async fn bind_listener(settings: &RuntimeSettings) -> anyhow::Result<BoundListener> {
164 let (listener, listen) = match &settings.listen {
165 Listen::Explicit(address) => {
166 let address = parse_socket_address(address, "--listen")?;
167 let listener =
168 bind_tcp_listener(address).with_context(|| format!("bind --listen {address}"))?;
169 let listen = listener.local_addr().context("read bound listen address")?;
170 (listener, listen)
171 }
172 Listen::AutoLoopback => {
173 let mut last_error = None;
174 let mut bound = None;
175 for port in AUTO_LISTEN_START..=AUTO_LISTEN_END {
176 let address = SocketAddr::from(([127, 0, 0, 1], port));
177 match bind_tcp_listener(address) {
178 Ok(listener) => {
179 bound = Some((listener, address));
180 break;
181 }
182 Err(error) if error.kind() == std::io::ErrorKind::AddrInUse => {
183 last_error = Some(error);
184 }
185 Err(error) => return Err(error).with_context(|| format!("bind {address}")),
186 }
187 }
188 bound.ok_or_else(|| {
189 anyhow!(
190 "no free managed demo port in 127.0.0.1:{AUTO_LISTEN_START}-{AUTO_LISTEN_END}: {}",
191 last_error
192 .map(|error| error.to_string())
193 .unwrap_or_else(|| "range exhausted".to_string())
194 )
195 })?
196 }
197 };
198
199 let advertise = if let Some(address) = settings.advertise.as_deref() {
200 parse_advertise(address)?
201 } else if listen.ip().is_unspecified() {
202 return Err(anyhow!(
203 "--advertise is required when --listen uses an unspecified address ({listen}).\n\
204 Give the address peers should dial, for example --advertise \
205 {}:{} or --advertise node1.example.com:{}",
206 "10.0.0.1",
207 listen.port(),
208 listen.port()
209 ));
210 } else {
211 Advertise::Addr(listen)
212 };
213 if advertise.is_public_ip() && !settings.unsafe_public_advertise {
214 return Err(anyhow!(
215 "--advertise {advertise} is a public IP address; peer HTTP carries \
216 application data without built-in TLS. Use a private overlay, or \
217 pass --unsafe-public-advertise to accept this exposure explicitly"
218 ));
219 }
220
221 Ok(BoundListener {
222 listener,
223 listen,
224 advertise,
225 })
226}
227
228fn parse_socket_address(value: &str, option: &str) -> anyhow::Result<SocketAddr> {
229 value
230 .parse()
231 .with_context(|| format!("{option} must be an IP socket address such as 127.0.0.1:8080"))
232}
233
234/// Parse `--advertise`, accepting `IP:PORT` or `HOST:PORT`.
235pub fn parse_advertise(value: &str) -> anyhow::Result<Advertise> {
236 let value = value.trim();
237 if let Ok(address) = value.parse::<SocketAddr>() {
238 if address.port() == 0 {
239 return Err(anyhow!("--advertise must use a nonzero port"));
240 }
241 if address.ip().is_unspecified() || address.ip().is_multicast() {
242 return Err(anyhow!(
243 "--advertise must be a concrete unicast address, not {address}"
244 ));
245 }
246 if matches!(address.ip(), IpAddr::V4(ip) if ip.is_broadcast()) {
247 return Err(anyhow!("--advertise cannot use the IPv4 broadcast address"));
248 }
249 return Ok(Advertise::Addr(address));
250 }
251
252 let (host, port) = value.rsplit_once(':').ok_or_else(|| {
253 anyhow!("--advertise must be HOST:PORT or IP:PORT, such as node1.example.com:8080")
254 })?;
255 let port: u16 = port.parse().with_context(|| {
256 format!("--advertise port {port:?} is not a number between 1 and 65535")
257 })?;
258 if port == 0 {
259 return Err(anyhow!("--advertise must use a nonzero port"));
260 }
261 if !is_dns_name(host) {
262 return Err(anyhow!(
263 "--advertise host {host:?} is not a valid hostname or IP address"
264 ));
265 }
266 Ok(Advertise::Name {
267 host: host.to_string(),
268 port,
269 })
270}
271
272fn is_dns_name(host: &str) -> bool {
273 !host.is_empty()
274 && host.len() <= 253
275 && host.split('.').all(|label| {
276 !label.is_empty()
277 && label.len() <= 63
278 && !label.starts_with('-')
279 && !label.ends_with('-')
280 && label
281 .chars()
282 .all(|character| character.is_ascii_alphanumeric() || character == '-')
283 })
284}
285
286pub fn validate_peer_id(value: &str) -> anyhow::Result<()> {
287 if value.is_empty()
288 || value.len() > 200
289 || value.contains('/')
290 || value.contains('?')
291 || value.contains('#')
292 || value.chars().any(char::is_whitespace)
293 {
294 return Err(anyhow!(
295 "--peer must be one node-session ID without a path or whitespace"
296 ));
297 }
298 Ok(())
299}
300
301#[cfg(all(test, celld_internal_tests))]
302mod conformance_startup_tests {
303 include!(env!("CELLD_CONFORMANCE_STARTUP_TESTS"));
304}