Skip to main content

bynk/dev/
events.rs

1use super::serving::DEFAULT_BASE_PORT;
2use super::serving::Serving;
3use std::path::Path;
4
5/// `bynk dev --format` (#2094).
6#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
7pub enum DevFormat {
8    /// The readable stream on stderr, unchanged.
9    #[default]
10    Human,
11    /// The readable stream on stderr, plus one JSON [`DevEvent`] per line on
12    /// stdout. `wrangler dev`'s own stdout moves to stderr, so stdout carries
13    /// nothing but events.
14    Json,
15}
16
17/// One lifecycle event of a `bynk dev --format json` session (#2094): a stable,
18/// line-delimited interface for the editor and CI scripts, so neither has to
19/// parse the human report, whose wording is UX and changes. Serialised with an
20/// `event` tag in snake_case. A consumer should ignore fields and events it
21/// does not know: new ones may be added, existing ones keep their meaning.
22#[derive(Debug, Clone, PartialEq, serde::Serialize)]
23#[serde(tag = "event", rename_all = "snake_case")]
24pub enum DevEvent {
25    /// Every `wrangler dev` has been started. Ports are allocated, but a
26    /// worker may still be booting; poll its URL for readiness.
27    Serving { contexts: Vec<ServedContext> },
28    /// A source change was seen and a rebuild has begun.
29    Rebuilding,
30    /// The rebuild succeeded; the workers hot-reload from it.
31    RebuildOk,
32    /// The rebuild failed. Its diagnostics are on stderr, and the last good
33    /// build keeps serving.
34    RebuildFailed,
35    /// The session ended, with the exit code `bynk dev` is about to return.
36    Stopped { code: u8 },
37    /// One request a worker served (`--trace-events`, #3580): its route, status
38    /// and duration, and the steps it took in call order. Steps carry no argument
39    /// values. A cross-context call is its own step here; the callee's own
40    /// request is a separate event.
41    Request {
42        /// The worker dir that served it, as in [`ServedContext::name`].
43        context: String,
44        /// This request's id.
45        id: String,
46        /// The id of the request that made this one, when it is a cross-context
47        /// call from another worker (that request's `call` step carries this one's
48        /// id as its `request`); `null` for a request from outside.
49        parent: Option<String>,
50        /// `<METHOD> <path>`.
51        route: String,
52        status: u16,
53        duration_ms: f64,
54        steps: Vec<crate::trace::TraceStep>,
55        /// More steps happened than are listed (the list is bounded).
56        truncated: bool,
57        /// The fault that answered the request with a 500, with its stack frames
58        /// mapped to `.bynk` locations; `null` when it did not fault.
59        fault: Option<crate::trace::TraceFault>,
60    },
61    /// One line a worker printed (`--log-events`, #2474), with any stack frame
62    /// into generated code rewritten to the `.bynk` line it came from. A
63    /// thrown error is a headline line followed by one event per frame, all
64    /// at the same level.
65    Log {
66        /// The worker dir that printed it, as in [`ServedContext::name`].
67        context: String,
68        level: crate::logs::LogLevel,
69        text: String,
70    },
71}
72
73/// One served context in a [`DevEvent::Serving`] event.
74#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
75pub struct ServedContext {
76    /// The context's worker dir (dasherised), as `--context` accepts it.
77    pub name: String,
78    /// The HTTP port it answers on.
79    pub port: u16,
80    /// `http://localhost:<port>`.
81    pub url: String,
82    /// Its V8 inspector port, when one was allocated (`--inspect`, or several
83    /// contexts served); `null` otherwise.
84    pub inspector_port: Option<u16>,
85}
86
87/// The [`DevEvent::Serving`] event for an allocation. A lone worker left on
88/// wrangler's default (`port: None`) reports the port it actually gets: a
89/// `-- --port N` passthrough, else wrangler's 8787.
90pub fn serving_event(serving: &[Serving], wrangler_args: &[String]) -> DevEvent {
91    DevEvent::Serving {
92        contexts: serving
93            .iter()
94            .map(|s| {
95                let port = s
96                    .port
97                    .or_else(|| passthrough_port(wrangler_args))
98                    .unwrap_or(DEFAULT_BASE_PORT);
99                ServedContext {
100                    name: s.worker.clone(),
101                    port,
102                    url: format!("http://localhost:{port}"),
103                    inspector_port: s.inspector_port,
104                }
105            })
106            .collect(),
107    }
108}
109
110/// One event as its JSON line (no trailing newline).
111pub fn event_line(event: &DevEvent) -> String {
112    serde_json::to_string(event).expect("a dev event serialises")
113}
114
115/// Write `event` to stdout under `--format json`; nothing under `human`.
116pub(super) fn emit(format: DevFormat, event: &DevEvent) {
117    if format == DevFormat::Json {
118        use std::io::Write;
119        let mut out = std::io::stdout().lock();
120        let _ = writeln!(out, "{}", event_line(event));
121        let _ = out.flush();
122    }
123}
124
125/// The `--port` value of a `-- --port N` / `-- --port=N` passthrough.
126fn passthrough_port(args: &[String]) -> Option<u16> {
127    args.iter().enumerate().find_map(|(i, a)| {
128        if a == "--port" {
129            args.get(i + 1).and_then(|v| v.parse().ok())
130        } else {
131            a.strip_prefix("--port=").and_then(|v| v.parse().ok())
132        }
133    })
134}
135
136/// The session file's record (#3581) of the contexts a `serving` event names.
137pub(super) fn session_of(serving: &DevEvent, workers_dir: &Path) -> crate::dev_inspect::Session {
138    let DevEvent::Serving { contexts } = serving else {
139        unreachable!("serving_event builds a Serving event")
140    };
141    crate::dev_inspect::Session {
142        workers: contexts
143            .iter()
144            .map(|c| {
145                (
146                    c.name.clone(),
147                    crate::dev_inspect::SessionWorker {
148                        context: crate::dev_inspect::context_of_worker(&c.name),
149                        url: c.url.clone(),
150                        members: crate::dev_inspect::inspect_members(&workers_dir.join(&c.name)),
151                    },
152                )
153            })
154            .collect(),
155    }
156}
157
158/// The start-up report: which context answers on which URL, plus the inspector
159/// notice under `--inspect`. Pure and deterministic, so it is golden-pinned in
160/// the style of ADR 0096 §Exit — unlike the `wrangler dev` streams it precedes.
161///
162/// A lone worker on wrangler's own default port prints no table: there is no
163/// allocation to disclose and wrangler announces its own `Ready on` line, so
164/// that session reads exactly as it did before #552.
165pub fn serving_report(serving: &[Serving]) -> String {
166    let mut out = String::new();
167    if serving.iter().any(|s| s.port.is_some()) {
168        // Only claim the wiring when there is something to wire: a subset of
169        // one has no sibling to bind to, and saying otherwise would explain a
170        // cross-context call's failure as a bug rather than as the missing
171        // context it is.
172        out.push_str(&match serving.len() {
173            1 => "bynk dev: serving 1 context.\n".to_string(),
174            n => format!(
175                "bynk dev: serving {n} contexts — service bindings between them are wired.\n"
176            ),
177        });
178        let width = serving.iter().map(|s| s.worker.len()).max().unwrap_or(0);
179        for s in serving {
180            let Some(port) = s.port else { continue };
181            out.push_str(&format!(
182                "  {:width$}  http://localhost:{port}\n",
183                s.worker,
184                width = width
185            ));
186        }
187    }
188    // Only `--inspect` announces the inspector. Without it a multi-context
189    // session still allocates inspector ports (#1954), but only so they do not
190    // collide; that is wrangler's default inspector, moved, not a debug session.
191    let inspected = serving
192        .iter()
193        .filter(|s| s.inspect && s.inspector_port.is_some())
194        .count();
195    if inspected > 0 {
196        out.push_str(&match inspected {
197            1 => "bynk dev --inspect: the worker runs with the V8 inspector enabled.\n".to_string(),
198            _ => "bynk dev --inspect: each worker runs with the V8 inspector enabled, on its own port.\n"
199                .to_string(),
200        });
201        for s in serving {
202            let (true, Some(port)) = (s.inspect, s.inspector_port) else {
203                continue;
204            };
205            out.push_str(&format!(
206                "  {} — inspector on port {port} (CDP discovery: http://127.0.0.1:{port}/json)\n",
207                s.worker
208            ));
209        }
210        out.push_str(
211            "  Breakpoints set in `.bynk` sources resolve through the emitted source maps.\n\
212             \x20 A hand-rolled CDP client must send an `Origin` header — VS Code's\n\
213             \x20 JavaScript debugger does this for you.\n",
214        );
215    }
216    out
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use crate::dev::run::DevOptions;
223    use crate::dev::run::passthrough_has;
224
225    use crate::dev::serving::allocate;
226    use crate::dev::test_support::names;
227
228    #[test]
229    fn an_allocated_inspector_is_announced_only_under_inspect() {
230        let report = serving_report(&allocate(
231            &names(&["api", "worker"]),
232            None,
233            &DevOptions::default(),
234        ));
235        assert!(!report.contains("inspector"), "{report}");
236    }
237
238    #[test]
239    fn passthrough_port_is_detected_in_both_spellings() {
240        assert!(passthrough_has(&names(&["--port", "8788"]), "--port"));
241        assert!(passthrough_has(&names(&["--port=8788"]), "--port"));
242        assert!(!passthrough_has(&names(&["--remote"]), "--port"));
243        // `--inspector-port` must not be mistaken for `--port`.
244        assert!(!passthrough_has(
245            &names(&["--inspector-port", "9229"]),
246            "--port"
247        ));
248    }
249
250    #[test]
251    fn the_serving_report_lists_context_urls() {
252        let serving = allocate(
253            &names(&["commerce-orders", "commerce-payment"]),
254            None,
255            &DevOptions::default(),
256        );
257        let report = serving_report(&serving);
258        assert!(report.contains("serving 2 contexts"), "{report}");
259        // Names are padded to the widest, so the URLs line up in a column.
260        assert!(
261            report.contains("commerce-orders   http://localhost:8787"),
262            "{report}"
263        );
264        assert!(
265            report.contains("commerce-payment  http://localhost:8788"),
266            "{report}"
267        );
268        // A lone default-port worker discloses no allocation — wrangler's own
269        // `Ready on` line is the announcement, exactly as before #552.
270        assert_eq!(
271            serving_report(&allocate(&names(&["links"]), None, &DevOptions::default())),
272            ""
273        );
274    }
275
276    #[test]
277    fn the_serving_event_reports_every_port() {
278        let serving = allocate(
279            &names(&["commerce-orders", "commerce-payment"]),
280            None,
281            &DevOptions {
282                inspect_port: Some(9229),
283                ..Default::default()
284            },
285        );
286        assert_eq!(
287            event_line(&serving_event(&serving, &[])),
288            r#"{"event":"serving","contexts":[{"name":"commerce-orders","port":8787,"url":"http://localhost:8787","inspector_port":9229},{"name":"commerce-payment","port":8788,"url":"http://localhost:8788","inspector_port":9230}]}"#
289        );
290        // A lone worker on wrangler's default still reports a port: 8787, or a
291        // `-- --port N` passthrough in either spelling.
292        let lone = allocate(&names(&["links"]), None, &DevOptions::default());
293        let port = |args: &[&str]| match serving_event(&lone, &names(args)) {
294            DevEvent::Serving { contexts } => (contexts[0].port, contexts[0].inspector_port),
295            other => panic!("{other:?}"),
296        };
297        assert_eq!(port(&[]), (8787, None));
298        assert_eq!(port(&["--port", "9000"]), (9000, None));
299        assert_eq!(port(&["--remote", "--port=9001"]), (9001, None));
300    }
301
302    #[test]
303    fn lifecycle_events_are_tagged_lines() {
304        assert_eq!(
305            event_line(&DevEvent::Rebuilding),
306            r#"{"event":"rebuilding"}"#
307        );
308        assert_eq!(
309            event_line(&DevEvent::RebuildOk),
310            r#"{"event":"rebuild_ok"}"#
311        );
312        assert_eq!(
313            event_line(&DevEvent::RebuildFailed),
314            r#"{"event":"rebuild_failed"}"#
315        );
316        assert_eq!(
317            event_line(&DevEvent::Stopped { code: 130 }),
318            r#"{"event":"stopped","code":130}"#
319        );
320    }
321
322    #[test]
323    fn a_log_event_is_a_tagged_line() {
324        assert_eq!(
325            event_line(&DevEvent::Log {
326                context: "shop".into(),
327                level: crate::logs::LogLevel::Error,
328                text: "    at f (/p/src/a.bynk:3:1)".into(),
329            }),
330            r#"{"event":"log","context":"shop","level":"error","text":"    at f (/p/src/a.bynk:3:1)"}"#
331        );
332    }
333
334    /// #3580: the `request` event's documented shape.
335    #[test]
336    fn a_request_event_is_a_tagged_line() {
337        let event = DevEvent::Request {
338            context: "shop-orders".into(),
339            id: "r1".into(),
340            parent: Some("p0".into()),
341            route: "POST /orders".into(),
342            status: 201,
343            duration_ms: 12.5,
344            steps: vec![crate::trace::TraceStep {
345                kind: "call".into(),
346                target: "shop.payment.authorise".into(),
347                span: Some(crate::trace::TraceSpan {
348                    file: "src/shop/orders.bynk".into(),
349                    line: 23,
350                    col: 14,
351                }),
352                ms: 3.5,
353                outcome: "ok".into(),
354                request: Some("c1".into()),
355            }],
356            truncated: false,
357            fault: None,
358        };
359        assert_eq!(
360            event_line(&event),
361            r#"{"event":"request","context":"shop-orders","id":"r1","parent":"p0","route":"POST /orders","status":201,"duration_ms":12.5,"steps":[{"kind":"call","target":"shop.payment.authorise","span":{"file":"src/shop/orders.bynk","line":23,"col":14},"ms":3.5,"outcome":"ok","request":"c1"}],"truncated":false,"fault":null}"#
362        );
363    }
364
365    #[test]
366    fn a_subset_of_one_claims_no_wiring() {
367        // "bindings between them are wired" would be a lie for a single
368        // context, and a misleading one: it invites reading a cross-context
369        // call's failure as a bug rather than as the context left unserved.
370        let report = serving_report(&allocate(
371            &names(&["commerce-payment"]),
372            Some(8890),
373            &DevOptions::default(),
374        ));
375        assert!(report.contains("serving 1 context."), "{report}");
376        assert!(!report.contains("bindings"), "{report}");
377    }
378}