Skip to main content

xs/nu/commands/
last_command.rs

1use nu_engine::CallExt;
2use nu_protocol::engine::{Call, Command, EngineState, Stack};
3use nu_protocol::{
4    Category, ListStream, PipelineData, ShellError, Signals, Signature, SyntaxShape, Type, Value,
5};
6
7use crate::nu::util;
8use crate::store::{FollowOption, ReadOptions, Store};
9
10#[derive(Clone)]
11pub struct LastCommand {
12    store: Store,
13}
14
15impl LastCommand {
16    pub fn new(store: Store) -> Self {
17        Self { store }
18    }
19}
20
21impl Command for LastCommand {
22    fn name(&self) -> &str {
23        ".last"
24    }
25
26    fn signature(&self) -> Signature {
27        Signature::build(".last")
28            .input_output_types(vec![(Type::Nothing, Type::Any)])
29            .optional(
30                "topic",
31                SyntaxShape::Any,
32                "topic pattern(s) to get most recent frames from: string (commas allowed) or list (default: all topics)",
33            )
34            .optional(
35                "count",
36                SyntaxShape::Int,
37                "number of frames to return (default: 1)",
38            )
39            .switch(
40                "follow",
41                "long poll for updates to most recent frame",
42                Some('f'),
43            )
44            .switch(
45                "with-timestamp",
46                "include timestamp extracted from frame ID",
47                None,
48            )
49            .category(Category::Experimental)
50    }
51
52    fn description(&self) -> &str {
53        "get the most recent frame(s) for a topic"
54    }
55
56    fn run(
57        &self,
58        engine_state: &EngineState,
59        stack: &mut Stack,
60        call: &Call,
61        _input: PipelineData,
62    ) -> Result<PipelineData, ShellError> {
63        let raw_topic: Option<Value> = call.opt(engine_state, stack, 0)?;
64        let raw_count: Option<i64> = call.opt(engine_state, stack, 1)?;
65        let follow = call.has_flag(engine_state, stack, "follow")?;
66        let with_timestamp = call.has_flag(engine_state, stack, "with-timestamp")?;
67        let span = call.head;
68
69        // Disambiguate: if topic is an integer (or parses as one) and count is
70        // absent, treat it as the count (topics cannot start with digits per
71        // ADR 0002)
72        let (topic, n) = match (raw_topic, raw_count) {
73            (Some(Value::Int { val, .. }), None) if val > 0 => (None, val as usize),
74            (Some(Value::String { val, .. }), None) if val.parse::<usize>().is_ok() => {
75                (None, val.parse::<usize>().unwrap())
76            }
77            (raw_topic, raw_count) => (
78                raw_topic.map(util::topic_value_to_string).transpose()?,
79                raw_count.map(|v| v as usize).unwrap_or(1),
80            ),
81        };
82
83        if follow {
84            // Follow mode: stream historical-then-new through the receiver. The
85            // consumer dropping the ListStream cancels the producer task (L1).
86            let options = ReadOptions::builder()
87                .last(n)
88                .maybe_topic(topic)
89                .follow(FollowOption::On)
90                .build();
91
92            let mut rx = self.store.read(options);
93            let stream = ListStream::new(
94                std::iter::from_fn(move || {
95                    let frame = rx.blocking_recv()?; // parks off-runtime; None when producer done/cancelled
96                    Some(util::frame_to_value(&frame, span, with_timestamp))
97                }),
98                span,
99                Signals::empty(),
100            );
101
102            return Ok(PipelineData::ListStream(stream, None));
103        }
104
105        // Historical-only mode. Collect from the read receiver here (not via a
106        // shared eager helper) so we can preserve the single-value semantics for
107        // count == 1: a bare `.last topic` returns one Value, not a one-element
108        // list. The producer closes the channel once replay completes, so this
109        // loop terminates. blocking_recv parks the caller thread; callers that
110        // reach `.last` during an actor's async setup run the config eval on a
111        // dedicated thread (see parse_config), so this never parks a runtime
112        // thread.
113        let options = ReadOptions::builder().last(n).maybe_topic(topic).build();
114
115        let mut rx = self.store.read(options);
116        let frames: Vec<Value> = std::iter::from_fn(move || {
117            let frame = rx.blocking_recv()?; // None when the producer finishes replay
118            Some(util::frame_to_value(&frame, span, with_timestamp))
119        })
120        .collect();
121
122        if frames.is_empty() {
123            Ok(PipelineData::Empty)
124        } else if frames.len() == 1 {
125            Ok(PipelineData::Value(
126                frames.into_iter().next().unwrap(),
127                None,
128            ))
129        } else {
130            Ok(PipelineData::Value(Value::list(frames, span), None))
131        }
132    }
133}