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
22fn 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 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 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 let mut rx = self.store.read(options);
173 let rt = self.store.runtime();
174 let signals = engine_state.signals().clone();
175 let waiting = signals.clone();
176 let stream = ListStream::new(
177 std::iter::from_fn(move || {
178 let item = crate::nu::util::follow_recv(&mut rx, rt.as_ref(), &waiting)?;
179 Some(crate::nu::util::follow_value(&item, span, to_value))
180 }),
181 span,
182 signals,
183 );
184 return Ok(PipelineData::ListStream(stream, None));
185 }
186
187 let mut rx = self.store.read(options);
193 let stream = ListStream::new(
194 std::iter::from_fn(move || {
195 let frame = rx.blocking_recv()?.ok()?;
198 Some(to_value(&frame))
199 }),
200 span,
201 Signals::empty(),
202 );
203 Ok(PipelineData::ListStream(stream, None))
204 }
205}