Skip to main content

bynk/dev/
serving.rs

1use super::run::DevOptions;
2use std::collections::BTreeMap;
3use std::path::Path;
4
5/// Wrangler's own default dev port — the base of the per-context allocation
6/// when `--base-port` is not given, so a multi-context project's first worker
7/// lands where a single-context one always has.
8pub(super) const DEFAULT_BASE_PORT: u16 = 8787;
9
10/// wrangler's own default inspector port, the base of the per-context inspector
11/// allocation when `--inspect-port` is not given.
12const DEFAULT_INSPECT_PORT: u16 = 9229;
13
14/// One worker to serve: its dasherised context dir, its HTTP port (`None` = let
15/// wrangler choose, the lone-worker default), its inspector port, and whether
16/// the inspector was asked for (`--inspect`) rather than only allocated so the
17/// contexts' default inspectors do not collide (#1954).
18#[derive(Debug, PartialEq, Eq)]
19pub struct Serving {
20    pub worker: String,
21    pub port: Option<u16>,
22    pub inspector_port: Option<u16>,
23    pub inspect: bool,
24}
25
26/// Allocate a port per worker (#552): `wrangler dev` binds one port per process,
27/// so serving N contexts means N distinct ports, assigned `base + i` over the
28/// deterministic worker order.
29///
30/// The one exception preserves the pre-#552 contract: a **lone** worker with no
31/// explicit `--base-port` gets `None` — no injected `--port` at all — so it
32/// lands on wrangler's own default and `-- --port N` still works. Injecting
33/// unconditionally would break that, because a repeated `--port` is a hard
34/// wrangler error, not last-wins.
35///
36/// Inspector ports follow the same shape, from `--inspect-port`. They are
37/// allocated under `--inspect`, whenever `--inspect-port` is given (#3237: an
38/// explicit port is always honoured, for one worker too), and whenever more than
39/// one worker is served (#1954): `wrangler dev` always starts its inspector, on
40/// 9229 unless told otherwise, so N wranglers started together all bind 9229 and
41/// every one but the first dies with `Address already in use`. A lone worker
42/// with none of those gets none here; [`assign_free_inspector`] gives it a free
43/// port of its own.
44pub fn allocate(workers: &[String], base_port: Option<u16>, opts: &DevOptions) -> Vec<Serving> {
45    let lone = workers.len() == 1 && base_port.is_none();
46    let base = base_port.unwrap_or(DEFAULT_BASE_PORT);
47    let inspectors = opts.inspect || workers.len() > 1 || opts.inspect_port.is_some();
48    let inspect_base = opts.inspect_port.unwrap_or(DEFAULT_INSPECT_PORT);
49    workers
50        .iter()
51        .enumerate()
52        .map(|(i, worker)| Serving {
53            worker: worker.clone(),
54            port: (!lone).then(|| base.saturating_add(i as u16)),
55            inspector_port: inspectors.then(|| inspect_base.saturating_add(i as u16)),
56            inspect: opts.inspect,
57        })
58        .collect()
59}
60
61/// A port the allocation hands out twice: one context's HTTP port that is also
62/// some context's inspector port.
63pub(super) fn port_clash(serving: &[Serving]) -> Option<u16> {
64    serving
65        .iter()
66        .filter_map(|s| s.port)
67        .find(|p| serving.iter().any(|s| s.inspector_port == Some(*p)))
68}
69
70/// #3237: a lone worker with no `--inspect` and no `--inspect-port` has no
71/// inspector port of its own, so `wrangler dev` takes 9229 — and two sessions
72/// started together both see it free and both bind it, one dying with `Address
73/// already in use`. Give it the free port the OS hands out instead. `free` is
74/// `None` when no port could be found, or when the `--` passthrough already
75/// carries `--inspector-port` (wrangler rejects it twice, and the caller chose
76/// it); the worker then keeps wrangler's own default, as before.
77pub fn assign_free_inspector(serving: &mut [Serving], free: Option<u16>) {
78    if let [only] = serving
79        && only.inspector_port.is_none()
80    {
81        only.inspector_port = free;
82    }
83}
84
85/// A free localhost port, as the OS reports it right now. The listener is
86/// dropped before wrangler binds the port, so another process could still take
87/// it in between; that window is milliseconds, against the seconds in which two
88/// sessions starting together both saw 9229 free.
89pub(super) fn free_local_port() -> Option<u16> {
90    std::net::TcpListener::bind("127.0.0.1:0")
91        .and_then(|l| l.local_addr())
92        .map(|a| a.port())
93        .ok()
94}
95
96/// The first inspector port in the allocation that something is already
97/// listening on, so `bynk dev` can say so instead of leaving it to wrangler's
98/// `Address already in use`.
99pub(super) fn inspector_port_in_use(serving: &[Serving]) -> Option<u16> {
100    first_inspector_port_where(serving, port_is_in_use)
101}
102
103/// The first inspector port in the allocation for which `in_use` holds. The
104/// probe is a parameter so a test can say "this port is free" without relying
105/// on the OS leaving a port it just released alone (#3526).
106fn first_inspector_port_where(serving: &[Serving], in_use: impl Fn(u16) -> bool) -> Option<u16> {
107    serving
108        .iter()
109        .filter_map(|s| s.inspector_port)
110        .find(|p| in_use(*p))
111}
112
113/// Whether binding `port` on localhost fails because something holds it.
114fn port_is_in_use(port: u16) -> bool {
115    matches!(
116        std::net::TcpListener::bind(("127.0.0.1", port)),
117        Err(e) if e.kind() == std::io::ErrorKind::AddrInUse
118    )
119}
120
121/// The `wrangler dev` flags the driver injects for one worker: the ports it
122/// allocated (#552) — `--port` when serving several contexts, `--inspector-port`
123/// under `--inspect` (slice 3, ADR 0104), so a JavaScript debugger can attach and
124/// `.bynk` breakpoints resolve through the emitted source maps.
125///
126/// A lone worker without `--base-port` or `--inspect` gets no port flag — the
127/// pre-#552 invocation, so that path keeps its `-- --port N` passthrough.
128///
129/// I2 (#1971): and the local key for each edge the Worker is on (`edge_keys`,
130/// its [`crate::deploy::local_edge_keys`]), as `--var`s rather than a file:
131/// every internal request (`/_bynk/call/`, `/_bynk/event/`) is signed under
132/// its edge's key, and a lone context still delivers its own events to
133/// itself. The fixed [`bynk_emit::LOCAL_CALL_KEY`], so two `bynk dev
134/// --context` sessions run side by side admit each other's calls.
135/// The keys `bynk dev` gives each Worker through `--var`: the local edge keys (I2, #1971), and
136/// (#3386) a local signing key for each `SignedCookie` binding: derived from the binding's name,
137/// so each actor has its own and two `bynk dev --context` sessions side by side admit each other's
138/// cookies. It is for local development only; `deploy` mints its own.
139pub(super) struct LocalKeys {
140    pub(super) edge: BTreeMap<String, Vec<String>>,
141    session: BTreeMap<String, Vec<String>>,
142}
143
144impl LocalKeys {
145    pub(super) fn read(
146        workers_dir: &Path,
147        available: &[String],
148        model: &bynk_emit::emit_model::WorkersBuild,
149    ) -> Result<Self, String> {
150        Ok(Self {
151            edge: crate::deploy::local_edge_keys(workers_dir, available, model)?,
152            session: crate::deploy::local_session_keys(workers_dir, available, model)?,
153        })
154    }
155
156    /// `--var NAME:<key>` for each session key a Worker holds, except one the operator already
157    /// passes after `--` (that is theirs).
158    pub(super) fn session_args(&self, worker: &str, passthrough: &[String]) -> Vec<String> {
159        let mut args = Vec::new();
160        for name in self.session.get(worker).into_iter().flatten() {
161            if passthrough.iter().any(|a| {
162                let a = a.strip_prefix("--var=").unwrap_or(a);
163                a.starts_with(&format!("{name}:"))
164            }) {
165                continue;
166            }
167            args.push("--var".to_string());
168            args.push(format!("{name}:{}", crate::deploy::local_session_key(name)));
169        }
170        args
171    }
172}
173
174pub(super) fn serve_args(s: &Serving, edge_keys: &[String]) -> Vec<String> {
175    let mut args = Vec::new();
176    for key in edge_keys {
177        args.push("--var".to_string());
178        args.push(format!("{key}:{}", bynk_emit::LOCAL_CALL_KEY));
179    }
180    if let Some(port) = s.port {
181        args.push("--port".to_string());
182        args.push(port.to_string());
183    }
184    if let Some(port) = s.inspector_port {
185        args.push("--inspector-port".to_string());
186        args.push(port.to_string());
187    }
188    args
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194    use crate::dev::run::DevOptions;
195    use crate::dev::test_support::names;
196
197    use std::collections::BTreeMap;
198
199    /// I2 (#1971): a Worker's edge keys come first, each the local key.
200    #[test]
201    fn every_edge_key_is_passed_as_the_local_key() {
202        let serving = allocate(&names(&["api"]), None, &DevOptions::default());
203        assert_eq!(
204            serve_args(
205                &serving[0],
206                &names(&["BYNK_CALL_FROM_WORKER", "BYNK_CALL_TO_WORKER"])
207            ),
208            names(&[
209                "--var",
210                "BYNK_CALL_FROM_WORKER:bynk-local-call-key",
211                "--var",
212                "BYNK_CALL_TO_WORKER:bynk-local-call-key",
213            ])
214        );
215    }
216
217    #[test]
218    fn inspect_injects_the_inspector_port() {
219        let off = DevOptions::default();
220        let lone = allocate(&names(&["links"]), None, &off);
221        assert_eq!(
222            serve_args(&lone[0], &[]),
223            Vec::<String>::new(),
224            "a lone worker without --inspect keeps the pre-#552 invocation"
225        );
226
227        let on = DevOptions {
228            inspect: true,
229            inspect_port: Some(9229),
230            ..Default::default()
231        };
232        let lone = allocate(&names(&["links"]), None, &on);
233        assert_eq!(
234            serve_args(&lone[0], &[]),
235            names(&["--inspector-port", "9229"])
236        );
237    }
238
239    // ---- #3237: inspector ports for a lone worker -------------------------
240
241    #[test]
242    fn an_explicit_inspect_port_is_honoured_for_a_lone_worker() {
243        let given = DevOptions {
244            inspect_port: Some(9300),
245            ..Default::default()
246        };
247        let lone = allocate(&names(&["links"]), None, &given);
248        assert_eq!(lone[0].inspector_port, Some(9300));
249        assert!(!lone[0].inspect, "an explicit port is not a debug session");
250        assert_eq!(
251            serve_args(&lone[0], &[]),
252            names(&["--inspector-port", "9300"])
253        );
254        // Several contexts still count up from it.
255        let two = allocate(&names(&["a", "b"]), None, &given);
256        assert_eq!(
257            two.iter().map(|s| s.inspector_port).collect::<Vec<_>>(),
258            vec![Some(9300), Some(9301)]
259        );
260    }
261
262    #[test]
263    fn a_session_key_is_a_per_run_var_unless_the_operator_passes_their_own() {
264        let local = LocalKeys {
265            edge: BTreeMap::new(),
266            session: BTreeMap::from([("shop".to_string(), vec!["SESSION_KEY".to_string()])]),
267        };
268        let key = crate::deploy::local_session_key("SESSION_KEY");
269        assert_eq!(
270            local.session_args("shop", &[]),
271            ["--var".to_string(), format!("SESSION_KEY:{key}")]
272        );
273        // Each binding has its own key, and it is the same in every session.
274        assert_ne!(key, crate::deploy::local_session_key("ADMIN_KEY"));
275        assert_eq!(key, crate::deploy::local_session_key("SESSION_KEY"));
276        assert!(local.session_args("other", &[]).is_empty());
277        let own = ["--var".to_string(), "SESSION_KEY:mine".to_string()];
278        assert!(local.session_args("shop", &own).is_empty());
279        let eq_form = ["--var=SESSION_KEY:mine".to_string()];
280        assert!(local.session_args("shop", &eq_form).is_empty());
281    }
282
283    #[test]
284    fn a_lone_worker_with_no_inspector_flags_is_given_a_free_port() {
285        let mut lone = allocate(&names(&["links"]), None, &DevOptions::default());
286        assert_eq!(lone[0].inspector_port, None);
287        assign_free_inspector(&mut lone, Some(40123));
288        assert_eq!(lone[0].inspector_port, Some(40123));
289        assert_eq!(
290            serve_args(&lone[0], &[]),
291            names(&["--inspector-port", "40123"])
292        );
293        // No free port found (or `--inspector-port` passed through): unchanged.
294        let mut none = allocate(&names(&["links"]), None, &DevOptions::default());
295        assign_free_inspector(&mut none, None);
296        assert_eq!(none[0].inspector_port, None);
297    }
298
299    #[test]
300    fn a_free_inspector_never_overrides_an_allocated_one() {
301        let given = DevOptions {
302            inspect_port: Some(9300),
303            ..Default::default()
304        };
305        let mut lone = allocate(&names(&["links"]), None, &given);
306        assign_free_inspector(&mut lone, Some(40123));
307        assert_eq!(lone[0].inspector_port, Some(9300));
308        let mut two = allocate(&names(&["a", "b"]), None, &DevOptions::default());
309        assign_free_inspector(&mut two, Some(40123));
310        assert_eq!(two[0].inspector_port, Some(9229));
311    }
312
313    #[test]
314    fn a_taken_inspector_port_is_found() {
315        // The listener is held for the whole test, so the port stays taken.
316        let held = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
317        let taken = held.local_addr().unwrap().port();
318        let given = DevOptions {
319            inspect_port: Some(taken),
320            ..Default::default()
321        };
322        let lone = allocate(&names(&["links"]), None, &given);
323        assert_eq!(inspector_port_in_use(&lone), Some(taken));
324        // A worker with no inspector port has nothing to find.
325        let plain = allocate(&names(&["links"]), None, &DevOptions::default());
326        assert_eq!(inspector_port_in_use(&plain), None);
327        assert!(free_local_port().is_some());
328    }
329
330    #[test]
331    fn a_free_inspector_port_is_not_reported() {
332        // #3526: this used to drop the listener and assert the port was then
333        // free, which fails whenever a parallel test's `bind(":0")` is handed
334        // the port just released. The probe says "free" without the OS.
335        let given = DevOptions {
336            inspect_port: Some(9300),
337            ..Default::default()
338        };
339        let lone = allocate(&names(&["links"]), None, &given);
340        assert_eq!(first_inspector_port_where(&lone, |_| false), None);
341        assert_eq!(first_inspector_port_where(&lone, |p| p == 9300), Some(9300));
342    }
343
344    // ---- #552: port allocation --------------------------------------------
345
346    #[test]
347    fn ports_are_allocated_per_context_from_the_base() {
348        let opts = DevOptions {
349            inspect: true,
350            inspect_port: Some(9229),
351            ..Default::default()
352        };
353        let serving = allocate(&names(&["api", "worker"]), None, &opts);
354        assert_eq!(
355            serving.iter().map(|s| s.port).collect::<Vec<_>>(),
356            vec![Some(8787), Some(8788)],
357            "each wrangler dev binds its own port"
358        );
359        assert_eq!(
360            serving.iter().map(|s| s.inspector_port).collect::<Vec<_>>(),
361            vec![Some(9229), Some(9230)],
362            "inspector ports must not collide either"
363        );
364        assert_eq!(
365            serve_args(&serving[1], &[]),
366            names(&["--port", "8788", "--inspector-port", "9230"])
367        );
368    }
369
370    #[test]
371    fn base_port_moves_the_whole_allocation() {
372        let serving = allocate(&names(&["a", "b"]), Some(9000), &DevOptions::default());
373        assert_eq!(
374            serving.iter().map(|s| s.port).collect::<Vec<_>>(),
375            vec![Some(9000), Some(9001)]
376        );
377    }
378
379    #[test]
380    fn a_lone_worker_keeps_wranglers_own_port() {
381        // The back-compat contract: no injected --port, so `-- --port N` still
382        // reaches wrangler (a repeated --port is a hard error, not last-wins).
383        let serving = allocate(&names(&["links"]), None, &DevOptions::default());
384        assert_eq!(serving[0].port, None);
385        assert_eq!(serve_args(&serving[0], &[]), Vec::<String>::new());
386        // …but an explicit --base-port is honoured even for one context.
387        let pinned = allocate(&names(&["links"]), Some(8900), &DevOptions::default());
388        assert_eq!(pinned[0].port, Some(8900));
389    }
390
391    #[test]
392    fn several_contexts_get_distinct_inspector_ports_without_inspect() {
393        // #1954: wrangler's inspector is always on, so two wranglers left on
394        // its default both bind 9229 and the second dies at boot.
395        let plain = DevOptions {
396            inspect_port: Some(9229), // the CLI default
397            ..Default::default()
398        };
399        let serving = allocate(&names(&["api", "worker"]), None, &plain);
400        assert_eq!(
401            serving.iter().map(|s| s.inspector_port).collect::<Vec<_>>(),
402            vec![Some(9229), Some(9230)]
403        );
404        assert_eq!(
405            serve_args(&serving[1], &[]),
406            names(&["--port", "8788", "--inspector-port", "9230"])
407        );
408        // `--inspect-port` moves that allocation even without `--inspect`…
409        let moved = DevOptions {
410            inspect_port: Some(9300),
411            ..Default::default()
412        };
413        let serving = allocate(&names(&["api", "worker"]), None, &moved);
414        assert_eq!(
415            serving.iter().map(|s| s.inspector_port).collect::<Vec<_>>(),
416            vec![Some(9300), Some(9301)]
417        );
418        // …and a lone worker without `--inspect` still gets none.
419        let lone = allocate(&names(&["links"]), Some(8900), &DevOptions::default());
420        assert_eq!(lone[0].inspector_port, None);
421    }
422
423    #[test]
424    fn overlapping_http_and_inspector_ranges_are_caught() {
425        let opts = DevOptions {
426            inspect_port: Some(9229),
427            ..Default::default()
428        };
429        let two = names(&["api", "worker"]);
430        // HTTP 9228/9229 against inspectors 9229/9230.
431        assert_eq!(port_clash(&allocate(&two, Some(9228), &opts)), Some(9229));
432        assert_eq!(port_clash(&allocate(&two, None, &opts)), None);
433        // A lone worker has neither, so nothing can clash.
434        assert_eq!(port_clash(&allocate(&names(&["links"]), None, &opts)), None);
435    }
436}