/
manager.rs
327 lines (285 loc) · 9.43 KB
/
manager.rs
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
// Copyright 2022 CeresDB Project Authors. Licensed under Apache-2.0.
//! WalManager abstraction
use std::{collections::VecDeque, fmt, sync::Arc, time::Duration};
use async_trait::async_trait;
pub use common_types::SequenceNumber;
use common_util::runtime::Runtime;
use snafu::ResultExt;
use crate::log_batch::{LogEntry, LogWriteBatch, Payload, PayloadDecoder};
pub mod error {
use common_util::define_result;
use snafu::{Backtrace, Snafu};
use crate::manager::RegionId;
// Now most error from manage implementation don't have backtrace, so we add
// backtrace here.
#[derive(Debug, Snafu)]
#[snafu(visibility(pub))]
pub enum Error {
#[snafu(display(
"Failed to open wal, path:{}, err:{}.\nBacktrace:\n{}",
wal_path,
source,
backtrace
))]
Open {
wal_path: String,
source: Box<dyn std::error::Error + Send + Sync>,
backtrace: Backtrace,
},
#[snafu(display("Failed to initialize wal, err:{}.\nBacktrace:\n{}", source, backtrace))]
Initialization {
source: Box<dyn std::error::Error + Send + Sync>,
backtrace: Backtrace,
},
#[snafu(display(
"Region is not found, region_id:{}.\nBacktrace:\n{}",
region_id,
backtrace
))]
RegionNotFound {
region_id: RegionId,
backtrace: Backtrace,
},
#[snafu(display(
"Failed to write log entries, err:{}.\nBacktrace:\n{}",
source,
backtrace
))]
Write {
source: Box<dyn std::error::Error + Send + Sync>,
backtrace: Backtrace,
},
#[snafu(display(
"Failed to read log entries, err:{}.\nBacktrace:\n{}",
source,
backtrace
))]
Read {
source: Box<dyn std::error::Error + Send + Sync>,
backtrace: Backtrace,
},
#[snafu(display(
"Failed to delete log entries, err:{}.\nBacktrace:\n{}",
source,
backtrace
))]
Delete {
source: Box<dyn std::error::Error + Send + Sync>,
backtrace: Backtrace,
},
#[snafu(display("Failed to encode, err:{}.\nBacktrace:\n{}", source, backtrace))]
Encoding {
source: Box<dyn std::error::Error + Send + Sync>,
backtrace: Backtrace,
},
#[snafu(display("Failed to decode, err:{}.\nBacktrace:\n{}", source, backtrace))]
Decoding {
source: Box<dyn std::error::Error + Send + Sync>,
backtrace: Backtrace,
},
#[snafu(display("Failed to close wal, err:{}.\nBacktrace:\n{}", source, backtrace))]
Close {
source: Box<dyn std::error::Error + Send + Sync>,
backtrace: Backtrace,
},
#[snafu(display("Failed to execute in runtime, err:{}", source))]
RuntimeExec { source: common_util::runtime::Error },
}
define_result!(Error);
}
use common_types::{MAX_SEQUENCE_NUMBER, MIN_SEQUENCE_NUMBER};
pub use error::*;
pub type RegionId = u64;
pub const MAX_REGION_ID: RegionId = u64::MAX;
#[derive(Debug, Clone)]
pub struct WriteContext {
/// Timeout to write wal and it only takes effect when writing to a Wal on a
/// remote machine (writing to the local disk does not have timeout).
pub timeout: Duration,
}
impl Default for WriteContext {
fn default() -> Self {
Self {
timeout: Duration::from_secs(1),
}
}
}
/// Write abstraction for log entries in Wal.
#[async_trait]
pub trait LogWriter {
/// Write a batch of log entries to log.
///
/// Returns the max sequence number for the batch of log entries.
async fn write<P: Payload>(
&self,
ctx: &WriteContext,
batch: &LogWriteBatch<P>,
) -> Result<SequenceNumber>;
}
#[derive(Debug, Clone)]
pub struct ReadContext {
/// Timeout to read log entries and it only takes effect when reading from a
/// Wal on a remote machine (reading from the local disk does not have
/// timeout).
pub timeout: Duration,
/// Batch size to read log entries.
pub batch_size: usize,
}
impl Default for ReadContext {
fn default() -> Self {
Self {
timeout: Duration::from_secs(5),
batch_size: 500,
}
}
}
#[derive(Debug, Clone, Copy)]
pub enum ReadBoundary {
Max,
Min,
Included(SequenceNumber),
Excluded(SequenceNumber),
}
impl ReadBoundary {
/// Convert the boundary to start sequence number.
///
/// Returns `None` if the boundary is `Excluded(MAX_SEQUENCE_NUM)`
pub fn as_start_sequence_number(&self) -> Option<SequenceNumber> {
match *self {
ReadBoundary::Max => Some(MAX_SEQUENCE_NUMBER),
ReadBoundary::Min => Some(MIN_SEQUENCE_NUMBER),
ReadBoundary::Included(n) => Some(n),
ReadBoundary::Excluded(n) => {
if n == MAX_SEQUENCE_NUMBER {
None
} else {
Some(n + 1)
}
}
}
}
/// Convert the boundary to start sequence number.
///
/// Returns `None` if the boundary is `Excluded(MIN_SEQUENCE_NUM)`
pub fn as_end_sequence_number(&self) -> Option<SequenceNumber> {
match *self {
ReadBoundary::Max => Some(MAX_SEQUENCE_NUMBER),
ReadBoundary::Min => Some(MIN_SEQUENCE_NUMBER),
ReadBoundary::Included(n) => Some(n),
ReadBoundary::Excluded(n) => {
if n == MIN_SEQUENCE_NUMBER {
None
} else {
Some(n - 1)
}
}
}
}
}
#[derive(Debug, Clone)]
pub struct ReadRequest {
/// Region id of the wal to read
pub region_id: RegionId,
// TODO(yingwen): Or just rename to ReadBound?
/// Start bound
pub start: ReadBoundary,
/// End bound
pub end: ReadBoundary,
}
/// Blocking Iterator abstraction for log entry.
pub trait BlockingLogIterator {
/// Fetch next log entry from the iterator.
///
/// NOTE that this operation may **BLOCK** caller thread now.
fn next_log_entry<D: PayloadDecoder>(
&mut self,
decoder: &D,
) -> Result<Option<LogEntry<D::Target>>>;
}
/// Vectorwise log entry iterator.
#[async_trait]
pub trait BatchLogIterator {
/// Fetch next batch of log entries from the iterator to the provided
/// `buffer`. This iterator should clear the `buffer` before using it.
///
/// Returns the entries if there are remaining log entries, or empty `Vec`
/// if the iterator is exhausted.
async fn next_log_entries<D: PayloadDecoder + Send + 'static>(
&mut self,
decoder: D,
buffer: VecDeque<LogEntry<D::Target>>,
) -> Result<VecDeque<LogEntry<D::Target>>>;
}
/// Read abstraction for log entries in the Wal.
#[async_trait]
pub trait LogReader {
/// Batch iterator.
type BatchIter: BatchLogIterator + Send;
/// Provide iterator on necessary entries according to `ReadRequest`.
async fn read_batch(&self, ctx: &ReadContext, req: &ReadRequest) -> Result<Self::BatchIter>;
}
// TODO(xikai): define Error as associate type.
/// Management of multi-region Wals.
///
/// Every region has its own increasing (and maybe hallow) sequence number
/// space.
#[async_trait]
pub trait WalManager: LogWriter + LogReader + fmt::Debug {
/// Get current sequence number.
async fn sequence_num(&self, region_id: RegionId) -> Result<SequenceNumber>;
/// Mark the entries whose sequence number is in [0, `sequence_number`] to
/// be deleted in the future.
async fn mark_delete_entries_up_to(
&self,
region_id: RegionId,
sequence_num: SequenceNumber,
) -> Result<()>;
/// Close the wal gracefully.
async fn close_gracefully(&self) -> Result<()>;
}
/// Adapter to convert a blocking interator to a batch async iterator.
pub struct BatchLogIteratorAdapter<I> {
blocking_iter: Option<I>,
runtime: Arc<Runtime>,
batch_size: usize,
}
impl<I: BlockingLogIterator + Send + 'static> BatchLogIteratorAdapter<I> {
pub fn new(blocking_iter: I, runtime: Arc<Runtime>, batch_size: usize) -> Self {
Self {
blocking_iter: Some(blocking_iter),
runtime,
batch_size,
}
}
}
#[async_trait]
impl<I: BlockingLogIterator + Send + 'static> BatchLogIterator for BatchLogIteratorAdapter<I> {
async fn next_log_entries<D: PayloadDecoder + Send + 'static>(
&mut self,
decoder: D,
mut buffer: VecDeque<LogEntry<D::Target>>,
) -> Result<VecDeque<LogEntry<D::Target>>> {
if self.blocking_iter.is_none() {
return Ok(VecDeque::new());
}
buffer.clear();
let mut iter = self.blocking_iter.take().unwrap();
let batch_size = self.batch_size;
let (log_entries, iter) = self
.runtime
.spawn_blocking(move || {
for _ in 0..batch_size {
if let Some(log_entry) = iter.next_log_entry(&decoder)? {
buffer.push_back(log_entry);
} else {
return Ok((buffer, None));
}
}
Ok((buffer, Some(iter)))
})
.await
.context(RuntimeExec)??;
self.blocking_iter = iter;
Ok(log_entries)
}
}