Skip to main content

xs/nu/commands/
cat_command.rs

1use nu_engine::CallExt;
2use nu_protocol::engine::{Call, Command, EngineState, Stack};
3use nu_protocol::shell_error::generic::GenericError;
4use nu_protocol::{
5    Category, ListStream, PipelineData, ShellError, Signals, Signature, SyntaxShape, Type, Value,
6};
7use std::time::Duration;
8
9use crate::store::{FollowOption, ReadOptions, Store};
10
11#[derive(Clone)]
12pub struct CatCommand {
13    store: Store,
14}
15
16impl CatCommand {
17    pub fn new(store: Store) -> Self {
18        Self { store }
19    }
20}
21
22// Parse a Scru128Id, boxing the (large) ShellError so the returned Result stays
23// small (avoids clippy::result_large_err). Callers unbox at the `?` boundary.
24fn parse_id(
25    s: &str,
26    name: &str,
27    span: nu_protocol::Span,
28) -> Result<scru128::Scru128Id, Box<ShellError>> {
29    s.parse().map_err(|e| {
30        Box::new(ShellError::Generic(GenericError::new(
31            format!("Invalid {name}"),
32            format!("Failed to parse Scru128Id: {e}"),
33            span,
34        )))
35    })
36}
37
38impl Command for CatCommand {
39    fn name(&self) -> &str {
40        ".cat"
41    }
42
43    fn signature(&self) -> Signature {
44        Signature::build(".cat")
45            .input_output_types(vec![(Type::Nothing, Type::Any)])
46            .switch("follow", "long poll for new events", Some('f'))
47            .named(
48                "pulse",
49                SyntaxShape::Int,
50                "interval in ms for synthetic xs.pulse events",
51                Some('p'),
52            )
53            .switch("new", "skip existing, only show new", Some('n'))
54            .switch("detail", "include all frame fields", Some('d'))
55            .named(
56                "limit",
57                SyntaxShape::Int,
58                "limit the number of frames to retrieve",
59                None,
60            )
61            .named(
62                "after",
63                SyntaxShape::String,
64                "start after a specific frame ID (exclusive)",
65                Some('a'),
66            )
67            .named(
68                "from",
69                SyntaxShape::String,
70                "start from a specific frame ID (inclusive)",
71                None,
72            )
73            .named(
74                "last",
75                SyntaxShape::Int,
76                "return the N most recent frames",
77                None,
78            )
79            .named(
80                "topic",
81                SyntaxShape::OneOf(vec![
82                    SyntaxShape::String,
83                    SyntaxShape::List(Box::new(SyntaxShape::String)),
84                ]),
85                "filter by topic pattern(s): string (commas allowed) or list",
86                Some('T'),
87            )
88            .switch(
89                "with-timestamp",
90                "include timestamp extracted from frame ID",
91                None,
92            )
93            .category(Category::Experimental)
94    }
95
96    fn description(&self) -> &str {
97        "Reads the event stream and returns frames"
98    }
99
100    fn run(
101        &self,
102        engine_state: &EngineState,
103        stack: &mut Stack,
104        call: &Call,
105        _input: PipelineData,
106    ) -> Result<PipelineData, ShellError> {
107        let follow = call.has_flag(engine_state, stack, "follow")?;
108        let pulse: Option<i64> = call.get_flag(engine_state, stack, "pulse")?;
109        let new = call.has_flag(engine_state, stack, "new")?;
110        let detail = call.has_flag(engine_state, stack, "detail")?;
111        let with_timestamp = call.has_flag(engine_state, stack, "with-timestamp")?;
112        let limit: Option<i64> = call.get_flag(engine_state, stack, "limit")?;
113        let last: Option<i64> = call.get_flag(engine_state, stack, "last")?;
114        let after: Option<String> = call.get_flag(engine_state, stack, "after")?;
115        let from: Option<String> = call.get_flag(engine_state, stack, "from")?;
116        let topic: Option<nu_protocol::Value> = call.get_flag(engine_state, stack, "topic")?;
117        let topic: Option<String> = topic
118            .map(crate::nu::util::topic_value_to_string)
119            .transpose()?;
120
121        let span = call.head;
122
123        let after: Option<scru128::Scru128Id> = after
124            .as_deref()
125            .map(|s| parse_id(s, "after", span))
126            .transpose()
127            .map_err(|e| *e)?;
128        let from: Option<scru128::Scru128Id> = from
129            .as_deref()
130            .map(|s| parse_id(s, "from", span))
131            .transpose()
132            .map_err(|e| *e)?;
133
134        // Build ReadOptions
135        let following = pulse.is_some() || follow;
136        let options = ReadOptions::builder()
137            .follow(if let Some(pulse_ms) = pulse {
138                FollowOption::WithHeartbeat(Duration::from_millis(pulse_ms as u64))
139            } else if follow {
140                FollowOption::On
141            } else {
142                FollowOption::Off
143            })
144            .new(new)
145            .maybe_after(after)
146            .maybe_from(from)
147            .maybe_limit(limit.map(|l| l as usize))
148            .maybe_last(last.map(|l| l as usize))
149            .maybe_topic(topic)
150            .build();
151
152        // Shape one frame into a Value, stripping `ttl` unless `--detail`.
153        let to_value = move |frame: &crate::store::Frame| {
154            let value = crate::nu::util::frame_to_value(frame, span, with_timestamp);
155            if detail {
156                return value;
157            }
158            match value {
159                Value::Record { val, .. } => {
160                    let mut filtered = val.into_owned();
161                    filtered.remove("ttl");
162                    Value::record(filtered, span)
163                }
164                v => v,
165            }
166        };
167
168        if following {
169            // Follow mode: stream lazily. The follow/heartbeat task runs on the
170            // shared runtime; the consumer dropping the ListStream cancels it
171            // (the L1 fd-leak fix). Driven off the runtime in real use.
172            let mut rx = self.store.read(options);
173            let stream = ListStream::new(
174                std::iter::from_fn(move || {
175                    let frame = rx.blocking_recv()?; // parks off-runtime; None when producer done/cancelled
176                    Some(to_value(&frame))
177                }),
178                span,
179                Signals::empty(),
180            );
181            return Ok(PipelineData::ListStream(stream, None));
182        }
183
184        // Historical mode: stream lazily, same shape as the follow branch. The
185        // producer closes the channel once replay completes, so from_fn ends.
186        // blocking_recv parks the caller thread; callers that reach `.cat`
187        // during an actor's async setup run the config eval on a dedicated
188        // thread (see parse_config), so this never parks a runtime thread.
189        let mut rx = self.store.read(options);
190        let stream = ListStream::new(
191            std::iter::from_fn(move || {
192                let frame = rx.blocking_recv()?; // None when the producer finishes replay
193                Some(to_value(&frame))
194            }),
195            span,
196            Signals::empty(),
197        );
198        Ok(PipelineData::ListStream(stream, None))
199    }
200}