systemd-journal-sdk-engine 0.7.0

Async query engine components for the pure Rust systemd journal SDK
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
//! Log querying from indexed journal files.
//!
//! This module provides the `LogQuery` builder for efficiently querying and
//! merging log entries from multiple indexed journal files, as well as
//! functions for extracting raw field data from journal entries.

use crate::error::Result;
use journal_core::file::{CurrentRowView, JournalFile, Mmap};
use journal_index::{
    Anchor, Direction, FieldName, FieldValuePair, FileIndex, Filter, LogEntryId, LogQueryParams,
    LogQueryParamsBuilder, Microseconds,
};
use journal_registry::File;
use std::collections::{HashMap, HashSet};
use std::num::NonZeroU64;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio_util::sync::CancellationToken;
use tracing::warn;

/// Pagination state for multi-file log queries.
///
/// This tracks the position in each file where we stopped reading,
/// allowing queries to resume efficiently without re-scanning entries.
///
/// The state is tied to a specific query configuration (filter, anchor, direction, etc).
/// Changing the query parameters while using the same pagination state will produce
/// undefined results.
#[derive(Debug, Clone, Default)]
pub struct PaginationState {
    /// Maps each file to the last position we read from it
    pub file_positions: HashMap<File, usize>,
}

/// Builder for configuring and executing log queries from indexed journal files.
///
/// This builder allows you to specify:
/// - Direction (forward/backward in time)
/// - Anchor timestamp (starting point)
/// - Limit (maximum entries to retrieve)
/// - Source timestamp field (which field to use for timestamps)
/// - Filter (to match specific entries)
///
/// # Example
///
/// ```ignore
/// use journal_index::{Anchor, Direction};
/// use journal_function::logs::LogQuery;
///
/// let entries = LogQuery::new(&file_indexes, Anchor::Head, Direction::Forward)
///     .with_limit(100)
///     .execute();
/// ```
pub struct LogQuery<'a> {
    file_indexes: &'a [FileIndex],
    builder: LogQueryParamsBuilder,
    cancellation: Option<CancellationToken>,
    progress: Option<Arc<AtomicUsize>>,
    output_fields: Option<HashSet<String>>,
}

impl<'a> LogQuery<'a> {
    /// Create a new log query builder with required parameters.
    ///
    /// # Arguments
    ///
    /// * `file_indexes` - Journal file indexes to query
    /// * `anchor` - Starting point for the query (Head, Tail, or specific timestamp)
    /// * `direction` - Direction to iterate (Forward or Backward)
    ///
    /// # Optional Configuration
    ///
    /// Use builder methods to set optional parameters:
    /// - Limit: None (unlimited)
    /// - Source timestamp field: _SOURCE_REALTIME_TIMESTAMP
    /// - Filter: None
    pub fn new(file_indexes: &'a [FileIndex], anchor: Anchor, direction: Direction) -> Self {
        Self {
            file_indexes,
            builder: LogQueryParamsBuilder::new(anchor, direction).with_source_timestamp_field(
                Some(FieldName::new_unchecked("_SOURCE_REALTIME_TIMESTAMP")),
            ),
            cancellation: None,
            progress: None,
            output_fields: None,
        }
    }

    /// Set the maximum number of log entries to retrieve (optional).
    ///
    /// If not set (None), all matching entries will be retrieved.
    pub fn with_limit(mut self, limit: usize) -> Self {
        self.builder = self.builder.with_limit(limit);
        self
    }

    /// Set the source timestamp field to use for entry timestamps (optional).
    ///
    /// Pass `None` to use the entry's realtime timestamp from the journal header.
    /// Pass `Some(field_name)` to use a custom timestamp field from the entry data.
    pub fn with_source_timestamp_field(mut self, field: Option<FieldName>) -> Self {
        self.builder = self.builder.with_source_timestamp_field(field);
        self
    }

