Cap reservation, partial-tail repair and the single-record append. Caller holds the exclusive append lock.
(&self, file: &mut std::fs::File, record: &[u8])
| 868 | /// Cap reservation, partial-tail repair and the single-record append. |
| 869 | /// Caller holds the exclusive append lock. |
| 870 | fn append_locked(&self, file: &mut std::fs::File, record: &[u8]) -> Result<(), std::io::Error> { |
| 871 | let length = file.metadata()?.len(); |
| 872 | if length > 0 { |
| 873 | let mut last = [0u8; 1]; |
| 874 | file.seek(SeekFrom::End(-1))?; |
| 875 | file.read_exact(&mut last)?; |
| 876 | if last[0] != b'\n' { |
| 877 | // A crashed writer left an incomplete trailing fragment — |
| 878 | // or foreign content. CB-13C F1 ownership rule: only an |
| 879 | // identified owned fragment (an unterminated JSON record |
| 880 | // starting with `{`, at most one maximum record long) is |
| 881 | // repaired; foreign content is preserved untouched and the |
| 882 | // event is dropped. Foreign data is never mutated or |
| 883 | // erased. |
| 884 | let window: u64 = (MAX_BRIDGE_EVENT_RECORD_BYTES as u64 * 16).min(length); |
| 885 | file.seek(SeekFrom::End(-(window as i64)))?; |
| 886 | let mut tail = vec![0u8; window as usize]; |
| 887 | file.read_exact(&mut tail)?; |
| 888 | match tail.iter().rposition(|byte| *byte == b'\n') { |
| 889 | Some(position) if window <= length => { |
| 890 | // The fragment after the last complete record. |
| 891 | let fragment = &tail[position + 1..]; |
| 892 | if !is_owned_crash_fragment(fragment) { |
| 893 | // Foreign content: preserve, drop the event. |
| 894 | return Ok(()); |
| 895 | } |
| 896 | file.set_len(length - window + position_to_len(position))?; |
| 897 | } |
| 898 | _ if length <= window => { |
| 899 | // No complete record exists anywhere: the whole |
| 900 | // file is one unterminated fragment — repairable |
| 901 | // only if it is an owned crash fragment. |
| 902 | if !is_owned_crash_fragment(&tail) { |
| 903 | return Ok(()); |
| 904 | } |
| 905 | file.set_len(0)?; |
| 906 | } |
| 907 | _ => { |
| 908 | // Foreign content without a newline in the window: |
| 909 | // refuse to guess and drop this event. |
| 910 | return Ok(()); |
| 911 | } |
| 912 | } |
| 913 | } |
| 914 | } |
| 915 | |
| 916 | let length = file.metadata()?.len(); |
| 917 | if length + record.len() as u64 > MAX_BRIDGE_EVENT_JOURNAL_BYTES { |
| 918 | // Retention bound reached: drop the event rather than truncate |
| 919 | // recorded history or grow without bound. |
| 920 | return Ok(()); |
| 921 | } |
| 922 | // One atomic O_APPEND write of the complete record. |
| 923 | file.write_all(record)?; |
| 924 | Ok(()) |
| 925 | } |
| 926 | |
| 927 | /// Append one event, swallowing every error: observability must never |
no test coverage detected