Skip to main content

bynk/
trace.rs

1//! `bynk dev --trace-events` (#3580): the per-request trace a traced Worker
2//! prints, and the `request` event `bynk dev` makes of it.
3//!
4//! A traced Worker prints one `__bynk_trace:` line per request (the `trace`
5//! runtime module). The driver recognises it before the frame rewriter sees the
6//! line, parses it, maps the fault's stack frames to `.bynk` locations, and
7//! emits a [`crate::dev::DevEvent::Request`]. A line that carries the prefix but
8//! does not parse is left to the ordinary output, so nothing is lost.
9
10use serde::{Deserialize, Serialize};
11
12/// The prefix a traced Worker puts on its trace line.
13pub const TRACE_PREFIX: &str = "__bynk_trace:";
14
15/// The `.bynk` call site a step came from.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17pub struct TraceSpan {
18    pub file: String,
19    pub line: u32,
20    pub col: u32,
21}
22
23/// One recorded step of a request: what it called and how it went. It carries no
24/// argument values.
25#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
26pub struct TraceStep {
27    /// `capability`, `call` (a cross-context call) or `agent`.
28    pub kind: String,
29    /// What was called: `Db.query`, `shop.payment.authorise`, `Ledger.tally`.
30    pub target: String,
31    pub span: Option<TraceSpan>,
32    pub ms: f64,
33    /// `ok`, `fault`, or `pending` (not settled when the response was ready).
34    pub outcome: String,
35    /// A `call` step: the id of the callee's own request, so a client can join
36    /// this step to the callee's `request` event. Absent on other steps.
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub request: Option<String>,
39}
40
41/// A request's fault: the error's first line and its stack frames, with frames
42/// into generated code rewritten to `.bynk` locations.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
44pub struct TraceFault {
45    pub message: String,
46    pub frames: Vec<String>,
47}
48
49/// The line as the Worker printed it.
50#[derive(Debug, Deserialize)]
51pub struct RawTrace {
52    pub id: String,
53    /// The calling request's id, when a cross-context call carried one.
54    #[serde(default)]
55    pub parent: Option<String>,
56    pub route: String,
57    pub status: u16,
58    pub duration_ms: f64,
59    pub steps: Vec<TraceStep>,
60    pub truncated: bool,
61    pub fault: Option<String>,
62}
63
64/// The trace JSON on `line`, when it carries the prefix (anywhere in the line, as
65/// a host may put its own text before it).
66pub fn trace_json(line: &str) -> Option<&str> {
67    line.find(TRACE_PREFIX)
68        .map(|at| line[at + TRACE_PREFIX.len()..].trim_end())
69}
70
71/// Parse a trace line, or `None` when it is not one or is malformed.
72pub fn parse(line: &str) -> Option<RawTrace> {
73    serde_json::from_str(trace_json(line)?).ok()
74}
75
76/// A fault's stack as a [`TraceFault`], each frame passed through `rewrite`.
77pub fn fault(stack: &str, rewrite: impl Fn(&str) -> String) -> TraceFault {
78    let mut lines = stack.lines();
79    let message = lines.next().unwrap_or("").to_string();
80    TraceFault {
81        message,
82        frames: lines.map(|l| rewrite(l).trim().to_string()).collect(),
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    const LINE: &str = r#"__bynk_trace:{"context":"shop.orders","id":"r1","parent":"p0","route":"POST /orders","status":500,"duration_ms":12.5,"steps":[{"kind":"call","target":"shop.payment.authorise","span":{"file":"src/shop/orders.bynk","line":23,"col":14},"ms":3.1,"outcome":"fault","request":"c1"},{"kind":"agent","target":"Ledger.tally","span":null,"ms":0,"outcome":"pending"}],"truncated":false,"fault":"Error: boom\n    at f (index.js:1:2)"}"#;
91
92    #[test]
93    fn a_trace_line_parses() {
94        let t = parse(LINE).expect("parses");
95        assert_eq!(t.route, "POST /orders");
96        assert_eq!(t.parent.as_deref(), Some("p0"));
97        assert_eq!(t.steps[0].request.as_deref(), Some("c1"));
98        assert_eq!(t.steps[1].request, None);
99        assert_eq!(t.status, 500);
100        assert_eq!(t.steps.len(), 2);
101        assert_eq!(t.steps[0].span.as_ref().unwrap().line, 23);
102        assert_eq!(t.steps[1].span, None);
103    }
104
105    #[test]
106    fn host_text_before_the_prefix_is_tolerated() {
107        assert!(parse(&format!("[wrangler:inf] {LINE}")).is_some());
108    }
109
110    #[test]
111    fn other_lines_and_malformed_traces_are_not_traces() {
112        assert!(parse("hello").is_none());
113        assert!(parse("__bynk_trace:{not json").is_none());
114        assert!(trace_json("hello").is_none());
115    }
116
117    #[test]
118    fn a_fault_keeps_its_message_and_rewrites_each_frame() {
119        let f = fault(
120            "Error: boom\n    at f (index.js:1:2)\n    at g (index.js:3:4)",
121            |l| l.replace("index.js:1:2", "src/a.bynk:9:1"),
122        );
123        assert_eq!(f.message, "Error: boom");
124        assert_eq!(f.frames, ["at f (src/a.bynk:9:1)", "at g (index.js:3:4)"]);
125    }
126}