    /// Set a filter to apply to log entries (optional).
    ///
    /// Only entries matching the filter will be included in the results.
    pub fn with_filter(mut self, filter: Filter) -> Self {
        self.builder = self.builder.with_filter(filter);
        self
    }

    /// Set the lower time boundary (inclusive) in microseconds (optional).
    ///
    /// Only entries with timestamp >= after_usec will be included.
    /// This enforces a hard boundary regardless of anchor or limit.
    pub fn with_after_usec(mut self, after: u64) -> Self {
        self.builder = self.builder.with_after(Microseconds(after));
        self
    }

    /// Set the upper time boundary (exclusive) in microseconds (optional).
    ///
    /// Only entries with timestamp < before_usec will be included.
    /// This enforces a hard boundary regardless of anchor or limit.
    pub fn with_before_usec(mut self, before: u64) -> Self {
        self.builder = self.builder.with_before(Microseconds(before));
        self
    }

    /// Set a regex pattern for full-text search (optional).
    ///
    /// Only entries where at least one data object (in "FIELD=value" format)
    /// matches the regex will be included in the results.
    ///
    /// The pattern will be compiled when the query is executed. Invalid patterns
    /// will cause execute() to return an error.
    pub fn with_regex(mut self, pattern: impl Into<String>) -> Self {
        self.builder = self.builder.with_regex(pattern);
        self
    }

    /// Set a cancellation token for the query (optional).
    ///
    /// When set, the query will check the token before processing each file
    /// and return early with partial results if cancelled.
    pub fn with_cancellation(mut self, token: CancellationToken) -> Self {
        self.cancellation = Some(token);
        self
    }

    /// Set a progress counter for the query (optional).
    ///
    /// When set, the counter is incremented (via `fetch_add`) after each file
    /// is processed in `retrieve_log_entries`.
    pub fn with_progress(mut self, counter: Arc<AtomicUsize>) -> Self {
        self.progress = Some(counter);
        self
    }

    /// Limit returned field-value pairs to the requested on-disk field names.
    pub fn with_output_fields<I, S>(mut self, fields: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.output_fields = Some(fields.into_iter().map(Into::into).collect());
        self
    }

    /// Execute the query and return log entries.
    ///
    /// This consumes the builder and returns a vector of log entries sorted by timestamp
    /// according to the configured direction.
    ///
    /// # Errors
    ///
    /// Returns an error if anchor or direction were not set, or if time boundaries are invalid.
    pub fn execute(self) -> Result<Vec<LogEntryData>> {
        let params = self.builder.build()?;
        let output_fields = self.output_fields;
        let (log_entry_ids, _state) = retrieve_log_entries(
            self.file_indexes.to_vec(),
            params,
            None,
            self.cancellation.as_ref(),
            self.progress.as_ref(),
        );

        extract_entry_data(&log_entry_ids, output_fields.as_ref())
    }

    /// Execute the query with pagination support.
    ///
    /// This consumes the builder and returns a page of log entries along with
    /// pagination state that can be used to retrieve the next page.
    ///
    /// # Arguments
    ///
    /// * `state` - Optional pagination state from a previous query. Pass `None` for the first page.
    ///
    /// # Returns
    ///
    /// Returns a tuple of (log entry data, new pagination state). If the pagination state
    /// is empty (no file positions tracked), there are no more results.
    ///
    /// # Errors
    ///
    /// Returns an error if anchor or direction were not set, or if time boundaries are invalid.
    pub fn execute_page(
        self,
        state: Option<&PaginationState>,
    ) -> Result<(Vec<LogEntryData>, PaginationState)> {
        let params = self.builder.build()?;
        let output_fields = self.output_fields;
        let (log_entry_ids, new_state) = retrieve_log_entries(
            self.file_indexes.to_vec(),
            params,
            state,
            self.cancellation.as_ref(),
            self.progress.as_ref(),
        );

        let data = extract_entry_data(&log_entry_ids, output_fields.as_ref())?;
        Ok((data, new_state))
    }
}

