1use kute_core::{AdapterCapabilities, ModalityAdapter};
18use kute_types::{AdapterConfig, CanonicalInput, KuteError, Modality, Payload, Result};
19use serde_json::Value;
20
21pub const BINARY: &str = "binary";
22pub const TEXT: &str = "text";
23pub const JSON: &str = "json";
24pub const JSONL: &str = "jsonl";
25pub const JSONL_EVENTS: &str = "jsonl-events";
26
27pub fn register(registry: &mut kute_core::Registry) {
29 registry.register_adapter(BINARY, || Box::new(BinaryAdapter));
30 registry.register_adapter(TEXT, || Box::new(TextAdapter));
31 registry.register_adapter(JSON, || Box::new(JsonAdapter));
32 registry.register_adapter(JSONL, || Box::new(JsonlAdapter));
33 registry.register_adapter(JSONL_EVENTS, || Box::new(JsonlEventsAdapter));
34}
35
36fn bytes_of(input: &CanonicalInput, adapter: &str) -> Result<Vec<u8>> {
37 match &input.payload {
38 Payload::Bytes(b) => Ok(b.clone()),
39 Payload::Symbols(_) => Err(KuteError::InvalidInput(format!("the {adapter} adapter reconstructs byte payloads, not symbols"))),
40 }
41}
42
43fn caps(name: &str, modality: Modality, lossless: bool, notes: &str) -> AdapterCapabilities {
44 AdapterCapabilities { name: name.to_string(), modality, lossless, notes: notes.to_string() }
45}
46
47fn canonical(value: &Value) -> Result<Vec<u8>> {
49 fn sort(value: &Value) -> Value {
50 match value {
51 Value::Object(map) => {
52 let mut keys: Vec<&String> = map.keys().collect();
53 keys.sort();
54 let mut out = serde_json::Map::new();
55 for k in keys {
56 out.insert(k.clone(), sort(&map[k]));
57 }
58 Value::Object(out)
59 }
60 Value::Array(items) => Value::Array(items.iter().map(sort).collect()),
61 other => other.clone(),
62 }
63 }
64 Ok(serde_json::to_vec(&sort(value))?)
65}
66
67fn parse(bytes: &[u8], what: &str) -> Result<Value> {
68 serde_json::from_slice(bytes).map_err(|e| KuteError::InvalidInput(format!("{what}: {e}")))
69}
70
71pub struct BinaryAdapter;
72
73impl ModalityAdapter for BinaryAdapter {
74 fn modality(&self) -> Modality {
75 Modality::Binary
76 }
77 fn ingest(&self, input: &[u8], _: &AdapterConfig) -> Result<CanonicalInput> {
78 Ok(CanonicalInput::bytes(Modality::Binary, input))
79 }
80 fn reconstruct(&self, input: &CanonicalInput) -> Result<Vec<u8>> {
81 bytes_of(input, BINARY)
82 }
83 fn capabilities(&self) -> AdapterCapabilities {
84 caps(BINARY, Modality::Binary, true, "Arbitrary bytes, passed through unchanged.")
85 }
86}
87
88pub struct TextAdapter;
89
90impl ModalityAdapter for TextAdapter {
91 fn modality(&self) -> Modality {
92 Modality::Text
93 }
94 fn ingest(&self, input: &[u8], _: &AdapterConfig) -> Result<CanonicalInput> {
95 std::str::from_utf8(input).map_err(|e| KuteError::InvalidInput(format!("text adapter: not valid UTF-8 ({e}); use the binary adapter")))?;
96 Ok(CanonicalInput::bytes(Modality::Text, input))
97 }
98 fn reconstruct(&self, input: &CanonicalInput) -> Result<Vec<u8>> {
99 bytes_of(input, TEXT)
100 }
101 fn capabilities(&self) -> AdapterCapabilities {
102 caps(TEXT, Modality::Text, true, "Valid UTF-8, passed through unchanged. No normalization.")
103 }
104}
105
106pub struct JsonAdapter;
107
108impl ModalityAdapter for JsonAdapter {
109 fn modality(&self) -> Modality {
110 Modality::Structured
111 }
112 fn ingest(&self, input: &[u8], _: &AdapterConfig) -> Result<CanonicalInput> {
113 Ok(CanonicalInput::bytes(Modality::Structured, canonical(&parse(input, "json adapter")?)?))
114 }
115 fn reconstruct(&self, input: &CanonicalInput) -> Result<Vec<u8>> {
116 bytes_of(input, JSON)
117 }
118 fn capabilities(&self) -> AdapterCapabilities {
119 caps(JSON, Modality::Structured, false, "One JSON document, re-serialized with sorted keys and no extra whitespace. Values survive; original formatting does not.")
120 }
121}
122
123pub struct JsonlAdapter;
124
125impl ModalityAdapter for JsonlAdapter {
126 fn modality(&self) -> Modality {
127 Modality::Structured
128 }
129 fn ingest(&self, input: &[u8], _: &AdapterConfig) -> Result<CanonicalInput> {
130 let mut out = Vec::with_capacity(input.len());
131 for (n, line) in input.split(|&b| b == b'\n').enumerate() {
132 let line = trim(line);
133 if line.is_empty() {
134 continue;
135 }
136 out.extend_from_slice(&canonical(&parse(line, &format!("jsonl adapter, line {}", n + 1))?)?);
137 out.push(b'\n');
138 }
139 Ok(CanonicalInput::bytes(Modality::Structured, out))
140 }
141 fn reconstruct(&self, input: &CanonicalInput) -> Result<Vec<u8>> {
142 bytes_of(input, JSONL)
143 }
144 fn capabilities(&self) -> AdapterCapabilities {
145 caps(JSONL, Modality::Structured, false, "One JSON value per line, each canonicalized; blank lines dropped. Values survive; original formatting does not.")
146 }
147}
148
149#[derive(Default)]
156pub struct JsonlEventsAdapter;
157
158const DEFAULT_FIELD: &str = "event";
159
160impl ModalityAdapter for JsonlEventsAdapter {
161 fn modality(&self) -> Modality {
162 Modality::Events
163 }
164 fn ingest(&self, input: &[u8], config: &AdapterConfig) -> Result<CanonicalInput> {
165 let field = config.get("field").unwrap_or(DEFAULT_FIELD);
166 let mut symbols = Vec::new();
167 for (n, line) in input.split(|&b| b == b'\n').enumerate() {
168 let line = trim(line);
169 if line.is_empty() {
170 continue;
171 }
172 let what = format!("jsonl-events adapter, line {}", n + 1);
173 let value = parse(line, &what)?;
174 let symbol = match value.get(field) {
175 Some(Value::String(s)) if !s.is_empty() => s.clone(),
176 Some(Value::Number(num)) => num.to_string(),
177 Some(Value::Bool(b)) => b.to_string(),
178 Some(_) => return Err(KuteError::InvalidInput(format!("{what}: field {field:?} must be a non-empty string, number or boolean"))),
179 None => return Err(KuteError::InvalidInput(format!("{what}: no field {field:?}"))),
180 };
181 if symbol.len() > kute_types::vocab::MAX_SYMBOL_BYTES {
182 return Err(KuteError::InvalidInput(format!("{what}: symbol longer than 1024 bytes")));
183 }
184 symbols.push(symbol);
185 }
186 Ok(CanonicalInput { modality: Modality::Events, payload: Payload::Symbols(symbols) })
187 }
188 fn reconstruct(&self, input: &CanonicalInput) -> Result<Vec<u8>> {
189 let Payload::Symbols(symbols) = &input.payload else {
190 return Err(KuteError::InvalidInput("the jsonl-events adapter reconstructs symbol payloads".into()));
191 };
192 let mut out = Vec::new();
193 for s in symbols {
194 out.extend_from_slice(&serde_json::to_vec(&serde_json::json!({ DEFAULT_FIELD: s }))?);
195 out.push(b'\n');
196 }
197 Ok(out)
198 }
199 fn capabilities(&self) -> AdapterCapabilities {
200 caps(JSONL_EVENTS, Modality::Events, false, "Extracts one field per JSONL record as an event symbol (option: field, default \"event\"). All other fields are dropped.")
201 }
202}
203
204fn trim(mut line: &[u8]) -> &[u8] {
205 while let [first, rest @ ..] = line {
206 if first.is_ascii_whitespace() { line = rest } else { break }
207 }
208 while let [rest @ .., last] = line {
209 if last.is_ascii_whitespace() { line = rest } else { break }
210 }
211 line
212}
213
214#[cfg(test)]
215mod tests {
216 use super::*;
217
218 #[test]
219 fn pass_through_adapters_are_exact() {
220 let cfg = AdapterConfig::default();
221 let data: Vec<u8> = (0u16..=255).map(|b| b as u8).collect();
222 let c = BinaryAdapter.ingest(&data, &cfg).unwrap();
223 assert_eq!(BinaryAdapter.reconstruct(&c).unwrap(), data);
224 assert!(BinaryAdapter.capabilities().lossless);
225 let text = "naïve café — 日本語\r\n";
226 let c = TextAdapter.ingest(text.as_bytes(), &cfg).unwrap();
227 assert_eq!(TextAdapter.reconstruct(&c).unwrap(), text.as_bytes());
228 assert!(TextAdapter.ingest(&[0xff, 0xfe], &cfg).is_err());
229 }
230
231 #[test]
232 fn json_is_canonical_and_declared_lossy() {
233 let cfg = AdapterConfig::default();
234 let a = JsonAdapter.ingest(br#"{ "b": [1, 2.50, {"z":null,"a":true}], "a": "x" }"#, &cfg).unwrap();
235 let b = JsonAdapter.ingest(br#"{"a":"x","b":[1,2.50,{"a":true,"z":null}]}"#, &cfg).unwrap();
236 assert_eq!(a, b);
237 assert_eq!(JsonAdapter.reconstruct(&a).unwrap(), br#"{"a":"x","b":[1,2.5,{"a":true,"z":null}]}"#);
238 assert!(!JsonAdapter.capabilities().lossless);
239 assert!(JsonAdapter.ingest(b"{not json", &cfg).is_err());
240 }
241
242 #[test]
243 fn jsonl_canonicalizes_each_line() {
244 let cfg = AdapterConfig::default();
245 let c = JsonlAdapter.ingest(b"{\"b\":1, \"a\":2}\r\n\n {\"x\": [ ]}\n", &cfg).unwrap();
246 assert_eq!(JsonlAdapter.reconstruct(&c).unwrap(), b"{\"a\":2,\"b\":1}\n{\"x\":[]}\n");
247 let err = JsonlAdapter.ingest(b"{\"ok\":1}\n{broken\n", &cfg).unwrap_err().to_string();
248 assert!(err.contains("line 2"), "{err}");
249 }
250
251 #[test]
252 fn events_extracts_a_field() {
253 let cfg = AdapterConfig::default().with("field", "tag");
254 let c = JsonlEventsAdapter.ingest(b"{\"tag\":\"MOTOR_START\",\"t\":1}\n{\"tag\":\"MOTOR_TRIP\",\"t\":2}\n", &cfg).unwrap();
255 assert_eq!(c.payload, Payload::Symbols(vec!["MOTOR_START".into(), "MOTOR_TRIP".into()]));
256 assert!(JsonlEventsAdapter.ingest(b"{\"other\":1}\n", &cfg).is_err());
257 assert!(!JsonlEventsAdapter.capabilities().lossless);
258 }
259}