1use std::collections::{BTreeMap, BTreeSet};
2
3use saluki_error::{generic_error, GenericError};
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6
7pub const LOG_ENVELOPE_FIELDS: &[&str] = &[
9 "message",
10 "status",
11 "timestamp",
12 "hostname",
13 "service",
14 "ddsource",
15 "ddtags",
16];
17
18#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
20pub struct LogsRequest {
21 path: String,
22 headers: BTreeMap<String, String>,
23 logs: Vec<Log>,
24}
25
26impl LogsRequest {
27 pub fn new<'a, I>(path: impl Into<String>, headers: I, logs: Vec<Log>) -> Self
31 where
32 I: IntoIterator<Item = (&'a str, &'a str)>,
33 {
34 let mut header_map = BTreeMap::<String, String>::new();
35 for (name, value) in headers {
36 header_map
37 .entry(name.to_ascii_lowercase())
38 .and_modify(|existing| {
39 existing.push_str(", ");
40 existing.push_str(value);
41 })
42 .or_insert_with(|| value.to_string());
43 }
44
45 Self {
46 path: path.into(),
47 headers: header_map,
48 logs,
49 }
50 }
51
52 pub fn path(&self) -> &str {
54 &self.path
55 }
56
57 pub fn headers(&self) -> &BTreeMap<String, String> {
59 &self.headers
60 }
61
62 pub fn header(&self, name: &str) -> Option<&str> {
64 self.headers.get(&name.to_ascii_lowercase()).map(String::as_str)
65 }
66
67 pub fn logs(&self) -> &[Log] {
69 &self.logs
70 }
71}
72
73#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
81pub struct Log {
82 #[serde(
83 default,
84 skip_serializing_if = "Option::is_none",
85 deserialize_with = "deserialize_present"
86 )]
87 message: Option<Value>,
88 #[serde(
89 default,
90 skip_serializing_if = "Option::is_none",
91 deserialize_with = "deserialize_present"
92 )]
93 status: Option<Value>,
94 #[serde(
95 default,
96 skip_serializing_if = "Option::is_none",
97 deserialize_with = "deserialize_present"
98 )]
99 hostname: Option<Value>,
100 #[serde(
101 default,
102 skip_serializing_if = "Option::is_none",
103 deserialize_with = "deserialize_present"
104 )]
105 service: Option<Value>,
106 #[serde(
107 default,
108 skip_serializing_if = "Option::is_none",
109 deserialize_with = "deserialize_present"
110 )]
111 ddsource: Option<Value>,
112 #[serde(
113 default,
114 skip_serializing_if = "Option::is_none",
115 deserialize_with = "deserialize_present"
116 )]
117 timestamp: Option<Value>,
118 ddtags: BTreeSet<String>,
119 envelope_properties: BTreeMap<String, Value>,
120 content_properties: Option<BTreeMap<String, Value>>,
121}
122
123impl Log {
124 pub fn try_from_payload(payload: &[u8]) -> Result<Vec<Self>, GenericError> {
131 let items = serde_json::from_slice::<Vec<Value>>(payload)
132 .map_err(|e| generic_error!("Failed to parse logs payload as a JSON array: {}", e))?;
133
134 items
135 .into_iter()
136 .enumerate()
137 .map(|(idx, item)| match item {
138 Value::Object(object) => Self::try_from_object(object.into_iter().collect()),
139 other => Err(generic_error!(
140 "Log at index {} is not a JSON object: {}",
141 idx,
142 value_kind(&other)
143 )),
144 })
145 .collect()
146 }
147
148 fn try_from_object(mut object: BTreeMap<String, Value>) -> Result<Self, GenericError> {
149 let ddtags = match object.remove("ddtags") {
150 None | Some(Value::Null) => BTreeSet::new(),
151 Some(Value::String(raw)) => split_ddtags(&raw),
152 Some(other) => {
153 return Err(generic_error!(
154 "Log `ddtags` field is not a string: {}",
155 value_kind(&other)
156 ))
157 }
158 };
159
160 let message = object.remove("message");
161 let content_properties = match &message {
162 Some(Value::String(content)) => match serde_json::from_str::<Value>(content) {
163 Ok(Value::Object(content_object)) => Some(content_object.into_iter().collect()),
164 _ => None,
165 },
166 _ => None,
167 };
168
169 Ok(Self {
170 message,
171 status: object.remove("status"),
172 hostname: object.remove("hostname"),
173 service: object.remove("service"),
174 ddsource: object.remove("ddsource"),
175 timestamp: object.remove("timestamp"),
176 ddtags,
177 envelope_properties: object,
178 content_properties,
179 })
180 }
181
182 pub fn message(&self) -> Option<&Value> {
184 self.message.as_ref()
185 }
186
187 pub fn status(&self) -> Option<&Value> {
189 self.status.as_ref()
190 }
191
192 pub fn hostname(&self) -> Option<&Value> {
194 self.hostname.as_ref()
195 }
196
197 pub fn service(&self) -> Option<&Value> {
199 self.service.as_ref()
200 }
201
202 pub fn ddsource(&self) -> Option<&Value> {
204 self.ddsource.as_ref()
205 }
206
207 pub fn timestamp(&self) -> Option<&Value> {
209 self.timestamp.as_ref()
210 }
211
212 pub fn ddtags(&self) -> &BTreeSet<String> {
217 &self.ddtags
218 }
219
220 pub fn envelope_properties(&self) -> &BTreeMap<String, Value> {
222 &self.envelope_properties
223 }
224
225 pub fn content_properties(&self) -> Option<&BTreeMap<String, Value>> {
227 self.content_properties.as_ref()
228 }
229
230 pub fn envelope_field(&self, name: &str) -> Option<&Value> {
234 match name {
235 "message" => self.message(),
236 "status" => self.status(),
237 "hostname" => self.hostname(),
238 "service" => self.service(),
239 "ddsource" => self.ddsource(),
240 "timestamp" => self.timestamp(),
241 _ => None,
242 }
243 }
244
245 pub fn display_message(&self) -> Option<&Value> {
248 match &self.content_properties {
249 Some(content) => content.get("message"),
250 None => self.message.as_ref(),
251 }
252 }
253
254 pub fn semantic_view(&self) -> BTreeMap<String, Value> {
260 let mut view = BTreeMap::new();
261
262 for name in LOG_ENVELOPE_FIELDS {
263 if *name == "message" && self.content_properties.is_some() {
264 continue;
265 }
266 if let Some(value) = self.envelope_field(name) {
267 view.insert(name.to_string(), value.clone());
268 }
269 }
270 if !self.ddtags.is_empty() {
271 let tags = self.ddtags.iter().cloned().map(Value::String).collect();
272 view.insert("ddtags".to_string(), Value::Array(tags));
273 }
274
275 view.extend(self.envelope_properties.iter().map(|(k, v)| (k.clone(), v.clone())));
276 if let Some(content) = &self.content_properties {
277 view.extend(content.iter().map(|(k, v)| (k.clone(), v.clone())));
278 }
279
280 view
281 }
282}
283
284fn deserialize_present<'de, D>(deserializer: D) -> Result<Option<Value>, D::Error>
290where
291 D: serde::Deserializer<'de>,
292{
293 Value::deserialize(deserializer).map(Some)
294}
295
296fn split_ddtags(raw: &str) -> BTreeSet<String> {
297 raw.split(',')
298 .map(str::trim)
299 .filter(|tag| !tag.is_empty())
300 .map(str::to_string)
301 .collect()
302}
303
304fn value_kind(value: &Value) -> &'static str {
305 match value {
306 Value::Null => "null",
307 Value::Bool(_) => "bool",
308 Value::Number(_) => "number",
309 Value::String(_) => "string",
310 Value::Array(_) => "array",
311 Value::Object(_) => "object",
312 }
313}
314
315#[cfg(test)]
316mod tests {
317 use serde_json::json;
318
319 use super::*;
320
321 fn props(value: Value) -> BTreeMap<String, Value> {
322 match value {
323 Value::Object(object) => object.into_iter().collect(),
324 _ => panic!("test properties must be a JSON object"),
325 }
326 }
327
328 #[test]
329 fn agent_payload_keeps_properties_in_content() {
330 let payload = br#"[{
332 "message": "{\"@timestamp\":\"2026-10-29T10:00:00.000Z\",\"hostname\":\"host-a\",\"message\":\"hello\",\"otel.severity_number\":\"9\",\"service\":\"svc\",\"status\":\"info\"}",
333 "status": "info",
334 "timestamp": 1793268000123,
335 "hostname": "host-a",
336 "service": "svc",
337 "ddsource": "otlp_log_ingestion",
338 "ddtags": " env:prod ,,otel_source:datadog_agent,env:prod,"
339 }]"#;
340
341 let logs = Log::try_from_payload(payload).expect("payload should parse");
342 assert_eq!(logs.len(), 1);
343 let log = &logs[0];
344
345 assert_eq!(log.status(), Some(&json!("info")));
346 assert_eq!(log.timestamp(), Some(&json!(1793268000123u64)));
347 assert_eq!(log.hostname(), Some(&json!("host-a")));
348 assert_eq!(log.service(), Some(&json!("svc")));
349 assert_eq!(log.ddsource(), Some(&json!("otlp_log_ingestion")));
350 assert_eq!(
351 log.ddtags().iter().map(String::as_str).collect::<Vec<_>>(),
352 vec!["env:prod", "otel_source:datadog_agent"]
353 );
354 assert!(log.envelope_properties().is_empty());
355 assert_eq!(
356 log.content_properties(),
357 Some(&props(json!({
358 "@timestamp": "2026-10-29T10:00:00.000Z",
359 "hostname": "host-a",
360 "message": "hello",
361 "otel.severity_number": "9",
362 "service": "svc",
363 "status": "info",
364 })))
365 );
366 assert_eq!(log.display_message(), Some(&json!("hello")));
367 }
368
369 #[test]
370 fn legacy_adp_payload_keeps_properties_at_top_level() {
371 let payload = br#"[{
373 "message": "{\"message\":\"hello\",\"service\":\"svc\"}",
374 "status": "Info",
375 "hostname": "host-a",
376 "service": "svc",
377 "ddsource": "otlp_log_ingestion",
378 "ddtags": "otel_source:datadog_agent",
379 "@timestamp": "2026-10-29T10:00:00.000Z",
380 "otel.severity_number": "9",
381 "nested": {"key": [1, 2]}
382 }]"#;
383
384 let logs = Log::try_from_payload(payload).expect("payload should parse");
385 let log = &logs[0];
386
387 assert_eq!(log.timestamp(), None);
388 assert_eq!(
389 log.envelope_properties(),
390 &props(json!({
391 "@timestamp": "2026-10-29T10:00:00.000Z",
392 "otel.severity_number": "9",
393 "nested": {"key": [1, 2]},
394 }))
395 );
396 assert_eq!(
397 log.content_properties(),
398 Some(&props(json!({"message": "hello", "service": "svc"})))
399 );
400 }
401
402 #[test]
403 fn semantic_view_merges_locations_with_content_winning() {
404 let payload = br#"[{
405 "message": "{\"message\":\"hello\",\"shared\":\"from-content\"}",
406 "status": "info",
407 "ddtags": "b:2,a:1",
408 "shared": "from-envelope",
409 "top": 1
410 }]"#;
411
412 let logs = Log::try_from_payload(payload).expect("payload should parse");
413 assert_eq!(
414 logs[0].semantic_view(),
415 props(json!({
416 "ddtags": ["a:1", "b:2"],
417 "message": "hello",
418 "shared": "from-content",
419 "status": "info",
420 "top": 1,
421 }))
422 );
423 }
424
425 #[test]
426 fn non_object_message_is_not_parsed_as_content() {
427 let payload = br#"[
428 {"message": "plain text"},
429 {"message": "[1,2,3]"},
430 {"message": "{not json"},
431 {"message": 42},
432 {}
433 ]"#;
434
435 let logs = Log::try_from_payload(payload).expect("payload should parse");
436 assert_eq!(logs.len(), 5);
437 for log in &logs {
438 assert_eq!(log.content_properties(), None);
439 }
440 assert_eq!(logs[0].display_message(), Some(&json!("plain text")));
441 assert_eq!(logs[1].display_message(), Some(&json!("[1,2,3]")));
442 assert_eq!(logs[3].display_message(), Some(&json!(42)));
443 assert_eq!(logs[4].display_message(), None);
444
445 assert_eq!(logs[0].semantic_view(), props(json!({"message": "plain text"})));
447 }
448
449 #[test]
450 fn duplicate_keys_keep_the_last_value() {
451 let payload = br#"[{"message": "{\"k\":1,\"k\":2}", "status": "warn", "status": "error"}]"#;
452
453 let logs = Log::try_from_payload(payload).expect("payload should parse");
454 assert_eq!(logs[0].status(), Some(&json!("error")));
455 assert_eq!(logs[0].content_properties(), Some(&props(json!({"k": 2}))));
456 }
457
458 #[test]
459 fn invalid_payloads_are_rejected() {
460 let cases: &[(&str, &[u8])] = &[
461 ("invalid JSON", b"[{"),
462 ("not an array", br#"{"message": "x"}"#),
463 ("array of non-objects", br#"["x"]"#),
464 ("non-string ddtags", br#"[{"ddtags": ["a"]}]"#),
465 ];
466
467 for (name, payload) in cases {
468 assert!(Log::try_from_payload(payload).is_err(), "{} should be rejected", name);
469 }
470 }
471
472 #[test]
473 fn empty_ddtags_and_null_ddtags_are_empty_sets() {
474 let payload = br#"[{"ddtags": ""}, {"ddtags": " , ,"}, {"ddtags": null}]"#;
475
476 let logs = Log::try_from_payload(payload).expect("payload should parse");
477 for log in &logs {
478 assert!(log.ddtags().is_empty());
479 }
480 }
481
482 #[test]
483 fn logs_request_normalizes_header_names() {
484 let request = LogsRequest::new(
485 "/api/v2/logs",
486 [("DD-PROTOCOL", "agent-json"), ("X-Multi", "a"), ("x-multi", "b")],
487 Vec::new(),
488 );
489
490 assert_eq!(request.path(), "/api/v2/logs");
491 assert_eq!(request.header("dd-protocol"), Some("agent-json"));
492 assert_eq!(request.header("Dd-Protocol"), Some("agent-json"));
493 assert_eq!(request.header("x-multi"), Some("a, b"));
494 assert!(request.logs().is_empty());
495 }
496
497 #[test]
498 fn logs_request_round_trips_through_json() {
499 let logs =
500 Log::try_from_payload(br#"[{"message": "{\"a\":1}", "ddtags": "x", "extra": true}, {"message": null}]"#)
501 .expect("payload should parse");
502 assert_eq!(logs[1].message(), Some(&Value::Null));
504 assert_eq!(logs[1].status(), None);
505 let request = LogsRequest::new("/v1/input", [("content-encoding", "zstd")], logs);
506
507 let encoded = serde_json::to_string(&request).expect("request should serialize");
508 let decoded: LogsRequest = serde_json::from_str(&encoded).expect("request should deserialize");
509 assert_eq!(decoded, request);
510 assert_eq!(decoded.logs()[1].message(), Some(&Value::Null));
511 assert_eq!(decoded.logs()[1].status(), None);
512 }
513}