/// Retrieve and merge log entries from multiple indexed journal files.
///
/// This function efficiently retrieves log entries from multiple journal files,
/// merging them in timestamp order while respecting the limit constraint.
///
/// # Arguments
///
/// * `file_indexes` - Vector of indexed journal files to retrieve from
/// * `params` - Query parameters (anchor, direction, limit, filter, boundaries)
/// * `state` - Optional pagination state to resume from previous query
///
/// # Returns
///
/// A tuple of (log entries, new pagination state). The entries are sorted by timestamp
/// and limited to `params.limit`. The new state can be used to resume the query.
fn retrieve_log_entries(
    file_indexes: Vec<FileIndex>,
    params: LogQueryParams,
    state: Option<&PaginationState>,
    cancellation: Option<&CancellationToken>,
    progress: Option<&Arc<AtomicUsize>>,
) -> (Vec<LogEntryId>, PaginationState) {
    // Handle edge cases
    if params.limit() == Some(0) || file_indexes.is_empty() {
        return (Vec::new(), PaginationState::default());
    }

    let anchor_usec = multi_file_anchor_usec(&file_indexes, params.anchor());
    let mut relevant_indexes =
        relevant_file_indexes(&file_indexes, params.direction(), anchor_usec);

    if let Some(counter) = progress {
        let filtered = file_indexes.len() - relevant_indexes.len();
        counter.fetch_add(filtered, Ordering::Relaxed);
    }

    if relevant_indexes.is_empty() {
        return (Vec::new(), PaginationState::default());
    }

    sort_relevant_indexes(&mut relevant_indexes, params.direction());

    let (limit, mut collected_entries) = collection_limit_and_buffer(params.limit());
    let mut new_state = state.cloned().unwrap_or_default();

    for file_index in relevant_indexes {
        if query_cancelled(cancellation, &new_state) {
            break;
        }

        mark_file_processed(progress);

        if should_prune_file(file_index, &collected_entries, limit, params.direction()) {
            break;
        }

        if let Some(new_entries) = query_file_entries(file_index, &params, state) {
            collected_entries =
                merge_log_entries(collected_entries, new_entries, limit, params.direction());
        }
    }

    update_pagination_state(&mut new_state, &collected_entries, params.direction());

    (collected_entries, new_state)
}

fn multi_file_anchor_usec(file_indexes: &[FileIndex], anchor: Anchor) -> u64 {
    match anchor {
        Anchor::Timestamp(ts) => ts.get(),
        Anchor::Head => file_indexes
            .iter()
            .map(|fi| fi.start_time().to_microseconds().get())
            .min()
            .unwrap_or(0),
        Anchor::Tail => file_indexes
            .iter()
            .map(|fi| fi.end_time().to_microseconds().get())
            .max()
            .unwrap_or(0),
    }
}

fn relevant_file_indexes(
    file_indexes: &[FileIndex],
    direction: Direction,
    anchor_usec: u64,
) -> Vec<&FileIndex> {
    file_indexes
        .iter()
        .filter(|fi| file_can_contain_anchor(fi, direction, anchor_usec))
        .collect()
}

fn file_can_contain_anchor(file_index: &FileIndex, direction: Direction, anchor_usec: u64) -> bool {
    match direction {
        Direction::Forward => file_index.end_time().to_microseconds().get() >= anchor_usec,
        Direction::Backward => file_index.start_time().to_microseconds().get() <= anchor_usec,
    }
}

fn sort_relevant_indexes(file_indexes: &mut [&FileIndex], direction: Direction) {
    match direction {
        Direction::Forward => file_indexes.sort_by_key(|fi| fi.start_time()),
        Direction::Backward => file_indexes.sort_by_key(|fi| std::cmp::Reverse(fi.end_time())),
    }
}

