| 1 | //! Standalone native accelerator CLI and JSON-RPC stdio worker for `last30days-skill`. |
| 2 | |
| 3 | use std::env; |
| 4 | use std::io::{self, BufRead, BufWriter, Write}; |
| 5 | |
| 6 | use anyhow::{Context, Result}; |
| 7 | use last30days_core::cluster::{ClusterCandidate, ClusterOutput, ClusterPlan, cluster_candidates}; |
| 8 | use last30days_core::dedupe::{DedupeEntry, dedupe_kept_indices, hybrid_similarity}; |
| 9 | use last30days_core::entity::{entity_overlap, extract_text_entities}; |
| 10 | use last30days_core::markdown::{ |
| 11 | MarkdownBatchItem, MarkdownBatchResult, MarkdownFileRequest, MarkdownScanOutcome, |
| 12 | has_private_corpus, is_unbounded_private_brief, public_markdown, sanitize_markdown_batch, |
| 13 | scan_markdown_files_batch, |
| 14 | }; |
| 15 | use last30days_core::relevance::{PreparedQuery, token_overlap_relevance}; |
| 16 | use last30days_core::signals::{AnnotatedSignal, FreshnessMode, SignalItem, annotate_stream}; |
| 17 | use serde::{Deserialize, Serialize}; |
| 18 | |
| 19 | const PROTOCOL_VERSION: u32 = 1; |
| 20 | |
| 21 | #[derive(Debug, Deserialize)] |
| 22 | #[serde(tag = "op", rename_all = "snake_case")] |
| 23 | enum Request { |
| 24 | Ping, |
| 25 | DedupeIndices { |
| 26 | entries: Vec<DedupeEntry>, |
| 27 | threshold: f64, |
| 28 | }, |
| 29 | HybridSimilarity { |
| 30 | text_a: String, |
| 31 | text_b: String, |
| 32 | }, |
| 33 | TokenOverlapRelevance { |
| 34 | query: String, |
| 35 | text: String, |
| 36 | #[serde(default)] |
| 37 | hashtags: Vec<String>, |
| 38 | }, |
| 39 | AnnotateStream { |
| 40 | items: Vec<SignalItem>, |
| 41 | ranking_query: String, |
| 42 | freshness_mode: FreshnessMode, |
| 43 | reference_date: String, |
| 44 | max_days: i64, |
| 45 | }, |
| 46 | ClusterCandidates { |
| 47 | candidates: Vec<ClusterCandidate>, |
| 48 | plan: ClusterPlan, |
| 49 | }, |
| 50 | ExtractEntities { |
| 51 | text: String, |
| 52 | }, |
| 53 | EntityOverlap { |
| 54 | text_a: String, |
| 55 | text_b: String, |
| 56 | }, |
| 57 | PublicMarkdown { |
| 58 | markdown: String, |
| 59 | }, |
| 60 | HasPrivateCorpus { |
| 61 | markdown: String, |
| 62 | }, |
| 63 | IsUnboundedPrivateBrief { |
| 64 | markdown: String, |
| 65 | source_format: Option<String>, |
| 66 | }, |
| 67 | SanitizeMarkdownBatch { |
| 68 | items: Vec<MarkdownBatchItem>, |
| 69 | }, |
| 70 | ScanMarkdownFiles { |
| 71 | requests: Vec<MarkdownFileRequest>, |
| 72 | }, |
| 73 | } |
| 74 | |
| 75 | #[derive(Debug, Serialize)] |
| 76 | #[serde(tag = "status", rename_all = "snake_case")] |
| 77 | enum Response { |
| 78 | Ok { |
| 79 | #[serde(flatten)] |
| 80 | payload: ResponsePayload, |
| 81 | }, |
| 82 | Error { |
| 83 | message: String, |
| 84 | }, |
| 85 | } |
| 86 | |
| 87 | #[derive(Debug, Serialize)] |
| 88 | #[serde(untagged)] |
| 89 | enum ResponsePayload { |
| 90 | Pong { |
| 91 | version: &'static str, |
| 92 | protocol: u32, |
| 93 | }, |
| 94 | Indices { |
| 95 | indices: Vec<usize>, |
| 96 | }, |
| 97 | Score { |
| 98 | score: f64, |
| 99 | }, |
| 100 | Annotated { |
| 101 | items: Vec<AnnotatedSignal>, |
| 102 | }, |
| 103 | Clusters { |
| 104 | clusters: Vec<ClusterOutput>, |
| 105 | }, |
| 106 | Entities { |
| 107 | entities: Vec<String>, |
| 108 | }, |
| 109 | Markdown { |
| 110 | markdown: String, |
| 111 | }, |
| 112 | Flag { |
| 113 | value: bool, |
| 114 | }, |
| 115 | SanitizedBatch { |
| 116 | results: Vec<MarkdownBatchResult>, |
| 117 | }, |
| 118 | ScanOutcomes { |
| 119 | outcomes: Vec<MarkdownScanOutcome>, |
| 120 | }, |
| 121 | } |
| 122 | |
| 123 | fn ok(payload: ResponsePayload) -> Response { |
| 124 | Response::Ok { payload } |
| 125 | } |
| 126 | |
| 127 | fn err_msg(message: impl Into<String>) -> Response { |
| 128 | Response::Error { |
| 129 | message: message.into(), |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | fn handle_request(request: Request) -> Response { |
| 134 | match request { |
| 135 | Request::Ping => ok(ResponsePayload::Pong { |
| 136 | version: env!("CARGO_PKG_VERSION"), |
| 137 | protocol: PROTOCOL_VERSION, |
| 138 | }), |
| 139 | Request::DedupeIndices { entries, threshold } => { |
| 140 | match dedupe_kept_indices(&entries, threshold) { |
| 141 | Ok(indices) => ok(ResponsePayload::Indices { indices }), |
| 142 | Err(err) => err_msg(err.to_string()), |
| 143 | } |
| 144 | } |
| 145 | Request::HybridSimilarity { text_a, text_b } => ok(ResponsePayload::Score { |
| 146 | score: hybrid_similarity(&text_a, &text_b), |
| 147 | }), |
| 148 | Request::TokenOverlapRelevance { |
| 149 | query, |
| 150 | text, |
| 151 | hashtags, |
| 152 | } => { |
| 153 | let prepared = PreparedQuery::new(&query); |
| 154 | ok(ResponsePayload::Score { |
| 155 | score: token_overlap_relevance(&prepared, &text, &hashtags), |
| 156 | }) |
| 157 | } |
| 158 | Request::AnnotateStream { |
| 159 | items, |
| 160 | ranking_query, |
| 161 | freshness_mode, |
| 162 | reference_date, |
| 163 | max_days, |
| 164 | } => match annotate_stream( |
| 165 | &items, |
| 166 | &ranking_query, |
| 167 | freshness_mode, |
| 168 | &reference_date, |
| 169 | max_days, |
| 170 | ) { |
| 171 | Ok(annotated) => ok(ResponsePayload::Annotated { items: annotated }), |
| 172 | Err(err) => err_msg(err.to_string()), |
| 173 | }, |
| 174 | Request::ClusterCandidates { candidates, plan } => ok(ResponsePayload::Clusters { |
| 175 | clusters: cluster_candidates(&candidates, &plan), |
| 176 | }), |
| 177 | Request::ExtractEntities { text } => ok(ResponsePayload::Entities { |
| 178 | entities: extract_text_entities(&text).into_iter().collect(), |
| 179 | }), |
| 180 | Request::EntityOverlap { text_a, text_b } => { |
| 181 | let a = extract_text_entities(&text_a); |
| 182 | let b = extract_text_entities(&text_b); |
| 183 | ok(ResponsePayload::Score { |
| 184 | score: entity_overlap(&a, &b), |
| 185 | }) |
| 186 | } |
| 187 | Request::PublicMarkdown { markdown } => ok(ResponsePayload::Markdown { |
| 188 | markdown: public_markdown(&markdown), |
| 189 | }), |
| 190 | Request::HasPrivateCorpus { markdown } => ok(ResponsePayload::Flag { |
| 191 | value: has_private_corpus(&markdown), |
| 192 | }), |
| 193 | Request::IsUnboundedPrivateBrief { |
| 194 | markdown, |
| 195 | source_format, |
| 196 | } => ok(ResponsePayload::Flag { |
| 197 | value: is_unbounded_private_brief(&markdown, source_format.as_deref()), |
| 198 | }), |
| 199 | Request::SanitizeMarkdownBatch { items } => ok(ResponsePayload::SanitizedBatch { |
| 200 | results: sanitize_markdown_batch(&items), |
| 201 | }), |
| 202 | Request::ScanMarkdownFiles { requests } => ok(ResponsePayload::ScanOutcomes { |
| 203 | outcomes: scan_markdown_files_batch(&requests), |
| 204 | }), |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | fn run_serve_loop() -> Result<()> { |
| 209 | let stdin = io::stdin(); |
| 210 | let stdout = io::stdout(); |
| 211 | let mut writer = BufWriter::new(stdout.lock()); |
| 212 | |
| 213 | for line_result in stdin.lock().lines() { |
| 214 | let line = line_result.context("reading request line from stdin")?; |
| 215 | let trimmed = line.trim(); |
| 216 | if trimmed.is_empty() { |
| 217 | continue; |
| 218 | } |
| 219 | let response = match serde_json::from_str::<Request>(trimmed) { |
| 220 | Ok(req) => handle_request(req), |
| 221 | Err(err) => Response::Error { |
| 222 | message: format!("invalid request JSON: {err}"), |
| 223 | }, |
| 224 | }; |
| 225 | serde_json::to_writer(&mut writer, &response).context("serializing response JSON")?; |
| 226 | writer.write_all(b"\n").context("writing newline")?; |
| 227 | writer.flush().context("flushing stdout")?; |
| 228 | } |
| 229 | Ok(()) |
| 230 | } |
| 231 | |
| 232 | fn main() -> Result<()> { |
| 233 | let mut args = env::args().skip(1); |
| 234 | match args.next().as_deref() { |
| 235 | Some("serve") | None => run_serve_loop(), |
| 236 | Some("--version" | "-V" | "version") => { |
| 237 | let mut stdout = io::stdout().lock(); |
| 238 | writeln!( |
| 239 | stdout, |
| 240 | "last30days-core {} (protocol {})", |
| 241 | env!("CARGO_PKG_VERSION"), |
| 242 | PROTOCOL_VERSION |
| 243 | ) |
| 244 | .context("writing version")?; |
| 245 | Ok(()) |
| 246 | } |
| 247 | Some("--help" | "-h" | "help") => { |
| 248 | let mut stdout = io::stdout().lock(); |
| 249 | writeln!( |
| 250 | stdout, |
| 251 | "last30days-core {} - native CPU accelerator for last30days-skill\n\n\ |
| 252 | Usage:\n last30days-core serve Run newline-delimited JSON worker on stdio\n \ |
| 253 | last30days-core version Print binary and protocol version", |
| 254 | env!("CARGO_PKG_VERSION") |
| 255 | ) |
| 256 | .context("writing help")?; |
| 257 | Ok(()) |
| 258 | } |
| 259 | Some(unknown) => { |
| 260 | anyhow::bail!("unknown subcommand `{unknown}`; expected `serve`, `version`, or `help`") |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 |