1mod parse;
4pub(crate) mod query;
5mod scan;
6
7use rmcp::ErrorData as McpError;
8use rmcp::model::Tool;
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11use serde_json::{Map, Value};
12use tokio_util::sync::CancellationToken;
13
14use super::core::tool;
15use super::mask;
16use super::{Call, ToolError, Toolset, parse_args, text, value_of};
17use crate::scrub;
18use crate::server::AppState;
19use parse::{Entry, Format, rank};
20use query::LogFile;
21use scan::{Backward, WINDOW};
22
23const NOT_INSTALLED: &str = "The log reader functions are not installed in this database.";
24const NOT_AUTHENTIC: &str = "The pgmcp log reader functions in this database were not installed by sql/log_reader.sql (unexpected owner or not SECURITY DEFINER).";
25const NO_PRIVILEGE: &str = "The connected role may not execute pgmcp.read_log_file.";
26const NO_FILES: &str =
27 "No log files found: logging_collector is off or the log directory is empty.";
28const ENABLE_LOGGING: &str = "Set logging_collector = on (restart required) and log_destination = 'jsonlog' (PostgreSQL 15+).";
29const BUDGET_BYTES: u64 = 4 * 1024 * 1024;
31const DEFAULT_LIMIT: i64 = 100;
32const SEVERITY_NAMES: &[&str] = &[
33 "DEBUG", "INFO", "NOTICE", "WARNING", "ERROR", "FATAL", "PANIC",
34];
35const TRUNCATED_MARK: &str = "…[truncated]";
36
37#[derive(Debug, Deserialize, JsonSchema)]
38#[serde(deny_unknown_fields)]
39pub struct ReadArgs {
40 pub database: Option<String>,
41 pub list_files: Option<bool>,
42 pub since: Option<String>,
43 pub until: Option<String>,
44 pub min_severity: Option<String>,
45 pub contains: Option<String>,
46 pub user: Option<String>,
47 pub entry_database: Option<String>,
48 pub pid: Option<i64>,
49 pub file: Option<String>,
50 pub limit: Option<i64>,
51 pub cursor: Option<String>,
52}
53
54#[derive(Debug, Serialize, JsonSchema)]
56#[serde(rename_all = "camelCase")]
57pub struct LogOutput {
58 pub database: String,
59 pub available: bool,
60 #[serde(skip_serializing_if = "Option::is_none")]
61 pub reason: Option<String>,
62 #[serde(skip_serializing_if = "Option::is_none")]
63 pub how_to_enable: Option<String>,
64 #[serde(skip_serializing_if = "Option::is_none")]
65 pub format: Option<&'static str>,
66 #[serde(skip_serializing_if = "Option::is_none")]
67 pub files: Option<Vec<FileInfo>>,
68 #[serde(skip_serializing_if = "Option::is_none")]
69 pub settings: Option<Map<String, Value>>,
70 #[serde(skip_serializing_if = "Option::is_none")]
71 pub entries: Option<Vec<LogEntry>>,
72 #[serde(skip_serializing_if = "Option::is_none")]
73 pub next_cursor: Option<String>,
74 #[serde(skip_serializing_if = "Option::is_none")]
75 pub scanned_to_end: Option<bool>,
76 #[serde(skip_serializing_if = "Option::is_none")]
77 pub scanned_bytes: Option<u64>,
78 #[serde(skip_serializing_if = "Option::is_none")]
79 pub files_read: Option<Vec<String>>,
80 #[serde(skip_serializing_if = "Option::is_none")]
81 pub truncated_messages: Option<u64>,
82}
83
84impl LogOutput {
85 fn bare(database: String, available: bool) -> LogOutput {
87 LogOutput {
88 database,
89 available,
90 reason: None,
91 how_to_enable: None,
92 format: None,
93 files: None,
94 settings: None,
95 entries: None,
96 next_cursor: None,
97 scanned_to_end: None,
98 scanned_bytes: None,
99 files_read: None,
100 truncated_messages: None,
101 }
102 }
103}
104
105#[derive(Debug, Serialize, JsonSchema)]
106#[serde(rename_all = "camelCase")]
107pub struct FileInfo {
108 pub name: String,
109 pub size_bytes: u64,
110 pub modified: String,
111 pub format: &'static str,
112}
113
114#[derive(Debug, Serialize, JsonSchema)]
115#[serde(rename_all = "camelCase")]
116pub struct EntriesResult {
117 pub database: String,
118 pub available: bool,
119 pub format: &'static str,
120 pub entries: Vec<LogEntry>,
121 #[serde(skip_serializing_if = "Option::is_none")]
122 pub next_cursor: Option<String>,
123 pub scanned_to_end: bool,
124 pub scanned_bytes: u64,
125 pub files_read: Vec<String>,
126 pub truncated_messages: u64,
127}
128
129#[derive(Debug, Serialize, JsonSchema)]
130#[serde(rename_all = "camelCase")]
131pub struct LogEntry {
132 pub timestamp: String,
133 pub severity: String,
134 pub message: String,
135 #[serde(skip_serializing_if = "Option::is_none")]
136 pub pid: Option<i64>,
137 #[serde(skip_serializing_if = "Option::is_none")]
138 pub user: Option<String>,
139 #[serde(skip_serializing_if = "Option::is_none")]
140 pub database: Option<String>,
141 #[serde(skip_serializing_if = "Option::is_none")]
142 pub application: Option<String>,
143 #[serde(skip_serializing_if = "Option::is_none")]
144 pub client_addr: Option<String>,
145 #[serde(skip_serializing_if = "Option::is_none")]
146 pub sqlstate: Option<String>,
147 #[serde(skip_serializing_if = "Option::is_none")]
148 pub detail: Option<String>,
149 #[serde(skip_serializing_if = "Option::is_none")]
150 pub hint: Option<String>,
151 #[serde(skip_serializing_if = "Option::is_none")]
152 pub context: Option<String>,
153 #[serde(skip_serializing_if = "Option::is_none")]
154 pub statement: Option<String>,
155 #[serde(skip_serializing_if = "Option::is_none")]
156 pub backend_type: Option<String>,
157 #[serde(skip_serializing_if = "Option::is_none")]
158 pub query_id: Option<i64>,
159 #[serde(skip_serializing_if = "Option::is_none")]
160 pub session_id: Option<String>,
161 pub file: String,
162}
163
164pub fn catalog() -> Vec<(Toolset, Tool)> {
166 vec![(
167 Toolset::Logs,
168 tool::<ReadArgs, LogOutput>(
169 "read_server_log",
170 text::READ_SERVER_LOG_TITLE,
171 text::READ_SERVER_LOG,
172 &[
173 ("database", text::DATABASE_PARAM),
174 ("list_files", text::READ_SERVER_LOG_LIST_FILES_PARAM),
175 ("since", text::READ_SERVER_LOG_SINCE_PARAM),
176 ("until", text::READ_SERVER_LOG_UNTIL_PARAM),
177 ("min_severity", text::READ_SERVER_LOG_MIN_SEVERITY_PARAM),
178 ("contains", text::READ_SERVER_LOG_CONTAINS_PARAM),
179 ("user", text::READ_SERVER_LOG_USER_PARAM),
180 ("entry_database", text::READ_SERVER_LOG_ENTRY_DATABASE_PARAM),
181 ("pid", text::READ_SERVER_LOG_PID_PARAM),
182 ("file", text::READ_SERVER_LOG_FILE_PARAM),
183 ("limit", text::LIMIT_PARAM),
184 ("cursor", text::CURSOR_PARAM),
185 ],
186 ),
187 )]
188}
189
190pub async fn dispatch(
192 state: &AppState,
193 name: &str,
194 args: Value,
195 ct: &CancellationToken,
196) -> Option<Result<Call, McpError>> {
197 if name != "read_server_log" {
198 return None;
199 }
200 let args: ReadArgs = match parse_args(args) {
201 Ok(args) => args,
202 Err(error) => return Some(Err(error)),
203 };
204 Some(Ok(read_server_log(state, args, ct).await))
205}
206
207async fn read_server_log(state: &AppState, args: ReadArgs, ct: &CancellationToken) -> Call {
208 let result = read(state, &args, ct).await;
209 let database = match &result {
210 Ok(outcome) => Some(outcome.database.clone()),
211 Err(_) => state.resolve_name(args.database.as_deref()),
212 };
213 let rows = result.as_ref().ok().and_then(|outcome| outcome.entries);
214 Call {
215 result: result.and_then(|outcome| value_of(&outcome.output)),
216 database,
217 rows,
218 sql: None,
219 }
220}
221
222struct Outcome {
223 database: String,
224 output: LogOutput,
225 entries: Option<usize>,
227}
228
229struct Plan {
231 limit: usize,
232 min_rank: Option<u8>,
233 contains: Option<String>,
234 user: Option<String>,
235 entry_database: Option<String>,
236 pid: Option<i64>,
237 since: Option<String>,
238 until: Option<String>,
239 files: Vec<LogFile>,
241 first: usize,
243 offset: Option<u64>,
245 format: Format,
246}
247
248async fn read(
249 state: &AppState,
250 args: &ReadArgs,
251 ct: &CancellationToken,
252) -> Result<Outcome, ToolError> {
253 let db = args.database.as_deref();
254 let database = state.pool(db)?.0.name.clone();
255 let setup = query::setup(state, db, ct).await?;
256 if let Some(reason) = setup_reason(&setup) {
257 return Ok(unavailable(database, reason, grant_text(&setup.role)));
258 }
259 let listing = query::files(state, db, ct).await?;
260 if let Some(reason) = listing_reason(listing.len()) {
261 return Ok(unavailable(database, reason, ENABLE_LOGGING.to_owned()));
262 }
263 if args.list_files.unwrap_or(false) {
264 let settings = query::settings(state, db, ct).await?;
265 let files = listing
266 .iter()
267 .map(|f| FileInfo {
268 name: f.name.clone(),
269 size_bytes: f.size,
270 modified: f.modified.clone(),
271 format: f.format.name(),
272 })
273 .collect();
274 return Ok(Outcome {
275 database: database.clone(),
276 output: LogOutput {
277 files: Some(files),
278 settings: Some(settings),
279 ..LogOutput::bare(database, true)
280 },
281 entries: None,
282 });
283 }
284 let plan = plan(state, args, &listing, db, ct).await?;
285 let scanned = scan_entries(state, db, &plan, ct).await?;
286 let count = scanned.entries.len();
287 Ok(Outcome {
288 database: database.clone(),
289 output: scanned.into_result(&database, plan.format),
290 entries: Some(count),
291 })
292}
293
294fn setup_reason(setup: &query::Setup) -> Option<&'static str> {
296 if !setup.installed {
297 Some(NOT_INSTALLED)
298 } else if !setup.authentic {
299 Some(NOT_AUTHENTIC)
300 } else if !setup.allowed {
301 Some(NO_PRIVILEGE)
302 } else {
303 None
304 }
305}
306
307fn listing_reason(files: usize) -> Option<&'static str> {
309 if files == 0 { Some(NO_FILES) } else { None }
310}
311
312fn grant_text(role: &str) -> String {
314 format!(
315 "Run sql/log_reader.sql as a superuser, then: GRANT USAGE ON SCHEMA pgmcp TO {role}; \
316 GRANT EXECUTE ON FUNCTION pgmcp.read_log_file(text, bigint, integer), pgmcp.list_log_files() TO {role};"
317 )
318}
319
320fn unavailable(database: String, reason: &str, how: String) -> Outcome {
321 let output = LogOutput {
322 reason: Some(reason.to_owned()),
323 how_to_enable: Some(how),
324 ..LogOutput::bare(database.clone(), false)
325 };
326 Outcome {
327 database,
328 output,
329 entries: None,
330 }
331}
332
333async fn plan(
335 state: &AppState,
336 args: &ReadArgs,
337 listing: &[LogFile],
338 db: Option<&str>,
339 ct: &CancellationToken,
340) -> Result<Plan, ToolError> {
341 let limit = args.limit.unwrap_or(DEFAULT_LIMIT);
342 if !(1..=500).contains(&limit) {
343 return Err(ToolError::Rejected(
344 "limit must be between 1 and 500.".to_owned(),
345 ));
346 }
347 let min_rank = match args.min_severity.as_deref() {
348 None => None,
349 Some(name) => {
350 let upper = name.to_ascii_uppercase();
351 match rank(&upper) {
352 Some(value) if SEVERITY_NAMES.contains(&upper.as_str()) => Some(value),
353 _ => {
354 return Err(ToolError::Rejected(format!(
355 "min_severity must be one of {}.",
356 SEVERITY_NAMES.join(", ")
357 )));
358 }
359 }
360 }
361 };
362 let (since, until) =
363 query::bounds(state, db, args.since.as_deref(), args.until.as_deref(), ct).await?;
364 let group = file_group(listing, args.file.as_deref())?;
365 let format = group.first().map_or(Format::Stderr, |file| file.format);
366 let (first, offset) = match args.cursor.as_deref() {
367 None => (0, None),
368 Some(text) => {
369 let (index, offset) = decode_cursor(text, listing, &group, args.file.as_deref())?;
370 (index, Some(offset))
371 }
372 };
373 Ok(Plan {
374 limit: usize::try_from(limit).unwrap_or(DEFAULT_LIMIT as usize),
375 min_rank,
376 contains: args.contains.as_ref().map(|s| s.to_lowercase()),
377 user: args.user.clone(),
378 entry_database: args.entry_database.clone(),
379 pid: args.pid,
380 since,
381 until,
382 files: group,
383 first,
384 offset,
385 format,
386 })
387}
388
389fn file_group(listing: &[LogFile], file: Option<&str>) -> Result<Vec<LogFile>, ToolError> {
391 if let Some(name) = file {
392 return match listing.iter().find(|f| f.name == name) {
393 Some(found) => Ok(vec![found.clone()]),
394 None => Err(ToolError::Rejected(format!("Unknown log file \"{name}\"."))),
395 };
396 }
397 for format in [Format::Jsonlog, Format::Csvlog, Format::Stderr] {
398 let group: Vec<LogFile> = listing
399 .iter()
400 .filter(|f| f.format == format)
401 .cloned()
402 .collect();
403 if !group.is_empty() {
404 return Ok(group);
405 }
406 }
407 Ok(listing.to_vec())
408}
409
410fn decode_cursor(
412 text: &str,
413 listing: &[LogFile],
414 group: &[LogFile],
415 file: Option<&str>,
416) -> Result<(usize, u64), ToolError> {
417 let invalid = || ToolError::Rejected("Invalid cursor.".to_owned());
418 let parts: Vec<&str> = text.split('|').collect();
419 let [name, offset, format] = parts.as_slice() else {
420 return Err(invalid());
421 };
422 let offset: u64 = offset.parse().map_err(|_| invalid())?;
423 let known = listing
424 .iter()
425 .find(|f| f.name == *name)
426 .ok_or_else(invalid)?;
427 if offset > known.size || *format != known.format.name() {
428 return Err(invalid());
429 }
430 if file.is_some_and(|wanted| wanted != *name) {
431 return Err(invalid());
432 }
433 let index = group
434 .iter()
435 .position(|f| f.name == *name)
436 .ok_or_else(invalid)?;
437 Ok((index, offset))
438}
439
440fn encode_cursor(file: &str, offset: u64, format: Format) -> String {
441 format!("{file}|{offset}|{}", format.name())
442}
443
444#[derive(Default)]
446struct Scanned {
447 entries: Vec<LogEntry>,
448 scanned_bytes: u64,
449 files_read: Vec<String>,
450 truncated: u64,
451 next: Option<(String, u64)>,
453 scanned_to_end: bool,
454 response_bytes: usize,
455}
456
457impl Scanned {
458 fn into_result(self, database: &str, format: Format) -> LogOutput {
459 let next_cursor = self
460 .next
461 .as_ref()
462 .map(|(file, offset)| encode_cursor(file, *offset, format));
463 LogOutput {
464 format: Some(format.name()),
465 entries: Some(self.entries),
466 next_cursor,
467 scanned_to_end: Some(self.scanned_to_end),
468 scanned_bytes: Some(self.scanned_bytes),
469 files_read: Some(self.files_read),
470 truncated_messages: Some(self.truncated),
471 ..LogOutput::bare(database.to_owned(), true)
472 }
473 }
474}
475
476async fn scan_entries(
479 state: &AppState,
480 db: Option<&str>,
481 plan: &Plan,
482 ct: &CancellationToken,
483) -> Result<Scanned, ToolError> {
484 let limits = &state.config.limits;
485 let mut scanned = Scanned::default();
486 let mut last: Option<(String, u64)> = None;
488 for (index, file) in plan.files.iter().enumerate().skip(plan.first) {
489 let end = match plan.offset {
490 Some(offset) if index == plan.first => offset,
491 _ => file.size,
492 };
493 let mut backward = Backward::new(file.format, end, WINDOW);
494 while let Some(read) = backward.request() {
495 if scanned.scanned_bytes >= BUDGET_BYTES {
496 scanned.next = Some((file.name.clone(), backward.end()));
497 return Ok(scanned);
498 }
499 if scanned.files_read.last() != Some(&file.name) {
500 scanned.files_read.push(file.name.clone());
501 }
502 let bytes = query::read_chunk(state, db, &file.name, read.offset, read.len, ct).await?;
503 scanned.scanned_bytes += bytes.len() as u64;
504 let Some(records) = backward.feed(read.offset, bytes) else {
505 continue;
506 };
507 for (at, entry) in records {
508 let stamped = !entry.timestamp.is_empty();
509 if let Some(since) = &plan.since
510 && stamped
511 && stamp(&entry.timestamp) < since.as_str()
512 {
513 scanned.scanned_to_end = true;
514 return Ok(scanned);
515 }
516 if let Some(until) = &plan.until
517 && stamped
518 && stamp(&entry.timestamp) >= until.as_str()
519 {
520 continue;
521 }
522 let entry = mask_entry(entry);
523 if !matches(plan, &entry) {
524 continue;
525 }
526 let output = to_output(
527 entry,
528 &file.name,
529 limits.max_value_bytes,
530 &mut scanned.truncated,
531 );
532 let size = serde_json::to_string(&output)
533 .map_err(|e| ToolError::Internal(e.to_string()))?
534 .len();
535 if !scanned.entries.is_empty()
536 && scanned.response_bytes + size > limits.max_response_bytes
537 {
538 scanned.next = last;
539 return Ok(scanned);
540 }
541 scanned.response_bytes += size;
542 scanned.entries.push(output);
543 last = Some((file.name.clone(), at));
544 if scanned.entries.len() >= plan.limit {
545 scanned.next = last;
546 return Ok(scanned);
547 }
548 }
549 }
550 }
551 scanned.scanned_to_end = true;
552 Ok(scanned)
553}
554
555fn stamp(timestamp: &str) -> &str {
557 timestamp.get(..23).unwrap_or(timestamp)
558}
559
560fn mask_entry(mut entry: Entry) -> Entry {
563 entry.message = clean(&entry.message);
564 entry.detail = entry.detail.as_deref().map(clean);
565 entry.statement = entry.statement.as_deref().map(clean);
566 entry.context = entry.context.as_deref().map(clean);
567 entry
568}
569
570fn clean(text: &str) -> String {
571 let (scrubbed, _) = scrub::scrub_counting(text);
572 mask::mask(&scrubbed)
573}
574
575fn matches(plan: &Plan, entry: &Entry) -> bool {
577 if let Some(min) = plan.min_rank {
578 match rank(&entry.severity) {
579 Some(value) if value >= min => {}
580 _ => return false,
581 }
582 }
583 if let Some(needle) = &plan.contains {
584 let found = [
585 Some(entry.message.as_str()),
586 entry.detail.as_deref(),
587 entry.statement.as_deref(),
588 ]
589 .into_iter()
590 .flatten()
591 .any(|text| text.to_lowercase().contains(needle.as_str()));
592 if !found {
593 return false;
594 }
595 }
596 if let Some(user) = &plan.user
597 && entry.user.as_deref() != Some(user.as_str())
598 {
599 return false;
600 }
601 if let Some(database) = &plan.entry_database
602 && entry.database.as_deref() != Some(database.as_str())
603 {
604 return false;
605 }
606 if let Some(pid) = plan.pid
607 && entry.pid != Some(pid)
608 {
609 return false;
610 }
611 true
612}
613
614fn cut(text: String, max: usize, truncated: &mut u64) -> String {
616 if text.len() <= max {
617 return text;
618 }
619 let mut end = crate::scrub::cut_index(text.as_bytes(), max);
620 while !text.is_char_boundary(end) {
621 end -= 1;
622 }
623 *truncated += 1;
624 format!("{}{TRUNCATED_MARK}", &text[..end])
625}
626
627fn to_output(entry: Entry, file: &str, max_value_bytes: usize, truncated: &mut u64) -> LogEntry {
628 let message = cut(entry.message, max_value_bytes, truncated);
629 let detail = entry
630 .detail
631 .map(|text| cut(text, max_value_bytes, truncated));
632 let context = entry
633 .context
634 .map(|text| cut(text, max_value_bytes, truncated));
635 let statement = entry
636 .statement
637 .map(|text| cut(text, max_value_bytes, truncated));
638 LogEntry {
639 timestamp: entry.timestamp,
640 severity: entry.severity,
641 message,
642 pid: entry.pid,
643 user: entry.user,
644 database: entry.database,
645 application: entry.application,
646 client_addr: entry.client_addr,
647 sqlstate: entry.sqlstate,
648 detail,
649 hint: entry.hint,
650 context,
651 statement,
652 backend_type: entry.backend_type,
653 query_id: entry.query_id,
654 session_id: entry.session_id,
655 file: file.to_owned(),
656 }
657}
658
659#[cfg(test)]
660mod tests {
661 use super::query::{LogFile, Setup, decode_bytea};
662 use super::*;
663
664 fn setup(installed: bool, authentic: bool, allowed: bool) -> Setup {
665 Setup {
666 installed,
667 authentic,
668 allowed,
669 role: "mcp_min".to_owned(),
670 }
671 }
672
673 #[test]
674 fn setup_reason_checks_installed_then_authentic_then_allowed() {
675 assert_eq!(
676 setup_reason(&setup(false, false, false)),
677 Some(NOT_INSTALLED)
678 );
679 assert_eq!(
680 setup_reason(&setup(true, false, false)),
681 Some(NOT_AUTHENTIC)
682 );
683 assert_eq!(setup_reason(&setup(true, true, false)), Some(NO_PRIVILEGE));
684 assert_eq!(setup_reason(&setup(true, true, true)), None);
685 }
686
687 #[test]
688 fn empty_log_directory_is_no_files_and_any_file_is_readable() {
689 assert_eq!(listing_reason(0), Some(NO_FILES));
690 assert_eq!(listing_reason(1), None);
691 assert_eq!(listing_reason(3), None);
692 }
693
694 fn listed(name: &str, size: u64, format: Format) -> LogFile {
695 LogFile {
696 name: name.to_owned(),
697 size,
698 modified: String::new(),
699 format,
700 }
701 }
702
703 fn cursor_error(text: &str, file: Option<&str>) -> String {
704 let listing = vec![
705 listed("a.json", 100, Format::Jsonlog),
706 listed("b.csv", 50, Format::Csvlog),
707 ];
708 let group = listing[..1].to_vec();
709 match decode_cursor(text, &listing, &group, file) {
710 Ok(found) => format!("ok {found:?}"),
711 Err(error) => error.message(),
712 }
713 }
714
715 #[test]
716 fn cut_leaves_short_text_and_counts_nothing() {
717 let mut truncated = 0;
718 assert_eq!(cut("abc".to_owned(), 5, &mut truncated), "abc");
719 assert_eq!(truncated, 0);
720 }
721
722 #[test]
723 fn cut_stops_on_a_character_boundary() {
724 let mut truncated = 0;
725 assert_eq!(cut("héllo".to_owned(), 2, &mut truncated), "h…[truncated]");
726 assert_eq!(cut("héllo".to_owned(), 3, &mut truncated), "hé…[truncated]");
727 assert_eq!(truncated, 2);
728 }
729
730 #[test]
731 fn cursor_must_name_a_listed_file_in_range_and_format() {
732 assert_eq!(cursor_error("a.json|10|jsonlog", None), "ok (0, 10)");
733 assert_eq!(cursor_error("a.json|100|jsonlog", None), "ok (0, 100)");
734 for bad in [
735 "a.json|101|jsonlog",
736 "a.json|10|csvlog",
737 "a.json|10",
738 "zz.json|1|jsonlog",
739 "a.json|x|jsonlog",
740 "garbage",
741 ] {
742 assert_eq!(cursor_error(bad, None), "Invalid cursor.", "{bad}");
743 }
744 assert_eq!(
745 cursor_error("a.json|10|jsonlog", Some("b.csv")),
746 "Invalid cursor."
747 );
748 }
749
750 #[test]
751 fn file_argument_selects_one_file_or_errors() {
752 let listing = vec![listed("a.json", 1, Format::Jsonlog)];
753 assert_eq!(
754 file_group(&listing, Some("a.json")).map(|g| g.len()).ok(),
755 Some(1)
756 );
757 let error = file_group(&listing, Some("x.log"))
758 .err()
759 .map(|e| e.message());
760 assert_eq!(error.as_deref(), Some("Unknown log file \"x.log\"."));
761 }
762
763 #[test]
764 fn bytea_hex_decodes_and_rejects_bad_input() {
765 assert_eq!(decode_bytea(b"\\x48690a").ok(), Some(b"Hi\n".to_vec()));
766 assert_eq!(decode_bytea(b"\\x").ok(), Some(Vec::new()));
767 assert!(decode_bytea(b"48").is_err());
768 assert!(decode_bytea(b"\\x4").is_err());
769 assert!(decode_bytea(b"\\xzz").is_err());
770 }
771}