fn collection_limit_and_buffer(limit: Option<usize>) -> (usize, Vec<LogEntryId>) {
    match limit {
        Some(limit) => (limit, Vec::with_capacity(limit)),
        None => (usize::MAX, Vec::with_capacity(200)),
    }
}

fn query_cancelled(cancellation: Option<&CancellationToken>, state: &PaginationState) -> bool {
    let Some(token) = cancellation else {
        return false;
    };
    if !token.is_cancelled() {
        return false;
    }
    warn!(
        "log query cancelled after processing {} files, returning partial results",
        state.file_positions.len()
    );
    true
}

fn mark_file_processed(progress: Option<&Arc<AtomicUsize>>) {
    if let Some(counter) = progress {
        counter.fetch_add(1, Ordering::Relaxed);
    }
}

fn should_prune_file(
    file_index: &FileIndex,
    collected_entries: &[LogEntryId],
    limit: usize,
    direction: Direction,
) -> bool {
    collected_entries.len() >= limit
        && can_prune_file(file_index, collected_entries, direction).unwrap_or(false)
}

fn query_file_entries(
    file_index: &FileIndex,
    params: &LogQueryParams,
    state: Option<&PaginationState>,
) -> Option<Vec<LogEntryId>> {
    let file = file_index.file();
    let file_params = params_for_file(file_index, params, state);
    match file_index.find_log_entries(file, &file_params) {
        Ok(entries) if entries.is_empty() => None,
        Ok(entries) => Some(entries),
        Err(e) => {
            warn!(file = file.path(), "failed to retrieve log entries: {e}");
            None
        }
    }
}

fn params_for_file(
    file_index: &FileIndex,
    params: &LogQueryParams,
    state: Option<&PaginationState>,
) -> LogQueryParams {
    let Some(pos) = state.and_then(|s| s.file_positions.get(file_index.file()).copied()) else {
        return params.clone();
    };

    let mut builder = LogQueryParamsBuilder::new(params.anchor(), params.direction());
    if let Some(limit) = params.limit() {
        builder = builder.with_limit(limit);
    }
    if let Some(field) = params.source_timestamp_field() {
        builder = builder.with_source_timestamp_field(Some(field.clone()));
    }
    if let Some(filter) = params.filter() {
        builder = builder.with_filter(filter.clone());
    }
    if let Some(after) = params.after() {
        builder = builder.with_after(after);
    }
    if let Some(before) = params.before() {
        builder = builder.with_before(before);
    }
    if let Some(regex) = params.regex() {
        builder = builder.with_regex(regex.as_str());
    }

    builder
        .with_resume_position(pos)
        .build()
        .expect("resume params copied from validated query params")
}

fn update_pagination_state(
    state: &mut PaginationState,
    entries: &[LogEntryId],
    direction: Direction,
) {
    for entry in entries {
        state
            .file_positions
            .entry(entry.file.clone())
            .and_modify(|pos| {
                *pos = next_resume_position(*pos, entry.position, direction);
            })
            .or_insert(entry.position);
    }
}

fn next_resume_position(current: usize, candidate: usize, direction: Direction) -> usize {
    match direction {
        Direction::Forward => current.max(candidate),
        Direction::Backward => current.min(candidate),
    }
}

/// Check if we can prune (skip) a file based on its time range and current results.
///
/// Returns Some(true) if we should break early, Some(false) if we should continue,
/// or None if we can't determine (shouldn't happen with a full result set).
fn can_prune_file(
    file_index: &FileIndex,
    result: &[LogEntryId],
    direction: Direction,
) -> Option<bool> {
    match direction {
        Direction::Forward => {
            // For forward: if file starts after our latest entry, skip all remaining files
            let max_timestamp = result.last()?.timestamp.get();
            Some(file_index.start_time().to_microseconds().get() > max_timestamp)
        }
        Direction::Backward => {
            // For backward: if file ends before our earliest entry, skip all remaining files
            let min_timestamp = result.first()?.timestamp.get();
            Some(file_index.end_time().to_microseconds().get() < min_timestamp)
        }
    }
}

