Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 23 additions & 16 deletions pkgs/id/crates/id-core/src/petname.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,22 +61,23 @@ impl Petnames {
names: BTreeMap::new(),
journal: Some(path.to_path_buf()),
};
let text = match std::fs::read_to_string(path) {
Ok(text) => text,
let bytes = match std::fs::read(path) {
Ok(bytes) => bytes,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(store),
Err(error) => return Err(error.into()),
};
let mut kept = 0;
for (number, line) in text.split_inclusive('\n').enumerate() {
let complete = line.ends_with('\n');
if !complete {
for (number, line) in bytes.split_inclusive(|byte| *byte == b'\n').enumerate() {
if !line.ends_with(b"\n") {
break;
}
if line.trim().is_empty() {
let text = std::str::from_utf8(line)
.with_context(|| format!("petname journal line {} is malformed", number + 1))?;
if text.trim().is_empty() {
kept += line.len();
continue;
}
match serde_json::from_str::<Record>(line.trim_end()) {
match serde_json::from_str::<Record>(text.trim_end()) {
Ok(record) => {
store.apply(record);
kept += line.len();
Expand All @@ -88,7 +89,7 @@ impl Petnames {
}
}
}
if kept < text.len() {
if kept < bytes.len() {
std::fs::OpenOptions::new()
.write(true)
.open(path)?
Expand Down Expand Up @@ -608,24 +609,30 @@ mod tests {
let dir = TempDir::new().unwrap();
let path = dir.path().join("petnames.jsonl");
let mut store = Petnames::open(&path).unwrap();
store.set(OWNER, ALICE, "Ali", names()).unwrap();
store.set(OWNER, ALICE, "José", names()).unwrap();
drop(store);
let good = std::fs::read_to_string(&path).unwrap();
// A crash mid-append leaves a partial record, no trailing newline.
let good = std::fs::read(&path).unwrap();
// A crash after the first byte of a multibyte name leaves invalid
// UTF-8 in the unterminated final record.
let mut torn = good.clone();
torn.push_str(&format!(
"{{\"op\":\"set\",\"owner\":\"{OWNER}\",\"account\":\"{CAROL}\",\"name\":\"Car"
));
torn.extend_from_slice(
format!(
"{{\"op\":\"set\",\"owner\":\"{OWNER}\",\"account\":\"{CAROL}\",\"name\":\"Jos"
)
.as_bytes(),
);
torn.push(0xc3); // First byte of "é".
std::fs::write(&path, torn).unwrap();
let mut store = Petnames::open(&path).unwrap();
assert_eq!(store.get(OWNER, ALICE), Some("Ali"));
assert_eq!(store.get(OWNER, ALICE), Some("José"));
assert!(store.get(OWNER, CAROL).is_none());
// The torn bytes are truncated, so the next append is not glued
// onto them and replays cleanly on the next open.
assert_eq!(std::fs::read_to_string(&path).unwrap(), good);
assert_eq!(std::fs::read(&path).unwrap(), good);
store.set(OWNER, CAROL, "Carol", names()).unwrap();
drop(store);
let store = Petnames::open(&path).unwrap();
assert_eq!(store.get(OWNER, ALICE), Some("José"));
assert_eq!(store.get(OWNER, CAROL), Some("Carol"));
}

Expand Down
30 changes: 20 additions & 10 deletions pkgs/id/src/artifact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -609,13 +609,16 @@ impl ArtifactLog {
///
/// Fails if a complete line is corrupt or does not verify.
pub fn open(path: &Path) -> Result<Self> {
let text = match fs::read_to_string(path) {
Ok(text) => text,
let bytes = match fs::read(path) {
Ok(bytes) => bytes,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Self::default()),
Err(error) => return Err(error).context("reading the artifact file"),
};
let kept = text.rfind('\n').map_or(0, |index| index + 1);
if kept < text.len() {
let kept = bytes
.iter()
.rposition(|&byte| byte == b'\n')
.map_or(0, |index| index + 1);
if kept < bytes.len() {
// #2128: mirror Directory::replay / FileJournal::open - a torn
// final entry is dropped loudly, not silently.
tracing::warn!(
Expand All @@ -627,8 +630,9 @@ impl ArtifactLog {
.open(path)?
.set_len(u64::try_from(kept)?)?;
}
let text = std::str::from_utf8(&bytes[..kept]).context("artifact file is not UTF-8")?;
let mut log = Self::default();
for (number, line) in text[..kept].lines().enumerate() {
for (number, line) in text.lines().enumerate() {
// #2128: blank lines are cosmetic (Directory::replay skips them
// in its own journal); enumerate() keeps the physical line
// number, so a corrupt non-blank line still reports its true
Expand Down Expand Up @@ -1360,14 +1364,20 @@ mod tests {
let second = log.sign(&key(1), &declared(1, 7)).unwrap();
log.insert(second.clone()).unwrap();
append(&path, &second).unwrap();
let mut text = fs::read_to_string(&path).unwrap();
text.push_str("{\"author\":\"tor");
fs::write(&path, text).unwrap();
let complete = fs::read(&path).unwrap();
let mut torn = complete.clone();
torn.extend_from_slice(b"{\"name\":\"Jos");
torn.push(0xc3); // First byte of "é".
fs::write(&path, torn).unwrap();

let reopened = ArtifactLog::open(&path).unwrap();
let mut reopened = ArtifactLog::open(&path).unwrap();
assert_eq!(reopened, log);
assert!(fs::read_to_string(&path).unwrap().ends_with('\n'));
assert_eq!(fs::read(&path).unwrap(), complete);
assert_eq!(reopened.head_seq(&public(1)), 2);
let third = reopened.sign(&key(1), &declared(1, 9)).unwrap();
reopened.insert(third.clone()).unwrap();
append(&path, &third).unwrap();
assert_eq!(ArtifactLog::open(&path).unwrap(), reopened);
}

#[test]
Expand Down
40 changes: 25 additions & 15 deletions pkgs/id/src/directory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -491,8 +491,8 @@ impl Directory {
/// Fails if a line is malformed or an entry breaks a directory rule.
pub fn replay(path: &Path) -> Result<Self> {
let mut directory = Self::new();
let text = match std::fs::read_to_string(path) {
Ok(text) => text,
let bytes = match std::fs::read(path) {
Ok(bytes) => bytes,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(directory),
Err(error) => return Err(error.into()),
};
Expand All @@ -503,12 +503,15 @@ impl Directory {
// drop the fragment (parseable or not), warn, and truncate the
// file to the last complete line. A newline-terminated line
// that does not parse is corruption and still fails below.
let kept_len = if text.is_empty() || text.ends_with('\n') {
text.len()
let kept_len = if bytes.is_empty() || bytes.ends_with(b"\n") {
bytes.len()
} else {
text.rfind('\n').map_or(0, |index| index + 1)
bytes
.iter()
.rposition(|&byte| byte == b'\n')
.map_or(0, |index| index + 1)
};
if kept_len < text.len() {
if kept_len < bytes.len() {
tracing::warn!(
"directory journal {}: dropping torn final entry at byte {kept_len}",
path.display()
Expand All @@ -518,7 +521,9 @@ impl Directory {
.open(path)?
.set_len(u64::try_from(kept_len)?)?;
}
for (number, line) in text[..kept_len].lines().enumerate() {
let text =
std::str::from_utf8(&bytes[..kept_len]).context("directory journal is not UTF-8")?;
for (number, line) in text.lines().enumerate() {
if line.trim().is_empty() {
continue;
}
Expand Down Expand Up @@ -3298,19 +3303,24 @@ mod tests {
let dir = TempDir::new().unwrap();
let path = dir.path().join("directory.jsonl");
let mut directory = Directory::new();
let (ann, ann_credential) = account_into(&mut directory, &path, "Ann");
let (ann, ann_credential) = account_into(&mut directory, &path, "José");
let (_bo, _) = account_into(&mut directory, &path, "Bo");
let complete = std::fs::read_to_string(&path).unwrap();
let complete = std::fs::read(&path).unwrap();

// A crash mid-append leaves half a JSON entry with no newline.
let mut text = complete.clone();
text.push_str("{\"account_created\":{\"id\":\"torn");
std::fs::write(&path, text).unwrap();
// A crash after the first byte of a multibyte name leaves invalid
// UTF-8 in the unterminated final entry.
let mut torn = complete.clone();
torn.extend_from_slice(b"{\"name\":\"Jos");
torn.push(0xc3); // First byte of "é".
std::fs::write(&path, torn).unwrap();

let replayed = Directory::replay(&path).unwrap();
let mut replayed = Directory::replay(&path).unwrap();
assert_eq!(replayed.account_for(&ann_credential), Some(ann));
// The fragment is gone: the file is back to the complete lines.
assert_eq!(std::fs::read_to_string(&path).unwrap(), complete);
assert_eq!(std::fs::read(&path).unwrap(), complete);
let (carol, carol_credential) = account_into(&mut replayed, &path, "Carol");
let roundtrip = Directory::replay(&path).unwrap();
assert_eq!(roundtrip.account_for(&carol_credential), Some(carol));
}

#[test]
Expand Down
19 changes: 11 additions & 8 deletions pkgs/id/src/envelope_outbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,14 +132,14 @@ impl Outbox {
path: path.into(),
entries: BTreeMap::new(),
};
let text = match fs::read_to_string(&outbox.path) {
Ok(text) => text,
let bytes = match fs::read(&outbox.path) {
Ok(bytes) => bytes,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(outbox),
Err(error) => return Err(error).context("reading the envelope outbox"),
};
let mut kept = 0;
for (number, line) in text.split_inclusive('\n').enumerate() {
if !line.ends_with('\n') {
for (number, line) in bytes.split_inclusive(|byte| *byte == b'\n').enumerate() {
if !line.ends_with(b"\n") {
// The final line has no newline: a crash cut the append
// short. Parseable or not, it was never completely
// written, so it is torn and dropped — the same rule
Expand All @@ -150,13 +150,15 @@ impl Outbox {
// truncated to it below.
break;
}
if line.trim().is_empty() {
let text = std::str::from_utf8(line)
.with_context(|| format!("envelope outbox line {} is corrupt", number + 1))?;
if text.trim().is_empty() {
// Blank lines carry no records, but they are complete bytes in
// the journal and must remain before any later torn tail.
kept += line.len();
continue;
}
match serde_json::from_str::<Record>(line.trim_end()) {
match serde_json::from_str::<Record>(text.trim_end()) {
Ok(record) => {
outbox.apply(record)?;
kept += line.len();
Expand All @@ -168,7 +170,7 @@ impl Outbox {
}
}
}
if kept < text.len() {
if kept < bytes.len() {
OpenOptions::new()
.write(true)
.open(&outbox.path)?
Expand Down Expand Up @@ -574,7 +576,8 @@ mod tests {
outbox.enqueue(&target(), envelope("e1")).unwrap();
drop(outbox);
let mut file = OpenOptions::new().append(true).open(path(&dir)).unwrap();
file.write_all(b"{\"op\":\"queued\",\"target\"").unwrap();
// The tail is cut after the first byte of a multibyte name.
file.write_all(b"{\"name\":\"Jos\xc3").unwrap();
drop(file);

let mut outbox = Outbox::open(path(&dir)).unwrap();
Expand Down
34 changes: 21 additions & 13 deletions pkgs/id/src/groups/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,26 +53,29 @@ impl GroupLog {
///
/// Fails if the file cannot be read, or a complete line is not an event.
pub fn open(path: &Path) -> Result<Self> {
let text = match std::fs::read_to_string(path) {
Ok(text) => text,
Err(error) if error.kind() == ErrorKind::NotFound => String::new(),
let bytes = match std::fs::read(path) {
Ok(bytes) => bytes,
Err(error) if error.kind() == ErrorKind::NotFound => Vec::new(),
Err(error) => return Err(error).with_context(|| format!("read {}", path.display())),
};
let mut events = Vec::new();
let mut kept = 0;
for (number, line) in text.split_inclusive('\n').enumerate() {
if !line.ends_with('\n') {
for (number, line) in bytes.split_inclusive(|byte| *byte == b'\n').enumerate() {
if !line.ends_with(b"\n") {
tracing::warn!(
"group log {}: dropping torn final entry at byte {kept}",
path.display()
);
break;
}
if line.trim().is_empty() {
let text = std::str::from_utf8(line).with_context(|| {
format!("{}: line {} is not an event", path.display(), number + 1)
})?;
if text.trim().is_empty() {
kept += line.len();
continue;
}
match serde_json::from_str::<Event>(line.trim_end()) {
match serde_json::from_str::<Event>(text.trim_end()) {
Ok(event) => {
events.push(event);
kept += line.len();
Expand All @@ -84,7 +87,7 @@ impl GroupLog {
}
}
}
if kept < text.len() {
if kept < bytes.len() {
OpenOptions::new()
.write(true)
.open(path)
Expand Down Expand Up @@ -544,19 +547,24 @@ mod tests {
let mut log = GroupLog::open(&path).unwrap();
let created = log.record(OWNER, None, create_body()).unwrap();
drop(log);
let good = std::fs::read_to_string(&path).unwrap();
// A crash mid-append leaves a partial event, no trailing newline.
let good = std::fs::read(&path).unwrap();
// A crash after the first byte of a multibyte name leaves invalid
// UTF-8 in the unterminated final event.
let mut torn = good.clone();
torn.push_str("{\"id\":\"f00");
torn.extend_from_slice(b"{\"name\":\"Jos");
torn.push(0xc3); // First byte of "é".
std::fs::write(&path, torn).unwrap();

let reopened = GroupLog::open(&path).unwrap();
let mut reopened = GroupLog::open(&path).unwrap();
assert_eq!(reopened.events().len(), 1);
let projection = reopened.projection().unwrap();
assert!(projection.group(&created.event).is_some());
// The torn bytes are truncated, so the next append is not glued
// onto them and replays cleanly on the next open.
assert_eq!(std::fs::read_to_string(&path).unwrap(), good);
assert_eq!(std::fs::read(&path).unwrap(), good);
reopened.record(OWNER, None, create_body()).unwrap();
drop(reopened);
assert_eq!(GroupLog::open(&path).unwrap().events().len(), 2);
}

#[test]
Expand Down
Loading