Skip to main content

bynk/
tail.rs

1//! `bynk tail` (#2546): a deployed Worker's logs, with the stack frames that
2//! name generated TypeScript rewritten to the `.bynk` line they came from.
3//!
4//! The second slice of ADR 0622. `wrangler tail` does the streaming; the
5//! driver compiles the project (nothing is deployed or provisioned) so the
6//! emitter's source maps are on disk, and pipes the tail through the same
7//! `Rewriter` `bynk dev` uses. Frames that name the
8//! deployed bundle rather than a module, or a module the build has no map for,
9//! pass through unchanged. Wrangler's pretty printer may print an uncaught
10//! exception's name and message without its stack, in which case the frames
11//! that can be mapped are those a handler's own `console.*` output carries.
12
13use bynk_driver::emsg;
14use std::path::Path;
15use std::process::{ExitCode, Stdio};
16use std::sync::{Arc, Mutex};
17use std::time::Duration;
18
19use crate::dev::forward_lines;
20use crate::logs::{Classifier, Rewriter};
21use crate::probe::{self, DetectOpts, Provenance, Toolbox};
22use crate::workers;
23
24/// Parsed `bynk tail` flags.
25#[derive(Debug, Clone, Default)]
26pub struct TailOptions {
27    /// `--context NAME`; `None` when the project has a single context.
28    pub context: Option<String>,
29    /// `--env NAME` (default `"default"`): the `bynk deploy --env` environment.
30    pub environment: String,
31    /// Arguments after `--`, forwarded to `wrangler tail`.
32    pub wrangler_args: Vec<String>,
33}
34
35/// The one worker to tail: the requested context, or the only one built.
36fn pick_worker(available: &[String], requested: Option<&str>) -> Result<String, String> {
37    let requested: Vec<String> = requested.map(str::to_string).into_iter().collect();
38    let chosen = workers::select_contexts(available, &requested).map_err(|e| e.to_string())?;
39    match chosen.as_slice() {
40        [one] => Ok(one.clone()),
41        _ => Err(format!(
42            "this project has several contexts — pick one with `--context NAME` (available: {})",
43            available.join(", ")
44        )),
45    }
46}
47
48/// The arguments after `wrangler tail`: the Worker, then the caller's own.
49/// Wrangler defaults `--format` to `json` when stdout is not a terminal, and
50/// ours is a pipe, so one JSON object per event would pass through with its
51/// stack on a single escaped line, never matching a frame. `pretty` is asked
52/// for unless the caller chose a format.
53fn tail_args(deployed: &str, extra: &[String]) -> Vec<String> {
54    let mut args = vec![deployed.to_string()];
55    args.extend(extra.iter().cloned());
56    if !extra
57        .iter()
58        .any(|a| a == "--format" || a.starts_with("--format="))
59    {
60        args.extend(["--format".into(), "pretty".into()]);
61    }
62    args
63}
64
65/// Compile, resolve the Worker's deployed name, and stream `wrangler tail`.
66/// Returns wrangler's exit code.
67pub fn run(tb: &dyn Toolbox, project_root: &Path, opts: &TailOptions) -> ExitCode {
68    let probe = probe::detect(
69        tb,
70        "wrangler",
71        DetectOpts {
72            project_root: Some(project_root),
73            allow_npx: true,
74            manager: Some(bynk_driver::npm_install::manager_in(project_root, tb)),
75        },
76    );
77    if matches!(probe.provenance, Provenance::Missing) {
78        emsg!("bynk: error: wrangler not found (run `bynk doctor --only deploy`)");
79        return ExitCode::FAILURE;
80    }
81
82    let build_dir = project_root.join(".bynk").join("tail");
83    if let Err(e) = workers::prepare_build_dir(project_root, &build_dir) {
84        emsg!("bynk: error: could not prepare build directory: {e}");
85        return ExitCode::FAILURE;
86    }
87    // `schema_registry` off: tailing must not touch `bynk.schema.lock`.
88    if !workers::compile_once(project_root, &build_dir, false) {
89        return ExitCode::FAILURE;
90    }
91    let workers_dir = build_dir.join("workers");
92    let available = workers::discover_workers(&workers_dir);
93    let worker = match pick_worker(&available, opts.context.as_deref()) {
94        Ok(w) => w,
95        Err(e) => {
96            emsg!("bynk: error: {e}");
97            return ExitCode::FAILURE;
98        }
99    };
100    let deployed = crate::deploy::deployed_worker_name(&opts.environment, &worker);
101
102    let Some(mut cmd) = crate::cloudflare::spawn_command(&probe.provenance, "tail") else {
103        emsg!("bynk: error: wrangler not found (run `bynk doctor --only deploy`)");
104        return ExitCode::FAILURE;
105    };
106    cmd.current_dir(workers_dir.join(&worker))
107        .args(tail_args(&deployed, &opts.wrangler_args))
108        .stdout(Stdio::piped())
109        .stderr(Stdio::piped());
110    // Piped, wrangler can't see our terminal: it colours as `--color` says.
111    bynk_driver::colour::apply_to_child(&mut cmd, true);
112    crate::stop::install();
113    let mut child = match cmd.spawn() {
114        Ok(c) => c,
115        Err(e) => {
116            emsg!("bynk: error: could not run wrangler tail: {e}");
117            return ExitCode::FAILURE;
118        }
119    };
120    emsg!(
121        "bynk tail: tailing `{deployed}` (frames are mapped to .bynk where the build has a map)."
122    );
123
124    let rewriter = Arc::new(Rewriter::new(&build_dir));
125    let classifier = Arc::new(Mutex::new(Classifier::default()));
126    let mut pumps = Vec::new();
127    if let Some(out) = child.stdout.take() {
128        let (rw, cl, w) = (rewriter.clone(), classifier.clone(), worker.clone());
129        pumps.push(std::thread::spawn(move || {
130            use std::io::Write;
131            forward_lines(out, &w, &rw, &cl, |line, _| {
132                let _ = writeln!(std::io::stdout().lock(), "{line}");
133            });
134        }));
135    }
136    if let Some(err) = child.stderr.take() {
137        let (rw, cl, w) = (rewriter.clone(), classifier.clone(), worker.clone());
138        pumps.push(std::thread::spawn(move || {
139            use std::io::Write;
140            forward_lines(err, &w, &rw, &cl, |line, _| {
141                let _ = writeln!(std::io::stderr().lock(), "{line}");
142            });
143        }));
144    }
145
146    let code = loop {
147        if let Some(sig) = crate::stop::received() {
148            let _ = child.kill();
149            let _ = child.wait();
150            break crate::stop::exit_byte(sig);
151        }
152        match child.try_wait() {
153            Ok(Some(status)) => break crate::shell::exit_status_byte(&status),
154            Ok(None) => std::thread::sleep(Duration::from_millis(100)),
155            Err(e) => {
156                emsg!("bynk: error: could not poll wrangler: {e}");
157                break 1;
158            }
159        }
160    };
161    // Bounded drain, as `dev`: the last lines usually say why it ended.
162    let deadline = std::time::Instant::now() + Duration::from_secs(2);
163    while std::time::Instant::now() < deadline && !pumps.iter().all(|p| p.is_finished()) {
164        std::thread::sleep(Duration::from_millis(10));
165    }
166    ExitCode::from(code)
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    fn names(n: &[&str]) -> Vec<String> {
174        n.iter().map(|s| s.to_string()).collect()
175    }
176
177    #[test]
178    fn pretty_is_asked_for_unless_a_format_is_given() {
179        assert_eq!(tail_args("w", &[]), ["w", "--format", "pretty"]);
180        let json = names(&["--format", "json"]);
181        assert_eq!(tail_args("w", &json), ["w", "--format", "json"]);
182        let eq = names(&["--format=json"]);
183        assert_eq!(tail_args("w", &eq), ["w", "--format=json"]);
184    }
185
186    #[test]
187    fn a_lone_context_needs_no_flag() {
188        assert_eq!(
189            pick_worker(&names(&["shop-cart"]), None),
190            Ok("shop-cart".into())
191        );
192    }
193
194    #[test]
195    fn several_contexts_need_a_choice() {
196        let err = pick_worker(&names(&["a", "b"]), None).unwrap_err();
197        assert!(err.contains("--context") && err.contains("a, b"), "{err}");
198    }
199
200    #[test]
201    fn a_dotted_name_resolves_to_its_worker_dir() {
202        assert_eq!(
203            pick_worker(&names(&["shop-cart", "shop-pay"]), Some("shop.cart")),
204            Ok("shop-cart".into())
205        );
206    }
207
208    #[test]
209    fn an_unknown_context_is_named() {
210        let err = pick_worker(&names(&["a"]), Some("zzz")).unwrap_err();
211        assert!(err.contains("zzz"), "{err}");
212    }
213
214    #[test]
215    fn tailed_lines_get_bynk_frames() {
216        let dir = std::env::temp_dir().join(format!("bynk-tail-{}", std::process::id()));
217        let worker = dir.join("workers").join("shop");
218        std::fs::create_dir_all(&worker).unwrap();
219        std::fs::write(
220            worker.join("handlers.ts.map"),
221            r#"{"version":3,"file":"h.ts","sources":["/p/src/a.bynk"],"mappings":";AASA"}"#,
222        )
223        .unwrap();
224        let rewriter = Rewriter::new(&dir);
225        let classifier = Mutex::new(Classifier::default());
226        let input = "Error: boom\n    at http_GET (handlers.ts:2:1)\nplain\n";
227        let mut got = Vec::new();
228        forward_lines(input.as_bytes(), "shop", &rewriter, &classifier, |l, _| {
229            got.push(l.to_string())
230        });
231        let _ = std::fs::remove_dir_all(&dir);
232        assert_eq!(
233            got,
234            [
235                "Error: boom",
236                "    at http_GET (/p/src/a.bynk:10:1)",
237                "plain"
238            ]
239        );
240    }
241}