Skip to main content

sutegi_repl/
lib.rs

1//! A tinker-style interactive shell for sutegi apps — Laravel's `artisan
2//! tinker`, reimagined for an agent-native framework.
3//!
4//! This is **not** a Rust evaluator (that would need a compiler toolchain and
5//! third-party machinery). It is a command shell over the surfaces a sutegi
6//! app already exposes:
7//!
8//! - the **agent contract** — `/__introspect`, `/__tools`, tool invocation
9//!   (streaming tools print their SSE frames live), and raw HTTP requests
10//!   through the app's own routes;
11//! - the **data layer** — raw SQL, a `where`-clause query DSL, KV, the event
12//!   store, and the job queue, when a [`Backend`] is attached.
13//!
14//! Two transports, one command set:
15//!
16//! ```no_run
17//! use sutegi_repl::Repl;
18//! use sutegi_web::App;
19//!
20//! // In-process: consume the built App; data commands work via `.db(...)`.
21//! let app = App::new("demo").get("/", "Health.", |_| "ok");
22//! Repl::new(app).run().unwrap();
23//! ```
24//!
25//! Remote mode is the agent contract exercised by a human: it drives a
26//! *running* app over plain HTTP with no source access — exactly the way an
27//! LLM does — so `sutegi repl <addr>` works against any sutegi app:
28//!
29//! ```no_run
30//! sutegi_repl::Repl::connect("127.0.0.1:8080").run().unwrap();
31//! ```
32//!
33//! Line editing is deliberately plain `stdin` (zero deps, works everywhere);
34//! wrap with `rlwrap` if you want history and arrow keys.
35
36use std::io::{self, BufRead, Read, Write};
37use std::net::TcpStream;
38
39use sutegi_http::{Body, Method, Request, Response};
40use sutegi_json::Json;
41#[cfg(feature = "orm")]
42use sutegi_orm::{Backend, QueryBuilder, Value};
43use sutegi_web::App;
44
45type Service = Box<dyn Fn(Request) -> Response>;
46
47enum Surface {
48    /// The app's request closure, no socket — `App::service()`.
49    InProcess(Service),
50    /// A running server, spoken to over one-shot HTTP/1.1 connections.
51    Remote { host: String, port: u16 },
52}
53
54/// The REPL: a [`Surface`] to send requests through, plus an optional data
55/// backend for the `sql`/`q`/`kv`/… commands.
56pub struct Repl {
57    surface: Surface,
58    #[cfg(feature = "orm")]
59    db: Option<Box<dyn Backend>>,
60}
61
62impl Repl {
63    /// Wrap a built [`App`] for in-process tinkering. Consumes the app (the
64    /// same closure `serve()` would run — routing, middleware, tools, ops
65    /// endpoints — minus the socket). No socket means no remote caller, so
66    /// the ops surface is opened ([`App::ops_public`]) for this closure only;
67    /// a set `ops_guard` still applies.
68    pub fn new(app: App) -> Repl {
69        Repl {
70            surface: Surface::InProcess(Box::new(app.ops_public().service())),
71            #[cfg(feature = "orm")]
72            db: None,
73        }
74    }
75
76    /// Attach to a running sutegi app at `addr` (`host:port`, an optional
77    /// `http://` prefix is tolerated). Everything the remote REPL does goes
78    /// through the app's public HTTP surface.
79    pub fn connect(addr: &str) -> Repl {
80        let (host, port) = parse_addr(addr);
81        Repl {
82            surface: Surface::Remote { host, port },
83            #[cfg(feature = "orm")]
84            db: None,
85        }
86    }
87
88    /// Attach a data backend (usually the same handle the app holds in
89    /// `.state(...)` — `Db` and `Pg` are `Clone`). Enables the data commands.
90    #[cfg(feature = "orm")]
91    pub fn db(mut self, db: impl Backend + 'static) -> Repl {
92        self.db = Some(Box::new(db));
93        self
94    }
95
96    /// The interactive loop: read a line from stdin, run it, print, repeat.
97    pub fn run(self) -> io::Result<()> {
98        let stdin = io::stdin();
99        let mut out = io::stdout();
100        writeln!(out, "sutegi repl — 'help' lists commands, 'exit' leaves")?;
101        let mut line = String::new();
102        loop {
103            write!(out, "sutegi> ")?;
104            out.flush()?;
105            line.clear();
106            if stdin.lock().read_line(&mut line)? == 0 {
107                writeln!(out)?;
108                return Ok(()); // EOF (ctrl-d / end of piped script)
109            }
110            let cmd = line.trim();
111            if cmd.is_empty() {
112                continue;
113            }
114            if matches!(cmd, "exit" | "quit") {
115                return Ok(());
116            }
117            self.dispatch(cmd, &mut out)?;
118        }
119    }
120
121    /// Evaluate one command and return its output — the programmatic seam the
122    /// interactive loop is built on, and what tests drive.
123    pub fn eval(&self, line: &str) -> String {
124        let mut buf: Vec<u8> = Vec::new();
125        let _ = self.dispatch(line.trim(), &mut buf);
126        String::from_utf8_lossy_owned(buf)
127    }
128
129    fn dispatch(&self, line: &str, out: &mut dyn Write) -> io::Result<()> {
130        let (cmd, rest) = split_first(line);
131        match cmd {
132            "help" => help(out),
133            "introspect" => self.request(Method::Get, "/__introspect", None, out),
134            "routes" => self.routes(out),
135            "models" => self.manifest_slice("/__introspect", "models", out),
136            "tools" => self.tools(out),
137            "tool" => self.tool_schema(rest, out),
138            "call" => self.call(rest, out),
139            "get" | "post" | "put" | "patch" | "delete" => {
140                let (path, body) = split_first(rest);
141                if path.is_empty() {
142                    return writeln!(out, "usage: {cmd} <path> [json body]");
143                }
144                let body = if body.is_empty() { None } else { Some(body) };
145                self.request(Method::parse(&cmd.to_uppercase()), path, body, out)
146            }
147            "sql" | "table" | "count" | "q" | "kv" | "events" | "jobs" => {
148                self.data_cmd(cmd, rest, out)
149            }
150            other => writeln!(out, "unknown command '{other}' — try 'help'"),
151        }
152    }
153
154    // ---- surface commands ---------------------------------------------
155
156    fn routes(&self, out: &mut dyn Write) -> io::Result<()> {
157        let manifest = match self.fetch_json("/__introspect") {
158            Ok(j) => j,
159            Err(e) => return writeln!(out, "error: {e}"),
160        };
161        let routes = manifest.get("routes").and_then(Json::as_array);
162        for r in routes.into_iter().flatten() {
163            let method = r.get("method").and_then(Json::as_str).unwrap_or("?");
164            let pattern = r.get("pattern").and_then(Json::as_str).unwrap_or("?");
165            let doc = r.get("doc").and_then(Json::as_str).unwrap_or("");
166            writeln!(out, "{method:<7} {pattern:<32} {doc}")?;
167        }
168        Ok(())
169    }
170
171    fn tools(&self, out: &mut dyn Write) -> io::Result<()> {
172        let manifest = match self.tool_manifest() {
173            Ok(j) => j,
174            Err(e) => return writeln!(out, "error: {e}"),
175        };
176        let tools = manifest.as_array().map(Vec::as_slice).unwrap_or(&[]);
177        if tools.is_empty() {
178            return writeln!(out, "no tools registered");
179        }
180        for t in tools {
181            let name = t.get("name").and_then(Json::as_str).unwrap_or("?");
182            let streaming = t.get("streaming").and_then(Json::as_bool).unwrap_or(false);
183            let desc = t.get("description").and_then(Json::as_str).unwrap_or("");
184            let tag = if streaming { "streaming" } else { "unary" };
185            writeln!(out, "{name:<24} [{tag:<9}] {desc}")?;
186        }
187        Ok(())
188    }
189
190    fn tool_schema(&self, rest: &str, out: &mut dyn Write) -> io::Result<()> {
191        let (name, _) = split_first(rest);
192        if name.is_empty() {
193            return writeln!(out, "usage: tool <name>");
194        }
195        match self.find_tool(name) {
196            Ok(Some(entry)) => writeln!(out, "{}", entry.to_pretty()),
197            Ok(None) => writeln!(out, "unknown tool '{name}'"),
198            Err(e) => writeln!(out, "error: {e}"),
199        }
200    }
201
202    /// Invoke a tool by name. Streaming tools are detected from the manifest
203    /// and their SSE frames are written through as they arrive.
204    fn call(&self, rest: &str, out: &mut dyn Write) -> io::Result<()> {
205        let (name, args) = split_first(rest);
206        if name.is_empty() {
207            return writeln!(out, "usage: call <name> [{{json args}}]");
208        }
209        let args = if args.is_empty() { "{}" } else { args };
210        if Json::parse(args).is_err() {
211            return writeln!(out, "arguments must be valid JSON, got: {args}");
212        }
213        let streaming = match self.find_tool(name) {
214            Ok(Some(entry)) => entry
215                .get("streaming")
216                .and_then(Json::as_bool)
217                .unwrap_or(false),
218            Ok(None) => return writeln!(out, "unknown tool '{name}' — 'tools' lists them"),
219            Err(e) => return writeln!(out, "error: {e}"),
220        };
221        let path = if streaming {
222            format!("/__tools/{name}/stream")
223        } else {
224            format!("/__tools/{name}")
225        };
226        self.request(Method::Post, &path, Some(args), out)
227    }
228
229    fn manifest_slice(&self, target: &str, key: &str, out: &mut dyn Write) -> io::Result<()> {
230        match self.fetch_json(target) {
231            Ok(j) => {
232                let slice = j.get(key).cloned().unwrap_or(Json::arr(vec![]));
233                writeln!(out, "{}", slice.to_pretty())
234            }
235            Err(e) => writeln!(out, "error: {e}"),
236        }
237    }
238
239    fn tool_manifest(&self) -> Result<Json, String> {
240        // `/__tools` only exists once a tool is registered; report that
241        // usefully instead of a bare 404.
242        self.fetch_json("/__tools")
243            .map_err(|e| format!("{e} (does the app register any tools?)"))
244    }
245
246    fn find_tool(&self, name: &str) -> Result<Option<Json>, String> {
247        let manifest = self.tool_manifest()?;
248        Ok(manifest
249            .as_array()
250            .into_iter()
251            .flatten()
252            .find(|t| t.get("name").and_then(Json::as_str) == Some(name))
253            .cloned())
254    }
255
256    // ---- transport ------------------------------------------------------
257
258    /// Perform a request and print the response: JSON bodies pretty-printed,
259    /// streaming bodies written through incrementally, non-200 statuses
260    /// prefixed on their own `[status]` line.
261    fn request(
262        &self,
263        method: Method,
264        target: &str,
265        body: Option<&str>,
266        out: &mut dyn Write,
267    ) -> io::Result<()> {
268        match &self.surface {
269            Surface::InProcess(svc) => {
270                let resp = svc(build_request(method, target, body));
271                if resp.status != 200 {
272                    writeln!(out, "[{}]", resp.status)?;
273                }
274                let ct = header(&resp.headers, "content-type").unwrap_or_default();
275                match resp.body {
276                    Body::Full(bytes) => print_body(out, &ct, &bytes),
277                    Body::Reader { reader, length } => {
278                        std::io::copy(&mut std::io::Read::take(reader, length), out)?;
279                        writeln!(out)
280                    }
281                    Body::Stream(producer) => {
282                        // The producer flushes per frame; `out` sees them live.
283                        if let Err(e) = producer(out) {
284                            writeln!(out, "stream error: {e}")?;
285                        }
286                        writeln!(out)
287                    }
288                    // A REPL request is not a socket to hand over.
289                    Body::Upgrade(_) => {
290                        writeln!(out, "[101] connection upgrade (unsupported here)")
291                    }
292                }
293            }
294            Surface::Remote { host, port } => {
295                match self.remote(host, *port, method, target, body, out) {
296                    Ok(()) => Ok(()),
297                    Err(e) => writeln!(
298                        out,
299                        "request failed: {e} (is the app running at {host}:{port}?)"
300                    ),
301                }
302            }
303        }
304    }
305
306    /// One `Connection: close` HTTP/1.1 exchange, reading the body
307    /// incrementally so close-framed SSE streams print frame by frame.
308    fn remote(
309        &self,
310        host: &str,
311        port: u16,
312        method: Method,
313        target: &str,
314        body: Option<&str>,
315        out: &mut dyn Write,
316    ) -> io::Result<()> {
317        let mut stream = TcpStream::connect((host, port))?;
318        let body = body.unwrap_or("");
319        let mut req = format!(
320            "{} {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\nAccept: application/json\r\n",
321            method.as_str(),
322            target,
323            host
324        );
325        if !body.is_empty() {
326            req.push_str("Content-Type: application/json\r\n");
327            req.push_str(&format!("Content-Length: {}\r\n", body.len()));
328        }
329        req.push_str("\r\n");
330        req.push_str(body);
331        stream.write_all(req.as_bytes())?;
332
333        let mut head: Vec<u8> = Vec::new();
334        let mut json_buf: Option<Vec<u8>> = None; // Some => buffer to pretty-print at EOF
335        let mut in_body = false;
336        let mut buf = [0u8; 4096];
337        loop {
338            let n = stream.read(&mut buf)?;
339            if n == 0 {
340                break;
341            }
342            let mut chunk: &[u8] = &buf[..n];
343            if !in_body {
344                head.extend_from_slice(chunk);
345                let Some(pos) = find_blank_line(&head) else {
346                    continue;
347                };
348                let header_text = String::from_utf8_lossy(&head[..pos]).into_owned();
349                let status = parse_status(&header_text);
350                if status != 200 {
351                    writeln!(out, "[{status}]")?;
352                }
353                let json = header_line(&header_text, "content-type")
354                    .map(|ct| ct.contains("application/json"))
355                    .unwrap_or(false);
356                json_buf = json.then(Vec::new);
357                in_body = true;
358                let rest = head.split_off(pos + 4);
359                match &mut json_buf {
360                    Some(b) => b.extend_from_slice(&rest),
361                    None => {
362                        out.write_all(&rest)?;
363                        out.flush()?;
364                    }
365                }
366                chunk = &[];
367            }
368            match &mut json_buf {
369                Some(b) => b.extend_from_slice(chunk),
370                None => {
371                    if !chunk.is_empty() {
372                        out.write_all(chunk)?;
373                        out.flush()?;
374                    }
375                }
376            }
377        }
378        match json_buf {
379            Some(b) => print_body(out, "application/json", &b),
380            None => writeln!(out),
381        }
382    }
383
384    /// A buffered GET that must yield JSON — the manifest fetches.
385    fn fetch_json(&self, target: &str) -> Result<Json, String> {
386        match &self.surface {
387            Surface::InProcess(svc) => {
388                let resp = svc(build_request(Method::Get, target, None));
389                if resp.status != 200 {
390                    return Err(format!("GET {target} -> {}", resp.status));
391                }
392                match resp.body {
393                    Body::Full(bytes) => Json::parse(&String::from_utf8_lossy(&bytes)),
394                    Body::Stream(_) | Body::Reader { .. } => {
395                        Err(format!("GET {target} unexpectedly streams"))
396                    }
397                    Body::Upgrade(_) => Err(format!("GET {target} unexpectedly upgrades")),
398                }
399            }
400            Surface::Remote { host, port } => {
401                let mut buf: Vec<u8> = Vec::new();
402                self.remote(host, *port, Method::Get, target, None, &mut buf)
403                    .map_err(|e| e.to_string())?;
404                let text = String::from_utf8_lossy(&buf);
405                let text = text.trim();
406                if let Some(status) = text.strip_prefix('[').and_then(|t| t.split(']').next())
407                    && status.bytes().all(|b| b.is_ascii_digit())
408                {
409                    return Err(format!("GET {target} -> {status}"));
410                }
411                Json::parse(text)
412            }
413        }
414    }
415
416    // ---- data commands ---------------------------------------------------
417
418    #[cfg(feature = "orm")]
419    fn data_cmd(&self, cmd: &str, rest: &str, out: &mut dyn Write) -> io::Result<()> {
420        let Some(db) = &self.db else {
421            return writeln!(
422                out,
423                "no database attached — in-process, chain `.db(db)`; \
424                 a remote REPL reaches data through the app's routes and tools"
425            );
426        };
427        let db = db.as_ref();
428        let result = match cmd {
429            "sql" => run_sql(db, rest),
430            "table" => run_table(db, rest),
431            "count" => run_count(db, rest),
432            "q" => parse_query(rest)
433                .and_then(|qb| db.select(&qb))
434                .map(rows_pretty),
435            "kv" => run_kv(db, rest),
436            "events" => run_events(db, rest),
437            "jobs" => run_jobs(db),
438            _ => unreachable!("dispatch only routes data commands here"),
439        };
440        match result {
441            Ok(text) => writeln!(out, "{text}"),
442            Err(e) => writeln!(out, "error: {e}"),
443        }
444    }
445
446    #[cfg(not(feature = "orm"))]
447    fn data_cmd(&self, _cmd: &str, _rest: &str, out: &mut dyn Write) -> io::Result<()> {
448        writeln!(
449            out,
450            "data commands need the `orm` feature (and an attached db); \
451             a remote REPL reaches data through the app's routes and tools"
452        )
453    }
454}
455
456fn help(out: &mut dyn Write) -> io::Result<()> {
457    writeln!(
458        out,
459        "surface (works in-process and remote)
460  introspect                       full app manifest (/__introspect)
461  routes | models | tools          slices of the manifest
462  tool <name>                      one tool's schema
463  call <name> [{{json args}}]       invoke a tool; streaming tools print SSE frames live
464  get|post|put|patch|delete <path> [json]
465                                   raw request through the app
466
467data (needs an attached backend: Repl::db(...))
468  sql <statement>                  raw SQL — SELECT prints rows, else the affected count
469  table <name> [n]                 peek at a table (default 10 rows)
470  count <table> [where ...]        row count
471  q <table> [select a,b] [where <col> <op> <val> [and ...]] [order <col> [desc]] [limit n] [offset n]
472  kv get|set|del|keys|scan <ns> [key] [json]
473  events [stream] [n]              recent events from the event store
474  jobs                             queue depth + recent jobs
475
476  exit                             leave"
477    )
478}
479
480// ---- request plumbing -----------------------------------------------------
481
482fn build_request(method: Method, target: &str, body: Option<&str>) -> Request {
483    let (path, query) = match target.split_once('?') {
484        Some((p, q)) => (p.to_string(), q.to_string()),
485        None => (target.to_string(), String::new()),
486    };
487    let body: Vec<u8> = body.map(|b| b.as_bytes().to_vec()).unwrap_or_default();
488    let mut headers = vec![("accept".to_string(), "application/json".to_string())];
489    if !body.is_empty() {
490        headers.push(("content-type".to_string(), "application/json".to_string()));
491        headers.push(("content-length".to_string(), body.len().to_string()));
492    }
493    Request {
494        method,
495        path,
496        query,
497        version: "HTTP/1.1".to_string(),
498        headers,
499        body,
500        peer: Some("repl".to_string()),
501    }
502}
503
504fn header(headers: &[(String, String)], name: &str) -> Option<String> {
505    headers
506        .iter()
507        .find(|(k, _)| k.eq_ignore_ascii_case(name))
508        .map(|(_, v)| v.clone())
509}
510
511fn print_body(out: &mut dyn Write, content_type: &str, bytes: &[u8]) -> io::Result<()> {
512    let text = String::from_utf8_lossy(bytes);
513    if content_type.contains("application/json")
514        && let Ok(j) = Json::parse(&text)
515    {
516        return writeln!(out, "{}", j.to_pretty());
517    }
518    writeln!(out, "{}", text.trim_end())
519}
520
521fn find_blank_line(buf: &[u8]) -> Option<usize> {
522    buf.windows(4).position(|w| w == b"\r\n\r\n")
523}
524
525fn parse_status(header_text: &str) -> u16 {
526    header_text
527        .lines()
528        .next()
529        .and_then(|l| l.split_whitespace().nth(1))
530        .and_then(|s| s.parse().ok())
531        .unwrap_or(0)
532}
533
534fn header_line(header_text: &str, name: &str) -> Option<String> {
535    header_text.lines().skip(1).find_map(|l| {
536        let (k, v) = l.split_once(':')?;
537        k.trim()
538            .eq_ignore_ascii_case(name)
539            .then(|| v.trim().to_ascii_lowercase())
540    })
541}
542
543fn parse_addr(addr: &str) -> (String, u16) {
544    let rest = addr.trim_prefix("http://");
545    let rest = rest.trim_end_matches('/');
546    match rest.split_once(':') {
547        Some((h, p)) => (h.to_string(), p.parse().unwrap_or(80)),
548        None => (rest.to_string(), 80),
549    }
550}
551
552/// Split off the first whitespace-delimited word; the remainder keeps its
553/// internal spacing (JSON bodies, SQL, docs).
554fn split_first(line: &str) -> (&str, &str) {
555    let line = line.trim();
556    match line.split_once(char::is_whitespace) {
557        Some((first, rest)) => (first, rest.trim()),
558        None => (line, ""),
559    }
560}
561
562// ---- data command implementations ------------------------------------------
563
564/// Shell-ish tokenizer: whitespace-separated, single or double quotes group a
565/// token and mark it as quoted (so `'42'` stays a string in the value parser).
566#[cfg(feature = "orm")]
567fn tokens(s: &str) -> Vec<(String, bool)> {
568    let mut out = Vec::new();
569    let mut cur = String::new();
570    let mut quoted = false;
571    let mut quote: Option<char> = None;
572    for c in s.chars() {
573        match quote {
574            Some(q) if c == q => quote = None,
575            Some(_) => cur.push(c),
576            None if c == '\'' || c == '"' => {
577                quote = Some(c);
578                quoted = true;
579            }
580            None if c.is_whitespace() => {
581                if !cur.is_empty() || quoted {
582                    out.push((std::mem::take(&mut cur), quoted));
583                    quoted = false;
584                }
585            }
586            None => cur.push(c),
587        }
588    }
589    if !cur.is_empty() || quoted {
590        out.push((cur, quoted));
591    }
592    out
593}
594
595#[cfg(feature = "orm")]
596fn parse_value(tok: &str, was_quoted: bool) -> Value {
597    if was_quoted {
598        return Value::Text(tok.to_string());
599    }
600    match tok {
601        "null" => Value::Null,
602        "true" => Value::Bool(true),
603        "false" => Value::Bool(false),
604        _ => {
605            if let Ok(i) = tok.parse::<i64>() {
606                Value::Int(i)
607            } else if let Ok(f) = tok.parse::<f64>() {
608                Value::Real(f)
609            } else {
610                Value::Text(tok.to_string())
611            }
612        }
613    }
614}
615
616/// Parse the `q` mini-DSL into a [`QueryBuilder`]. Identifier and operator
617/// validation is the builder's own job (`build()` rejects bad ones).
618#[cfg(feature = "orm")]
619fn parse_query(rest: &str) -> Result<QueryBuilder, String> {
620    let toks = tokens(rest);
621    let table = toks
622        .first()
623        .map(|(t, _)| t.clone())
624        .ok_or("usage: q <table> [select a,b] [where <col> <op> <val> [and ...]] [order <col> [desc]] [limit n] [offset n]")?;
625    let mut qb = QueryBuilder::table(&table);
626    let mut i = 1;
627    while i < toks.len() {
628        match toks[i].0.to_ascii_lowercase().as_str() {
629            "select" => {
630                let cols = &toks
631                    .get(i + 1)
632                    .ok_or("select needs a column list (a,b,c)")?
633                    .0;
634                let cols: Vec<&str> = cols.split(',').map(str::trim).collect();
635                qb = qb.select(&cols);
636                i += 2;
637            }
638            "where" | "and" => {
639                let [col, op, val] = [toks.get(i + 1), toks.get(i + 2), toks.get(i + 3)];
640                let (Some(col), Some(op), Some(val)) = (col, op, val) else {
641                    return Err("where/and needs `<col> <op> <value>`".to_string());
642                };
643                qb = qb.filter(&col.0, &op.0, parse_value(&val.0, val.1));
644                i += 4;
645            }
646            "order" => {
647                let col = toks.get(i + 1).ok_or("order needs a column")?;
648                let dir = toks.get(i + 2).map(|(t, _)| t.to_ascii_lowercase());
649                let desc = dir.as_deref() == Some("desc");
650                qb = qb.order_by(&col.0, desc);
651                i += if matches!(dir.as_deref(), Some("desc") | Some("asc")) {
652                    3
653                } else {
654                    2
655                };
656            }
657            "limit" => {
658                let n = parse_num(toks.get(i + 1), "limit")?;
659                qb = qb.limit(n);
660                i += 2;
661            }
662            "offset" => {
663                let n = parse_num(toks.get(i + 1), "offset")?;
664                qb = qb.offset(n);
665                i += 2;
666            }
667            other => return Err(format!("unexpected '{other}' in query")),
668        }
669    }
670    Ok(qb)
671}
672
673#[cfg(feature = "orm")]
674fn parse_num(tok: Option<&(String, bool)>, what: &str) -> Result<i64, String> {
675    tok.and_then(|(t, _)| t.parse().ok())
676        .ok_or_else(|| format!("{what} needs a number"))
677}
678
679#[cfg(feature = "orm")]
680fn rows_pretty(rows: Vec<Json>) -> String {
681    let n = rows.len();
682    let plural = if n == 1 { "row" } else { "rows" };
683    format!("{}\n({n} {plural})", Json::arr(rows).to_pretty())
684}
685
686#[cfg(feature = "orm")]
687fn run_sql(db: &dyn Backend, sql: &str) -> Result<String, String> {
688    if sql.is_empty() {
689        return Err("usage: sql <statement>".to_string());
690    }
691    let first = sql
692        .split_whitespace()
693        .next()
694        .unwrap_or("")
695        .to_ascii_lowercase();
696    if matches!(
697        first.as_str(),
698        "select" | "with" | "pragma" | "explain" | "show" | "values"
699    ) {
700        db.query(sql, &[]).map(rows_pretty)
701    } else {
702        db.execute(sql, &[]).map(|n| {
703            let plural = if n == 1 { "row" } else { "rows" };
704            format!("{n} {plural} affected")
705        })
706    }
707}
708
709#[cfg(feature = "orm")]
710fn run_table(db: &dyn Backend, rest: &str) -> Result<String, String> {
711    let toks = tokens(rest);
712    let table = toks
713        .first()
714        .map(|(t, _)| t.clone())
715        .ok_or("usage: table <name> [n]")?;
716    let limit = toks.get(1).and_then(|(t, _)| t.parse().ok()).unwrap_or(10);
717    let qb = QueryBuilder::table(&table).limit(limit);
718    db.select(&qb).map(rows_pretty)
719}
720
721#[cfg(feature = "orm")]
722fn run_count(db: &dyn Backend, rest: &str) -> Result<String, String> {
723    if rest.is_empty() {
724        return Err("usage: count <table> [where ...]".to_string());
725    }
726    let qb = parse_query(rest)?;
727    db.count(&qb).map(|n| n.to_string())
728}
729
730#[cfg(feature = "orm")]
731fn run_kv(db: &dyn Backend, rest: &str) -> Result<String, String> {
732    // Same portable SQL and table (`kv`) as `sutegi_orm::kv::Kv`, so
733    // the REPL sees exactly what the app's KV layer wrote.
734    const USAGE: &str = "usage: kv get|set|del|keys|scan <ns> [key] [json]";
735    let (sub, rest) = split_first(rest);
736    let toks = tokens(rest);
737    let ns = toks
738        .first()
739        .map(|(t, _)| Value::Text(t.clone()))
740        .ok_or(USAGE)?;
741    let key = toks.get(1).map(|(t, _)| Value::Text(t.clone()));
742    match (sub, key) {
743        ("get", Some(key)) => {
744            let row = db.query_one("SELECT value FROM kv WHERE ns = ? AND key = ?", &[ns, key])?;
745            match row.and_then(|r| r.get("value").and_then(Json::as_str).map(str::to_string)) {
746                Some(v) => Ok(Json::parse(&v).map(|j| j.to_pretty()).unwrap_or(v)),
747                None => Ok("(not set)".to_string()),
748            }
749        }
750        ("set", Some(key)) => {
751            // `rest` is "<ns> <key> <json...>"; take the raw tail so JSON
752            // objects with spaces survive intact.
753            let (_, after_ns) = split_first(rest);
754            let (_, raw) = split_first(after_ns);
755            if raw.is_empty() {
756                return Err("kv set needs a JSON value".to_string());
757            }
758            let value = Json::parse(raw).map_err(|e| format!("value is not JSON: {e}"))?;
759            let now = std::time::SystemTime::now()
760                .duration_since(std::time::UNIX_EPOCH)
761                .map(|d| d.as_millis() as i64)
762                .unwrap_or(0);
763            db.execute(
764                "INSERT INTO kv (ns, key, value, updated_at) VALUES (?, ?, ?, ?) \
765                 ON CONFLICT (ns, key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
766                &[ns, key, Value::Text(value.to_string()), Value::Int(now)],
767            )?;
768            Ok("ok".to_string())
769        }
770        ("del", Some(key)) => db
771            .execute("DELETE FROM kv WHERE ns = ? AND key = ?", &[ns, key])
772            .map(|n| {
773                if n > 0 {
774                    "deleted".to_string()
775                } else {
776                    "(not set)".to_string()
777                }
778            }),
779        ("keys", None) => {
780            let rows = db.query("SELECT key FROM kv WHERE ns = ? ORDER BY key", &[ns])?;
781            Ok(rows
782                .iter()
783                .filter_map(|r| r.get("key").and_then(Json::as_str))
784                .collect::<Vec<_>>()
785                .join("\n"))
786        }
787        ("scan", None) => db
788            .query("SELECT key, value FROM kv WHERE ns = ? ORDER BY key", &[ns])
789            .map(rows_pretty),
790        _ => Err(USAGE.to_string()),
791    }
792}
793
794#[cfg(feature = "orm")]
795fn run_events(db: &dyn Backend, rest: &str) -> Result<String, String> {
796    let toks = tokens(rest);
797    match toks.first() {
798        None => db
799            .query(
800                "SELECT position, stream, version, name, payload FROM sutegi_events \
801                 ORDER BY position DESC LIMIT 20",
802                &[],
803            )
804            .map(rows_pretty),
805        Some((stream, _)) => {
806            let limit = toks.get(1).and_then(|(t, _)| t.parse().ok()).unwrap_or(20);
807            db.query(
808                "SELECT position, stream, version, name, payload FROM sutegi_events \
809                 WHERE stream = ? ORDER BY version DESC LIMIT ?",
810                &[Value::Text(stream.clone()), Value::Int(limit)],
811            )
812            .map(rows_pretty)
813        }
814    }
815}
816
817#[cfg(feature = "orm")]
818fn run_jobs(db: &dyn Backend) -> Result<String, String> {
819    let counts = db.query_one(
820        "SELECT \
821            SUM(CASE WHEN failed_at IS NULL AND locked_at IS NULL THEN 1 ELSE 0 END) AS pending, \
822            SUM(CASE WHEN failed_at IS NULL AND locked_at IS NOT NULL THEN 1 ELSE 0 END) AS running, \
823            SUM(CASE WHEN failed_at IS NOT NULL THEN 1 ELSE 0 END) AS dead, \
824            COUNT(*) AS total \
825         FROM sutegi_jobs",
826        &[],
827    )?;
828    let recent = db.query(
829        "SELECT id, name, attempts, max_attempts, last_error FROM sutegi_jobs \
830         ORDER BY id DESC LIMIT 10",
831        &[],
832    )?;
833    let counts = counts.unwrap_or(Json::obj(vec![]));
834    Ok(format!(
835        "{}\nrecent:\n{}",
836        counts.to_pretty(),
837        rows_pretty(recent)
838    ))
839}
840
841#[cfg(test)]
842mod tests {
843    use super::*;
844
845    #[test]
846    fn split_first_separates_word_and_tail() {
847        assert_eq!(
848            split_first("call add {\"a\": 1}"),
849            ("call", "add {\"a\": 1}")
850        );
851        assert_eq!(split_first("routes"), ("routes", ""));
852        assert_eq!(split_first("  sql select 1  "), ("sql", "select 1"));
853    }
854
855    #[test]
856    fn parse_addr_accepts_bare_and_prefixed() {
857        assert_eq!(
858            parse_addr("127.0.0.1:8080"),
859            ("127.0.0.1".to_string(), 8080)
860        );
861        assert_eq!(
862            parse_addr("http://localhost:9000/"),
863            ("localhost".to_string(), 9000)
864        );
865        assert_eq!(parse_addr("example.test"), ("example.test".to_string(), 80));
866    }
867
868    #[test]
869    fn status_and_header_parse_from_head_text() {
870        let head = "HTTP/1.1 422 Unprocessable Entity\r\nContent-Type: application/json\r\nX: y";
871        assert_eq!(parse_status(head), 422);
872        assert_eq!(
873            header_line(head, "content-type").as_deref(),
874            Some("application/json")
875        );
876        assert_eq!(header_line(head, "missing"), None);
877    }
878
879    #[cfg(feature = "orm")]
880    mod orm {
881        use super::super::*;
882
883        #[test]
884        fn tokenizer_groups_quotes_and_marks_them() {
885            let toks = tokens("where title = 'hello world' and n = 42");
886            assert_eq!(toks[3], ("hello world".to_string(), true));
887            assert_eq!(toks[7], ("42".to_string(), false));
888        }
889
890        #[test]
891        fn values_parse_by_shape_unless_quoted() {
892            assert_eq!(parse_value("42", false), Value::Int(42));
893            assert_eq!(parse_value("42", true), Value::Text("42".to_string()));
894            assert_eq!(parse_value("1.5", false), Value::Real(1.5));
895            assert_eq!(parse_value("true", false), Value::Bool(true));
896            assert_eq!(parse_value("null", false), Value::Null);
897            assert_eq!(parse_value("open", false), Value::Text("open".to_string()));
898        }
899
900        #[test]
901        fn query_dsl_builds_parameterized_sql() {
902            let qb = parse_query("todos select id,title where done = false and id > 3 order id desc limit 5 offset 2")
903                .unwrap();
904            let (sql, params) = qb.build().unwrap();
905            assert_eq!(
906                sql,
907                "SELECT id, title FROM todos WHERE done = ? AND id > ? ORDER BY id DESC LIMIT 5 OFFSET 2"
908            );
909            assert_eq!(params, vec![Value::Bool(false), Value::Int(3)]);
910        }
911
912        #[test]
913        fn query_dsl_rejects_junk() {
914            assert!(parse_query("").is_err());
915            assert!(parse_query("todos frobnicate").is_err());
916            assert!(parse_query("todos where done =").is_err());
917        }
918    }
919}