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
//! The writer side of a partition: only the last segment (the active segment)
//! receives writes.
use std::fs;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use super::retention::{self, SealedSegment};
use super::{
FsyncPolicy, LogConfig, list_segment_bases, read_across, remove_orphan_indexes,
segment_log_path,
};
use crate::durable::sync_dir;
use crate::error::{Error, Result, corrupt};
use crate::partition_state::{SharedState, WriterState};
use crate::record::{self, Message, Record};
use crate::segment::Segment;
/// The append-only log of a partition, stored in its own directory.
#[derive(Debug)]
pub struct PartitionLog {
dir: PathBuf,
config: LogConfig,
/// The segments before the active one, sorted by base offset.
sealed: Vec<Segment>,
/// The last segment, the only one that receives writes.
active: Segment,
}
impl PartitionLog {
/// Opens the log in directory `dir`, creating it if needed.
///
/// The end of the active segment is repaired if a write was interrupted.
/// Returns [`Error::Corrupt`] if a sealed segment is unreadable.
pub fn open(dir: impl AsRef<Path>, config: LogConfig) -> Result<Self> {
config.validate()?;
let dir = dir.as_ref().to_path_buf();
fs::create_dir_all(&dir)?;
let interval = config.index_interval_bytes;
let (sealed, active) = match list_segment_bases(&dir)?.split_last() {
None => {
let first = Segment::create(&dir, 0, interval)?;
first.sync()?;
sync_dir(&dir)?;
(Vec::new(), first)
}
Some((&last, sealed)) => (
sealed
.iter()
.map(|&base| Segment::open(&dir, base, interval, false))
.collect::<Result<_>>()?,
Segment::open(&dir, last, interval, true)?,
),
};
let mut log = Self {
dir,
config,
sealed,
active,
};
check_continuity(&log.dir, &log.all_segments())?;
// From the open segments, including a freshly created first segment.
let bases: Vec<u64> = log.all_segments().iter().map(|s| s.base_offset()).collect();
remove_orphan_indexes(&log.dir, &bases)?;
log.enforce_retention()?;
Ok(log)
}
/// First offset still available.
pub fn start_offset(&self) -> u64 {
self.sealed.first().unwrap_or(&self.active).base_offset()
}
/// Offset that the next appended message will receive.
pub fn next_offset(&self) -> u64 {
self.active().next_offset()
}
/// What to publish in the shared partition state after a change, for the
/// other writers and for readers.
pub(crate) fn writer_state(&self) -> WriterState {
WriterState {
next_offset: self.next_offset(),
end_position: self.active().size(),
active_base: self.active().base_offset(),
start_offset: self.start_offset(),
}
}
/// Brings this view of the partition up to date with what other writers
/// did since our last change, as described by `shared`.
///
/// Must be called under the partition's write lock, with the state read
/// there. Usually a few comparisons and one `fstat`; the partition is
/// reopened from disk (with the usual tail repair) when another writer
/// started a new segment, or died in the middle of a change.
pub(crate) fn catch_up(&mut self, shared: &SharedState) -> Result<()> {
let expected = shared.state;
if shared.dirty || expected.active_base != self.active().base_offset() {
return self.reload();
}
// Retention never deletes the active segment: a start beyond it is a
// state the files do not match. Trust the disk, not the state.
if expected.start_offset > expected.active_base {
return self.reload();
}
// Same active segment: its length must be the published one, or
// something happened that the state does not describe.
if self.active().file_len()? != expected.end_position {
return self.reload();
}
// Segments deleted by another writer's retention.
self.sealed
.retain(|s| s.base_offset() >= expected.start_offset);
if (self.active().size(), self.next_offset())
!= (expected.end_position, expected.next_offset)
{
self.active_mut()
.catch_up(expected.end_position, expected.next_offset)?;
}
Ok(())
}
/// Reopens the partition from disk, repairing an interrupted write.
fn reload(&mut self) -> Result<()> {
*self = Self::open(&self.dir, self.config.clone())?;
Ok(())
}
/// Appends a message and returns its offset.
pub fn append(&mut self, message: &Message) -> Result<u64> {
self.append_batch(std::slice::from_ref(message))
.map(|range| range.start)
}
/// Appends messages in order and returns the range of assigned offsets.
///
/// All messages are validated before the first write: an invalid
/// message leaves none of them written. With [`FsyncPolicy::Always`], the whole
/// batch is on disk on return.
pub fn append_batch(&mut self, messages: &[Message]) -> Result<Range<u64>> {
let range = self.append_unsynced(messages)?;
if self.config.fsync == FsyncPolicy::Always {
self.active().sync()?;
}
Ok(range)
}
/// Like [`append_batch`](Self::append_batch), but without the final
/// `fsync` of the `Always` policy: the caller flushes later, possibly
/// together with other writers' messages (group commit). A segment sealed
/// along the way is still flushed before the next one is created.
pub(crate) fn append_unsynced(&mut self, messages: &[Message]) -> Result<Range<u64>> {
let sizes = messages
.iter()
.map(record::validate)
.collect::<Result<Vec<_>>>()?;
let first_offset = self.next_offset();
let timestamp = record::now_millis();
let mut pending = PendingWrite::default();
let mut rolled = false;
for (message, size) in messages.iter().zip(sizes) {
if self.needs_roll(&pending, size) {
self.write_pending(&mut pending)?;
self.roll()?;
rolled = true;
}
let offset = self.active().next_offset() + pending.sizes.len() as u64;
let ts = message.timestamp.unwrap_or(timestamp);
record::encode(message, offset, ts, &mut pending.bytes);
pending.sizes.push(size);
}
self.write_pending(&mut pending)?;
// A new sealed segment may have aged; size, on the other hand, is
// checked on each append, from the sizes known in memory.
if rolled || self.exceeds_max_bytes() {
self.enforce_retention()?;
}
Ok(first_offset..self.next_offset())
}
/// Deletes the oldest sealed segments that exceed the configured
/// retention, and returns how many were deleted.
///
/// Called on open and on each new segment. The age limit
/// advances with time, without any write: calling this method
/// regularly also applies it during quiet periods.
pub fn enforce_retention(&mut self) -> Result<usize> {
let retention = self.config.retention;
if retention.is_unlimited() {
return Ok(0);
}
let sealed = self
.sealed
.iter()
.map(|s| {
Ok(SealedSegment {
size: s.size(),
last_write: match retention.max_age {
Some(_) => Some(s.last_write()?),
None => None,
},
})
})
.collect::<Result<Vec<_>>>()?;
let count = retention::segments_to_delete(
&sealed,
self.active.size(),
&retention,
SystemTime::now(),
);
if count == 0 {
return Ok(0);
}
// Oldest first: on failure, what remains is always
// a continuous sequence of segments.
// `count` is at most the number of sealed segments: the active one stays.
for segment in self.sealed.drain(..count.min(self.sealed.len())) {
segment.delete()?;
}
sync_dir(&self.dir)?;
Ok(count)
}
/// Reads records starting from `offset`, without exceeding `max_bytes`
/// (encoded size). Always returns at least one record if one
/// exists, even if larger than `max_bytes`, so as never to block a reader.
///
/// Reading at [`next_offset`](Self::next_offset) returns an empty list.
/// Returns [`Error::OffsetOutOfRange`] outside `start_offset..=next_offset`.
pub fn read(&self, offset: u64, max_bytes: usize) -> Result<Vec<Record>> {
let (start, end) = (self.start_offset(), self.next_offset());
if offset < start || offset > end {
return Err(Error::OffsetOutOfRange { offset, start, end });
}
let segments = self.all_segments();
let bases: Vec<u64> = segments.iter().map(|s| s.base_offset()).collect();
let mut out = Vec::new();
let mut used = 0;
read_across(
&bases,
offset,
end,
max_bytes,
&mut used,
&mut out,
|i, req, out| segments[i].read(req, out),
)?;
Ok(out)
}
fn exceeds_max_bytes(&self) -> bool {
self.config.retention.max_bytes.is_some_and(|max| {
// Only one segment: nothing to delete, the active segment stays.
!self.sealed.is_empty()
&& self.sealed.iter().map(Segment::size).sum::<u64>() + self.active.size() > max
})
}
/// Forces everything appended so far to disk.
pub fn sync(&self) -> Result<()> {
self.active().sync()
}
fn active(&self) -> &Segment {
&self.active
}
fn active_mut(&mut self) -> &mut Segment {
&mut self.active
}
/// All segments, sorted by base offset, the active one last.
fn all_segments(&self) -> Vec<&Segment> {
self.sealed.iter().chain([&self.active]).collect()
}
/// Must a new segment be opened before appending a record of `size` bytes?
fn needs_roll(&self, pending: &PendingWrite, size: usize) -> bool {
let active = self.active();
let has_records = !active.is_empty() || !pending.sizes.is_empty();
let would_exceed =
active.size() + (pending.bytes.len() + size) as u64 > self.config.segment_max_bytes;
// The index's relative offsets are u32s.
let count = active.next_offset() - active.base_offset() + pending.sizes.len() as u64;
has_records && (would_exceed || count >= u64::from(u32::MAX))
}
fn write_pending(&mut self, pending: &mut PendingWrite) -> Result<()> {
if !pending.sizes.is_empty() {
self.active_mut().append(&pending.bytes, &pending.sizes)?;
pending.bytes.clear();
pending.sizes.clear();
}
Ok(())
}
/// Seals the active segment and opens a new one.
fn roll(&mut self) -> Result<()> {
// A sealed segment is never repaired again: it must be complete on disk.
self.active().sync()?;
let base = self.next_offset();
let segment = Segment::create(&self.dir, base, self.config.index_interval_bytes)?;
segment.sync()?;
sync_dir(&self.dir)?;
let sealed = std::mem::replace(&mut self.active, segment);
self.sealed.push(sealed);
Ok(())
}
}
/// Encoded records, not yet written to the active segment.
#[derive(Default)]
struct PendingWrite {
bytes: Vec<u8>,
sizes: Vec<usize>,
}
/// Each segment must end exactly where the next one begins:
/// otherwise offsets are missing or overlap.
fn check_continuity(dir: &Path, segments: &[&Segment]) -> Result<()> {
for pair in segments.windows(2) {
let (current, next) = (pair[0], pair[1]);
if current.next_offset() != next.base_offset() {
return Err(corrupt(
segment_log_path(dir, current.base_offset()),
format!(
"segment ends at offset {} but the next one starts at {}",
current.next_offset(),
next.base_offset()
),
));
}
}
Ok(())
}