-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathmod.rs
More file actions
332 lines (287 loc) · 11.7 KB
/
Copy pathmod.rs
File metadata and controls
332 lines (287 loc) · 11.7 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
use std::{fmt, io};
use log::{debug, warn};
use crate::{
commit::Commit,
error,
index::{IndexFile, IndexFileMut},
segment::{FileLike, Header, Metadata, OffsetIndexWriter, Reader, Writer},
Options,
};
pub(crate) mod fs;
#[cfg(any(test, feature = "test"))]
pub mod mem;
pub use fs::{Fs, OnNewSegmentFn, SizeOnDisk};
#[cfg(any(test, feature = "test"))]
pub use mem::Memory;
pub type TxOffset = u64;
pub type TxOffsetIndexMut = IndexFileMut<TxOffset>;
pub type TxOffsetIndex = IndexFile<TxOffset>;
pub trait SegmentLen: io::Seek {
/// Determine the length in bytes of the segment.
///
/// This method does not rely on metadata `fsync`, and may use up to three
/// `seek` operations.
///
/// If the method returns successfully, the seek position before the call is
/// restored. However, if it returns an error, the seek position is
/// unspecified.
///
/// The returned length will be the bytes actually written to the segment,
/// not the allocated size of the segment (if the `fallocate` feature is
/// enabled).
//
// TODO: Remove trait and replace with `Seek::stream_len` if / when stabilized:
// https://github.com/rust-lang/rust/issues/59359
fn segment_len(&mut self) -> io::Result<u64> {
let old_pos = self.stream_position()?;
let len = self.seek(io::SeekFrom::End(0))?;
// Avoid seeking a third time when we were already at the end of the
// stream. The branch is usually way cheaper than a seek operation.
if old_pos != len {
self.seek(io::SeekFrom::Start(old_pos))?;
}
Ok(len)
}
}
pub trait SegmentReader: io::BufRead + SegmentLen + Send + Sync {}
impl<T: io::BufRead + SegmentLen + Send + Sync> SegmentReader for T {}
pub trait SegmentWriter: FileLike + io::Read + io::Write + SegmentLen + Send + Sync {}
impl<T: FileLike + io::Read + io::Write + SegmentLen + Send + Sync> SegmentWriter for T {}
/// A repository of log segments.
///
/// This is mainly an internal trait to allow testing against an in-memory
/// representation.
///
/// The [fmt::Display] should provide context about the location of the repo,
/// e.g. the root directory for a filesystem-based implementation.
pub trait Repo: Clone + fmt::Display {
/// The type of log segments managed by this repo, which must behave like a file.
type SegmentWriter: SegmentWriter + 'static;
type SegmentReader: SegmentReader + 'static;
/// Create a new segment with the minimum transaction offset `offset`.
///
/// This **must** create the segment atomically, and return
/// [`io::ErrorKind::AlreadyExists`] if the segment already exists.
///
/// It is permissible, however, to successfully return the new segment if
/// it is completely empty (i.e. [`create_segment_writer`] did not previously
/// succeed in writing the segment header).
fn create_segment(&self, offset: u64) -> io::Result<Self::SegmentWriter>;
/// Open an existing segment at the minimum transaction offset `offset`.
///
/// Must return [`io::ErrorKind::NotFound`] if a segment with the given
/// `offset` does not exist.
///
/// The method does not guarantee that the segment is non-empty -- this case
/// will be caught by [`open_segment_reader`].
fn open_segment_reader(&self, offset: u64) -> io::Result<Self::SegmentReader>;
/// Open an existing segment at the minimum transaction offset `offset`.
///
/// Must return [`io::ErrorKind::NotFound`] if a segment with the given
/// `offset` does not exist.
///
/// The method does not guarantee that the segment is non-empty -- this case
/// will be caught by [`resume_segment_writer`].
fn open_segment_writer(&self, offset: u64) -> io::Result<Self::SegmentWriter>;
/// Remove the segment at the minimum transaction offset `offset`.
///
/// Return [`io::ErrorKind::NotFound`] if no such segment exists.
fn remove_segment(&self, offset: u64) -> io::Result<()>;
/// Compress a segment in storage, marking it as immutable.
fn compress_segment(&self, offset: u64) -> io::Result<()>;
/// Traverse all segments in this repository and return list of their
/// offsets, sorted in ascending order.
fn existing_offsets(&self) -> io::Result<Vec<u64>>;
/// Create [`TxOffsetIndexMut`] for the given `offset` or open it if already exist.
/// The `cap` parameter is the maximum number of entries in the index.
fn create_offset_index(&self, _offset: TxOffset, _cap: u64) -> io::Result<TxOffsetIndexMut> {
Err(io::Error::other("not implemented"))
}
/// Remove [`TxOffsetIndexMut`] named with `offset`.
fn remove_offset_index(&self, _offset: TxOffset) -> io::Result<()> {
Err(io::Error::other("not implemented"))
}
/// Get [`TxOffsetIndex`] for the given `offset`.
fn get_offset_index(&self, _offset: TxOffset) -> io::Result<TxOffsetIndex> {
Err(io::Error::other("not implemented"))
}
}
impl<T: Repo> Repo for &T {
type SegmentWriter = T::SegmentWriter;
type SegmentReader = T::SegmentReader;
fn create_segment(&self, offset: u64) -> io::Result<Self::SegmentWriter> {
T::create_segment(self, offset)
}
fn open_segment_reader(&self, offset: u64) -> io::Result<Self::SegmentReader> {
T::open_segment_reader(self, offset)
}
fn open_segment_writer(&self, offset: u64) -> io::Result<Self::SegmentWriter> {
T::open_segment_writer(self, offset)
}
fn remove_segment(&self, offset: u64) -> io::Result<()> {
T::remove_segment(self, offset)
}
fn compress_segment(&self, offset: u64) -> io::Result<()> {
T::compress_segment(self, offset)
}
fn existing_offsets(&self) -> io::Result<Vec<u64>> {
T::existing_offsets(self)
}
fn create_offset_index(&self, offset: TxOffset, cap: u64) -> io::Result<TxOffsetIndexMut> {
T::create_offset_index(self, offset, cap)
}
/// Remove [`TxOffsetIndexMut`] named with `offset`.
fn remove_offset_index(&self, offset: TxOffset) -> io::Result<()> {
T::remove_offset_index(self, offset)
}
/// Get [`TxOffsetIndex`] for the given `offset`.
fn get_offset_index(&self, offset: TxOffset) -> io::Result<TxOffsetIndex> {
T::get_offset_index(self, offset)
}
}
impl<T: SegmentLen> SegmentLen for io::BufReader<T> {
fn segment_len(&mut self) -> io::Result<u64> {
SegmentLen::segment_len(self.get_mut())
}
}
pub(crate) fn create_offset_index_writer<R: Repo>(repo: &R, offset: u64, opts: Options) -> Option<OffsetIndexWriter> {
repo.create_offset_index(offset, opts.offset_index_len())
.map(|index| OffsetIndexWriter::new(index, opts))
.map_err(|e| {
warn!("failed to get offset index for segment {offset}: {e}");
})
.ok()
}
/// Create a new segment [`Writer`] with `offset`.
///
/// Immediately attempts to write the segment header with the supplied
/// `log_format_version`.
///
/// If the segment already exists, [`io::ErrorKind::AlreadyExists`] is returned.
pub fn create_segment_writer<R: Repo>(
repo: &R,
opts: Options,
epoch: u64,
offset: u64,
) -> io::Result<Writer<R::SegmentWriter>> {
let mut storage = repo.create_segment(offset)?;
// Ensure we have enough space for this segment.
fallocate(&mut storage, &opts)?;
Header {
log_format_version: opts.log_format_version,
checksum_algorithm: Commit::CHECKSUM_ALGORITHM,
}
.write(&mut storage)?;
storage.fsync()?;
Ok(Writer {
commit: Commit {
min_tx_offset: offset,
n: 0,
records: Vec::new(),
epoch,
},
inner: io::BufWriter::new(storage),
min_tx_offset: offset,
bytes_written: Header::LEN as u64,
max_records_in_commit: opts.max_records_in_commit,
flush_on_commit: opts.flush_on_commit,
offset_index_head: create_offset_index_writer(repo, offset, opts),
})
}
/// Open the existing segment at `offset` for writing.
///
/// This will traverse the segment in order to find the offset of the next
/// commit to write to it, which may fail for various reasons.
///
/// If the traversal is successful, the segment header is checked against the
/// `max_log_format_version`, and [`io::ErrorKind::InvalidData`] is returned if
/// the segment's log format version is greater than the given value. Likewise
/// if the checksum algorithm stored in the segment header cannot be handled
/// by this crate.
///
/// If only a (non-empty) prefix of the segment could be read due to a failure
/// to decode a [`Commit`], the segment [`Metadata`] read up to the faulty
/// commit is returned in an `Err`. In this case, a new segment should be
/// created for writing.
pub fn resume_segment_writer<R: Repo>(
repo: &R,
opts: Options,
offset: u64,
) -> io::Result<Result<Writer<R::SegmentWriter>, Metadata>> {
let mut storage = repo.open_segment_writer(offset)?;
// Ensure we have enough space for this segment.
// The segment could have been created without the `fallocate` feature
// enabled, so we call this here again to ensure writes can't fail due to
// ENOSPC.
fallocate(&mut storage, &opts)?;
let offset_index = repo.get_offset_index(offset).ok();
let Metadata {
header,
tx_range,
size_in_bytes,
max_epoch,
max_commit_offset: _,
} = match Metadata::extract(offset, &mut storage, offset_index.as_ref()) {
Err(error::SegmentMetadata::InvalidCommit { sofar, source }) => {
warn!("invalid commit in segment {offset}: {source}");
debug!("sofar={sofar:?}");
return Ok(Err(sofar));
}
Err(error::SegmentMetadata::Io(e)) => return Err(e),
Ok(meta) => meta,
};
header
.ensure_compatible(opts.log_format_version, Commit::CHECKSUM_ALGORITHM)
.map_err(|msg| io::Error::new(io::ErrorKind::InvalidData, msg))?;
// When resuming, the log format version must be equal.
if header.log_format_version != opts.log_format_version {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"log format version mismatch: current={} segment={}",
opts.log_format_version, header.log_format_version
),
));
}
Ok(Ok(Writer {
commit: Commit {
min_tx_offset: tx_range.end,
n: 0,
records: Vec::new(),
epoch: max_epoch,
},
inner: io::BufWriter::new(storage),
min_tx_offset: tx_range.start,
bytes_written: size_in_bytes,
max_records_in_commit: opts.max_records_in_commit,
flush_on_commit: opts.flush_on_commit,
offset_index_head: create_offset_index_writer(repo, offset, opts),
}))
}
/// Open the existing segment at `offset` for reading.
///
/// Unlike [`resume_segment_writer`], this does not traverse the segment. It
/// does, however, attempt to read the segment header and checks that the log
/// format version and checksum algorithm are compatible.
pub fn open_segment_reader<R: Repo>(
repo: &R,
max_log_format_version: u8,
offset: u64,
) -> io::Result<Reader<R::SegmentReader>> {
debug!("open segment reader at {offset}");
let storage = repo.open_segment_reader(offset)?;
Reader::new(max_log_format_version, offset, storage)
}
/// Allocate [Options::max_segment_size] of space for [FileLike]
/// if the `fallocate` feature is enabled,
/// and [Options::preallocate_segments] is `true`.
///
/// No-op otherwise.
#[inline]
pub(crate) fn fallocate(_f: &mut impl FileLike, _opts: &Options) -> io::Result<()> {
#[cfg(feature = "fallocate")]
if _opts.preallocate_segments {
_f.fallocate(_opts.max_segment_size)?;
}
Ok(())
}