/// Merges two sorted vectors into a single sorted vector with at most `limit` elements.
///
/// This function performs a two-pointer merge, which is efficient for combining
/// sorted sequences. It only retains the smallest/largest `limit` entries by timestamp
/// depending on the direction.
///
/// # Arguments
///
/// * `a` - First sorted vector
/// * `b` - Second sorted vector
/// * `limit` - Maximum number of elements in the result
/// * `direction` - Direction determines ascending (Forward) or descending (Backward) order
///
/// # Returns
///
/// A new vector containing the merged and limited results
fn merge_log_entries(
    a: Vec<LogEntryId>,
    b: Vec<LogEntryId>,
    limit: usize,
    direction: Direction,
) -> Vec<LogEntryId> {
    // Handle simple cases
    if a.is_empty() {
        return b.into_iter().take(limit).collect();
    }
    if b.is_empty() {
        return a.into_iter().take(limit).collect();
    }

    // Allocate result vector with appropriate capacity — cap at actual data size
    // to avoid capacity overflow when limit is usize::MAX (no limit set).
    let mut result = Vec::with_capacity(a.len().saturating_add(b.len()).min(limit));
    let mut i = 0;
    let mut j = 0;

    // Two-pointer merge: always take the appropriate element based on direction
    while result.len() < limit {
        let take_from_a = match (i < a.len(), j < b.len()) {
            (true, false) => true,
            (false, true) => false,
            (false, false) => break,
            (true, true) => match direction {
                Direction::Forward => a[i].timestamp <= b[j].timestamp,
                Direction::Backward => a[i].timestamp >= b[j].timestamp,
            },
        };

        if take_from_a {
            result.push(a[i].clone());
            i += 1;
        } else {
            result.push(b[j].clone());
            j += 1;
        }
    }

    result
}

fn is_projected(raw_field_name: &str, output_fields: Option<&HashSet<String>>) -> bool {
    output_fields.map_or(true, |projected| projected.contains(raw_field_name))
}

/// Raw field data extracted from a journal entry.
///
/// This is an intermediate representation between a `LogEntryId` (which only contains
/// a file offset) and format-specific structures like `Table`, Arrow `RecordBatch`,
/// or columnar data.
///
/// The fields are stored as `FieldValuePair` objects, which efficiently store the
/// field name and value with a cached split position for fast access.
#[derive(Debug, Clone)]
pub struct LogEntryData {
    /// Timestamp of the entry in microseconds since epoch
    pub timestamp: u64,
    /// All field=value pairs in this entry
    pub fields: Vec<FieldValuePair>,
}

/// Extracts raw field data from multiple log entries efficiently.
///
/// This function groups entries by file and processes them in batches,
/// minimizing file open/close overhead. It reads the journal files and
/// extracts all field=value pairs without applying any transformations.
///
/// # Arguments
///
/// * `log_entries` - Slice of log entry IDs to extract data from
///
/// # Returns
///
/// A vector of `LogEntryData` in the same order as the input entries
fn extract_entry_data(
    log_entries: &[LogEntryId],
    output_fields: Option<&HashSet<String>>,
) -> Result<Vec<LogEntryData>> {
    let entries_by_file = entries_grouped_by_file(log_entries);
    let mut result = vec![None; log_entries.len()];

    for (file, file_entries) in entries_by_file {
        let journal_file = JournalFile::<Mmap>::open(file, 8 * 1024 * 1024)?;
        let mut row = CurrentRowView::default();

        for (original_idx, entry) in file_entries {
            let fields = read_entry_fields(&journal_file, entry, output_fields, &mut row)?;
            result[original_idx] = Some(LogEntryData {
                timestamp: entry.timestamp.get(),
                fields,
            });
        }
    }

    Ok(result.into_iter().flatten().collect())
}

