taskfast_cli/cmd/events/
poll.rs1use std::fs;
20use std::path::{Path, PathBuf};
21
22use clap::Parser;
23use serde_json::json;
24
25use super::super::{CmdError, CmdResult, Ctx};
26use crate::envelope::Envelope;
27
28use taskfast_agent::events::list_events_page_tolerant;
29
30#[derive(Debug, Parser)]
31pub struct PollArgs {
32 #[arg(long)]
36 pub cursor: Option<String>,
37
38 #[arg(long, default_value_t = 25)]
41 pub limit: i64,
42}
43
44pub async fn run(ctx: &Ctx, args: PollArgs) -> CmdResult {
45 let cursor_state = CursorState::resolve(args.cursor.as_deref(), ctx);
46 let effective_cursor = cursor_state.effective_cursor();
47
48 let client = ctx.client()?;
49 let page = list_events_page_tolerant(&client, effective_cursor, Some(args.limit))
50 .await
51 .map_err(CmdError::from)?;
52
53 if cursor_state.persistence_enabled() {
54 if let Some(path) = cursor_state.path() {
55 persist_cursor(path, page.meta.next_cursor.as_deref(), ctx);
56 }
57 }
58
59 for item in &page.unparseable {
60 tracing::warn!(
61 target: "taskfast::events",
62 raw = %item.raw,
63 error = %item.error,
64 "unparseable event surfaced via tolerant decode"
65 );
66 }
67
68 let unparseable: Vec<serde_json::Value> = page
69 .unparseable
70 .iter()
71 .map(|u| json!({ "raw": u.raw, "error": u.error }))
72 .collect();
73
74 Ok(Envelope::success(
75 ctx.environment,
76 ctx.dry_run,
77 json!({
78 "events": page.events,
79 "unparseable": unparseable,
80 "meta": page.meta,
81 }),
82 ))
83}
84
85const CURSOR_FILENAME: &str = "events.cursor";
89
90const DISABLE_SENTINEL: &str = "-";
92
93const DISABLE_ENV: &str = "TASKFAST_NO_CURSOR_STATE";
96
97struct CursorState {
103 request_cursor: Option<String>,
105 persist_to: Option<PathBuf>,
108}
109
110impl CursorState {
111 fn resolve(cursor_arg: Option<&str>, ctx: &Ctx) -> Self {
112 let env_disabled = std::env::var(DISABLE_ENV).is_ok_and(|v| v == "1");
113 let sentinel = matches!(cursor_arg, Some(s) if s == DISABLE_SENTINEL);
114 let persist_to = if env_disabled || sentinel {
115 None
116 } else {
117 cursor_path(ctx)
118 };
119
120 let request_cursor = match cursor_arg {
121 Some(s) if s == DISABLE_SENTINEL => None,
122 Some(s) => Some(s.to_string()),
123 None => persist_to.as_deref().and_then(read_cursor),
124 };
125
126 Self {
127 request_cursor,
128 persist_to,
129 }
130 }
131
132 fn effective_cursor(&self) -> Option<&str> {
133 self.request_cursor.as_deref()
134 }
135
136 fn persistence_enabled(&self) -> bool {
137 self.persist_to.is_some()
138 }
139
140 fn path(&self) -> Option<&Path> {
141 self.persist_to.as_deref()
142 }
143}
144
145fn cursor_path(ctx: &Ctx) -> Option<PathBuf> {
148 let parent = ctx.config_path.parent()?;
149 if parent.as_os_str().is_empty() {
150 return Some(PathBuf::from(CURSOR_FILENAME));
151 }
152 if parent == Path::new("/dev") {
153 return None;
154 }
155 Some(parent.join(CURSOR_FILENAME))
156}
157
158fn read_cursor(path: &Path) -> Option<String> {
159 let raw = fs::read_to_string(path).ok()?;
160 let trimmed = raw.trim().to_string();
161 if trimmed.is_empty() {
162 None
163 } else {
164 Some(trimmed)
165 }
166}
167
168fn persist_cursor(path: &Path, next_cursor: Option<&str>, ctx: &Ctx) {
177 let Some(payload) = next_cursor else {
178 return;
179 };
180 if let Some(dir) = path.parent() {
181 if let Err(e) = fs::create_dir_all(dir) {
182 warn_persist_failed(ctx, path, &e.to_string());
183 return;
184 }
185 }
186 if let Err(e) = fs::write(path, payload) {
187 warn_persist_failed(ctx, path, &e.to_string());
188 }
189}
190
191fn warn_persist_failed(ctx: &Ctx, path: &Path, reason: &str) {
192 if ctx.quiet {
193 return;
194 }
195 eprintln!(
196 "warning: failed to persist events cursor to {}: {reason}",
197 path.display()
198 );
199}
200
201#[cfg(test)]
202mod tests {
203 use super::*;
204 use std::path::PathBuf;
205
206 fn ctx_with_config(path: PathBuf) -> Ctx {
207 Ctx {
208 config_path: path,
209 ..Default::default()
210 }
211 }
212
213 #[test]
214 fn cursor_path_uses_config_parent() {
215 let ctx = ctx_with_config(PathBuf::from("/tmp/foo/.taskfast/config.json"));
216 assert_eq!(
217 cursor_path(&ctx),
218 Some(PathBuf::from("/tmp/foo/.taskfast/events.cursor"))
219 );
220 }
221
222 #[test]
223 fn cursor_path_skips_dev_null() {
224 let ctx = ctx_with_config(PathBuf::from("/dev/null"));
225 assert_eq!(cursor_path(&ctx), None);
226 }
227
228 #[test]
229 fn dash_sentinel_disables_both_request_and_persistence() {
230 let ctx = ctx_with_config(PathBuf::from("/tmp/x/.taskfast/config.json"));
231 let s = CursorState::resolve(Some("-"), &ctx);
232 assert!(!s.persistence_enabled());
233 assert_eq!(s.effective_cursor(), None);
234 }
235
236 #[test]
237 fn explicit_cursor_uses_passed_value() {
238 let ctx = ctx_with_config(PathBuf::from("/tmp/x/.taskfast/config.json"));
239 let s = CursorState::resolve(Some("abc"), &ctx);
240 assert_eq!(s.effective_cursor(), Some("abc"));
241 assert!(s.persistence_enabled());
242 }
243
244 #[test]
245 fn explicit_cursor_still_sent_when_persistence_unavailable() {
246 let ctx = ctx_with_config(PathBuf::from("/dev/null"));
247 let s = CursorState::resolve(Some("abc"), &ctx);
248 assert_eq!(s.effective_cursor(), Some("abc"));
249 assert!(!s.persistence_enabled());
250 }
251
252 #[test]
253 fn dev_null_config_disables_persistence() {
254 let ctx = ctx_with_config(PathBuf::from("/dev/null"));
255 let s = CursorState::resolve(None, &ctx);
256 assert_eq!(s.effective_cursor(), None);
257 assert!(!s.persistence_enabled());
258 }
259
260 #[test]
261 fn write_then_read_round_trips() {
262 let dir = tempfile::tempdir().unwrap();
263 let cfg = dir.path().join("config.json");
264 let ctx = ctx_with_config(cfg);
265 let path = cursor_path(&ctx).unwrap();
266 persist_cursor(&path, Some("xyz"), &ctx);
267 assert_eq!(read_cursor(&path), Some("xyz".into()));
268 }
269
270 #[test]
271 fn persist_none_preserves_last_known_cursor() {
272 let dir = tempfile::tempdir().unwrap();
273 let cfg = dir.path().join("config.json");
274 let ctx = ctx_with_config(cfg);
275 let path = cursor_path(&ctx).unwrap();
276 persist_cursor(&path, Some("abc"), &ctx);
277 persist_cursor(&path, None, &ctx);
278 assert_eq!(read_cursor(&path), Some("abc".into()));
279 }
280}