-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathpartial.rs
More file actions
351 lines (302 loc) · 9.95 KB
/
Copy pathpartial.rs
File metadata and controls
351 lines (302 loc) · 9.95 KB
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
use std::{
cmp,
fmt::{self, Debug},
io::{self, Seek as _, SeekFrom},
iter::{self, repeat},
num::NonZeroU16,
};
use log::debug;
use pretty_assertions::assert_matches;
use crate::{
commitlog, error, payload,
repo::{self, Repo, SegmentLen},
segment::{self, FileLike},
tests::helpers::{enable_logging, fill_log_with},
Commit, Encode, Options, DEFAULT_LOG_FORMAT_VERSION,
};
#[test]
fn traversal() {
enable_logging();
let mut log = open_log::<[u8; 32]>(ShortMem::new(800));
let total_commits = 100;
let total_txs = fill_log_enospc(&mut log, total_commits, (1..=10).cycle());
assert_eq!(
total_txs,
log.transactions_from(0, &payload::ArrayDecoder)
.map(Result::unwrap)
.count()
);
assert_eq!(total_commits, log.commits_from(0).map(Result::unwrap).count());
}
// Note: Write errors cause the in-flight commit to be written to a fresh
// segment. So as long as we write through the public API, partial writes
// never surface (i.e. the log is contiguous).
#[test]
fn reopen() {
enable_logging();
let repo = ShortMem::new(800);
let num_commits = 10;
let mut total_txs = 0;
for i in 0..2 {
let mut log = open_log::<[u8; 32]>(repo.clone());
total_txs += fill_log_enospc(&mut log, num_commits, (1..=10).cycle());
debug!("fill {} done", i + 1);
}
assert_eq!(
total_txs,
open_log::<[u8; 32]>(repo.clone())
.transactions_from(0, &payload::ArrayDecoder)
.map(Result::unwrap)
.count()
);
// Let's see if we hit a funny case in any of the segments.
for offset in repo.existing_offsets().unwrap().into_iter().rev() {
let meta = repo::open_segment_reader(&repo, DEFAULT_LOG_FORMAT_VERSION, offset)
.unwrap()
.metadata()
.unwrap();
debug!("dropping segment: segment::{meta:?}");
repo.remove_segment(offset).unwrap();
assert_eq!(
meta.tx_range.start,
open_log::<[u8; 32]>(repo.clone())
.transactions_from(0, &payload::ArrayDecoder)
.map(Result::unwrap)
.count() as u64
);
}
}
#[test]
fn overwrite_reopen() {
enable_logging();
let repo = ShortMem::new(800);
let num_commits = 10;
let txs_per_commit = 5;
let mut log = open_log::<[u8; 32]>(repo.clone());
let mut total_txs = fill_log_enospc(&mut log, num_commits, repeat(txs_per_commit));
let last_segment_offset = repo.existing_offsets().unwrap().last().copied().unwrap();
let last_commit: Commit = repo::open_segment_reader(&repo, DEFAULT_LOG_FORMAT_VERSION, last_segment_offset)
.unwrap()
.commits()
.map(Result::unwrap)
.last()
.unwrap()
.into();
debug!("last commit: {last_commit:?}");
{
let mut last_segment = repo.open_segment_writer(last_segment_offset).unwrap();
let pos = last_segment.len() - last_commit.encoded_len() + 1;
last_segment.modify_byte_at(pos, |_| 255);
}
let mut log = open_log::<[u8; 32]>(repo.clone());
for (i, commit) in log.commits_from(0).enumerate() {
if i < num_commits - 1 {
commit.expect("all but last commit should be good");
} else {
let last_good_offset = txs_per_commit * (num_commits - 1);
assert!(
matches!(
commit,
Err(error::Traversal::Checksum { offset, .. }) if offset == last_good_offset as u64,
),
"expected checksum error with offset={last_good_offset}: {commit:?}"
);
}
}
// Write some more data.
total_txs += fill_log_enospc(&mut log, num_commits, repeat(txs_per_commit));
// Log should be contiguous, but missing one corrupted commit.
assert_eq!(
total_txs - txs_per_commit,
log.transactions_from(0, &payload::ArrayDecoder)
.map(Result::unwrap)
.count()
);
// Check that this is true if we reopen the log.
assert_eq!(
total_txs - txs_per_commit,
open_log::<[u8; 32]>(repo)
.transactions_from(0, &payload::ArrayDecoder)
.map(Result::unwrap)
.count()
);
}
/// Edge case surfaced in production:
///
/// If the first commit in the last segment is corrupt, creating a new segment
/// would fail because the `tx_range` is the same as the corrupt segment.
///
/// We don't automatically recover from that, but test that `open` returns an
/// error providing some context.
#[test]
fn first_commit_in_last_segment_corrupt() {
enable_logging();
let repo = repo::Memory::unlimited();
let options = Options {
max_segment_size: 512,
max_records_in_commit: NonZeroU16::new(1).unwrap(),
..<_>::default()
};
{
let mut log = commitlog::Generic::open(repo.clone(), options).unwrap();
fill_log_with(&mut log, iter::once([b'x'; 64]).cycle().take(9));
}
let segments = repo.existing_offsets().unwrap();
assert_eq!(2, segments.len(), "repo should contain 2 segments");
{
let mut last_segment = repo.open_segment_writer(*segments.last().unwrap()).unwrap();
last_segment.modify_bytes_at(segment::Header::LEN + 1.., |data| data.fill(0));
}
assert_matches!(
commitlog::Generic::<_, [u8; 64]>::open(repo, options),
Err(e) if e.kind() == io::ErrorKind::InvalidData,
);
}
fn open_log<T>(repo: ShortMem) -> commitlog::Generic<ShortMem, T> {
commitlog::Generic::open(
repo,
Options {
max_segment_size: 1024,
max_records_in_commit: NonZeroU16::new(10).unwrap(),
..Options::default()
},
)
.unwrap()
}
const ENOSPC: i32 = 28;
/// Wrapper around [`mem::Segment`] which causes a partial [`io::Write::write`]
/// if and when the size of the underlying buffer exceeds a max length.
#[derive(Debug)]
struct ShortSegment {
inner: repo::mem::Segment,
max_len: u64,
}
impl ShortSegment {
pub fn len(&self) -> usize {
self.inner.len()
}
pub fn modify_byte_at(&mut self, pos: usize, f: impl FnOnce(u8) -> u8) {
self.inner.modify_byte_at(pos, f);
}
}
impl SegmentLen for ShortSegment {
fn segment_len(&mut self) -> io::Result<u64> {
self.inner.segment_len()
}
}
impl FileLike for ShortSegment {
fn fsync(&mut self) -> std::io::Result<()> {
self.inner.fsync()
}
fn ftruncate(&mut self, tx_offset: u64, size: u64) -> std::io::Result<()> {
self.inner.ftruncate(tx_offset, size)
}
#[cfg(feature = "fallocate")]
fn fallocate(&mut self, size: u64) -> io::Result<()> {
self.inner.fallocate(size)
}
}
impl io::Write for ShortSegment {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let pos = self.inner.stream_position()?;
debug!("pos={} max_len={} buf-len={}", pos, self.max_len, buf.len());
if pos + buf.len() as u64 > self.max_len {
let max = cmp::min(1, (self.max_len - pos) as usize);
let n = self.inner.write(&buf[..max])?;
debug!("partial write {}/{}", n, buf.len());
return Err(io::Error::from_raw_os_error(ENOSPC));
}
self.inner.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.inner.flush()
}
}
impl io::Read for ShortSegment {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.inner.read(buf)
}
}
impl io::Seek for ShortSegment {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
self.inner.seek(pos)
}
}
/// Wrapper around [`repo::Memory`] which causes partial (or: short) writes.
#[derive(Debug, Clone)]
struct ShortMem {
inner: repo::Memory,
max_len: u64,
}
impl ShortMem {
pub fn new(max_len: u64) -> Self {
Self {
inner: repo::Memory::new(max_len * 4096),
max_len,
}
}
}
impl fmt::Display for ShortMem {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.inner, f)
}
}
impl Repo for ShortMem {
type SegmentWriter = ShortSegment;
type SegmentReader = io::BufReader<repo::mem::Segment>;
fn create_segment(&self, offset: u64) -> io::Result<Self::SegmentWriter> {
self.inner.create_segment(offset).map(|inner| ShortSegment {
inner,
max_len: self.max_len,
})
}
fn open_segment_writer(&self, offset: u64) -> io::Result<Self::SegmentWriter> {
self.inner.open_segment_writer(offset).map(|inner| ShortSegment {
inner,
max_len: self.max_len,
})
}
fn open_segment_reader(&self, offset: u64) -> io::Result<Self::SegmentReader> {
self.inner.open_segment_reader(offset)
}
fn remove_segment(&self, offset: u64) -> io::Result<()> {
self.inner.remove_segment(offset)
}
fn compress_segment(&self, offset: u64) -> io::Result<()> {
self.inner.compress_segment(offset)
}
fn existing_offsets(&self) -> io::Result<Vec<u64>> {
self.inner.existing_offsets()
}
}
/// Like [`crate::tests::helpers::fill_log`], but expect that ENOSPC happens at
/// least once.
fn fill_log_enospc<T>(
log: &mut commitlog::Generic<ShortMem, T>,
num_commits: usize,
txs_per_commit: impl Iterator<Item = usize>,
) -> usize
where
T: Debug + Default + Encode,
{
let mut seen_enospc = false;
let mut total_txs = 0;
for (_, n) in (0..num_commits).zip(txs_per_commit) {
for _ in 0..n {
log.append(T::default()).unwrap();
total_txs += 1;
}
let res = log.commit();
if let Err(Some(os)) = res.as_ref().map_err(|e| e.raw_os_error()) {
if os == ENOSPC {
debug!("fill: ignoring ENOSPC");
seen_enospc = true;
log.commit().unwrap();
continue;
}
}
res.unwrap();
}
assert!(seen_enospc, "expected to see ENOSPC");
total_txs
}