fn entries_grouped_by_file(
    log_entries: &[LogEntryId],
) -> HashMap<&File, Vec<(usize, &LogEntryId)>> {
    let mut entries_by_file: HashMap<&File, Vec<(usize, &LogEntryId)>> = HashMap::new();
    for (idx, entry) in log_entries.iter().enumerate() {
        entries_by_file
            .entry(&entry.file)
            .or_default()
            .push((idx, entry));
    }
    entries_by_file
}

fn read_entry_fields(
    journal_file: &JournalFile<Mmap>,
    entry: &LogEntryId,
    output_fields: Option<&HashSet<String>>,
    row: &mut CurrentRowView,
) -> Result<Vec<FieldValuePair>> {
    let entry_offset =
        NonZeroU64::new(entry.offset).ok_or(journal_core::JournalError::InvalidOffset)?;
    row.load_entry(journal_file, entry_offset)?;
    let mut fields = Vec::with_capacity(row.data_offset_count());
    row.restart_data()?;

    let result = (|| {
        while let Some((_, payload)) = row.read_next_payload_with_offset(journal_file)? {
            let payload = row.payload_slice(payload);
            if let Some(pair) = read_projected_pair(payload, output_fields) {
                fields.push(pair);
            }
        }
        Ok(fields)
    })();
    row.reset_data_state(journal_file)?;
    result
}

fn read_projected_pair(
    payload_bytes: &[u8],
    output_fields: Option<&HashSet<String>>,
) -> Option<FieldValuePair> {
    if !payload_may_match_projection(payload_bytes, output_fields) {
        return None;
    }
    if let Some(pair) = FieldValuePair::parse_bytes(payload_bytes) {
        return is_projected(pair.field(), output_fields).then_some(pair);
    }
    let payload_str = String::from_utf8_lossy(payload_bytes);
    let Some(pair) = FieldValuePair::parse(&payload_str) else {
        return None;
    };
    is_projected(pair.field(), output_fields).then_some(pair)
}

fn payload_may_match_projection(
    payload_bytes: &[u8],
    output_fields: Option<&HashSet<String>>,
) -> bool {
    let Some(projected) = output_fields else {
        return true;
    };
    let Some(eq) = payload_bytes.iter().position(|byte| *byte == b'=') else {
        return true;
    };
    let Ok(field) = std::str::from_utf8(&payload_bytes[..eq]) else {
        return true;
    };
    projected.contains(field)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn projected_fields(fields: &[&str]) -> HashSet<String> {
        fields.iter().map(|field| (*field).to_string()).collect()
    }

    #[test]
    fn projection_accepts_raw_systemd_field_name() {
        let projected = projected_fields(&["_SYSTEMD_UNIT"]);

        assert!(is_projected("_SYSTEMD_UNIT", Some(&projected)));
    }

    #[test]
    fn projection_rejects_unmatched_field_names() {
        let projected = projected_fields(&["service.name"]);

        assert!(!is_projected("_SYSTEMD_UNIT", Some(&projected)));
    }

    #[test]
    fn projection_accepts_all_fields_without_projection_filter() {
        assert!(is_projected("_SYSTEMD_UNIT", None));
    }

    #[test]
    fn projected_pair_prefilter_rejects_unmatched_utf8_field_without_parsing_value() {
        let projected = projected_fields(&["MESSAGE"]);

        assert!(read_projected_pair(b"PRIORITY=3", Some(&projected)).is_none());
        assert_eq!(
            read_projected_pair(b"MESSAGE=hello", Some(&projected))
                .expect("projected pair")
                .as_str(),
            "MESSAGE=hello"
        );
    }

    #[test]
    fn projected_pair_preserves_lossy_legacy_path_for_non_utf8_payloads() {
        let projected = projected_fields(&["FIELD"]);
        let pair = read_projected_pair(b"FIELD=\xff", Some(&projected)).expect("lossy pair");

        assert_eq!(pair.field(), "FIELD");
    }
}