risingwave_hummock_trace/
record.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
// Copyright 2024 RisingWave Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::ops::{Bound, Deref};
use std::sync::atomic::{AtomicU64, Ordering};

use bincode::error::{DecodeError, EncodeError};
use bincode::{Decode, Encode};
use bytes::Bytes;
use prost::Message;
use risingwave_pb::meta::SubscribeResponse;

use crate::{
    LocalStorageId, StorageType, TracedHummockReadEpoch, TracedInitOptions, TracedNewLocalOptions,
    TracedReadOptions, TracedSealCurrentEpochOptions, TracedTryWaitEpochOptions,
};

pub type RecordId = u64;

pub type RecordIdGenerator = UniqueIdGenerator<AtomicU64>;
pub type ConcurrentIdGenerator = UniqueIdGenerator<AtomicU64>;

pub trait UniqueId {
    type Type;
    fn inc(&self) -> Self::Type;
}

impl UniqueId for AtomicU64 {
    type Type = u64;

    fn inc(&self) -> Self::Type {
        self.fetch_add(1, Ordering::Relaxed)
    }
}

pub struct UniqueIdGenerator<T> {
    id: T,
}

impl<T: UniqueId> UniqueIdGenerator<T> {
    pub fn new(id: T) -> Self {
        Self { id }
    }

    pub fn next(&self) -> T::Type {
        self.id.inc()
    }
}

#[derive(Encode, Decode, Debug, PartialEq, Clone)]
pub struct Record {
    pub storage_type: StorageType,
    pub record_id: RecordId,
    pub operation: Operation,
}

impl Record {
    pub fn new(storage_type: StorageType, record_id: RecordId, operation: Operation) -> Self {
        Self {
            storage_type,
            record_id,
            operation,
        }
    }

    pub fn storage_type(&self) -> &StorageType {
        &self.storage_type
    }

    pub fn record_id(&self) -> RecordId {
        self.record_id
    }

    pub fn operation(&self) -> &Operation {
        &self.operation
    }

    pub fn is_iter_related(&self) -> bool {
        matches!(
            self.operation(),
            Operation::Iter { .. } | Operation::IterNext(_)
        )
    }

    #[cfg(test)]
    pub(crate) fn new_local_none(record_id: RecordId, operation: Operation) -> Self {
        Self::new(StorageType::Global, record_id, operation)
    }
}

pub type TracedIterRange = (Bound<TracedBytes>, Bound<TracedBytes>);

/// Operations represents Hummock operations
#[derive(Encode, Decode, PartialEq, Debug, Clone)]
pub enum Operation {
    /// Get operation of Hummock.
    Get {
        /// Key to retrieve.
        key: TracedBytes,
        /// Optional epoch value.
        epoch: Option<u64>,
        /// Read options for the operation.
        read_options: TracedReadOptions,
    },

    /// Insert operation of Hummock.
    Insert {
        /// Key to insert.
        key: TracedBytes,
        /// New value to insert.
        new_val: TracedBytes,
        /// Optional old value to replace.
        old_val: Option<TracedBytes>,
    },

    /// Delete operation of Hummock.
    Delete {
        /// Key to delete.
        key: TracedBytes,
        /// Value to match for deletion.
        old_val: TracedBytes,
    },

    /// Iter operation of Hummock.
    Iter {
        /// Key range for iteration.
        key_range: TracedIterRange,
        /// Optional epoch value.
        epoch: Option<u64>,
        /// Read options for the operation.
        read_options: TracedReadOptions,
    },

    /// Iter.next operation of Hummock.
    IterNext(RecordId),

    /// Sync operation of Hummock.
    Sync(Vec<(u64, Vec<u32>)>),

    /// `MetaMessage` operation of Hummock.
    MetaMessage(Box<TracedSubResp>),

    /// Result operation of Hummock.
    Result(OperationResult),

    /// `NewLocalStorage` operation of Hummock.
    NewLocalStorage(TracedNewLocalOptions, LocalStorageId),

    /// `DropLocalStorage` operation of Hummock.
    DropLocalStorage,

    /// Init of a local storage
    LocalStorageInit(TracedInitOptions),

    /// Try wait epoch
    TryWaitEpoch(TracedHummockReadEpoch, TracedTryWaitEpochOptions),

    /// Seal current epoch
    SealCurrentEpoch {
        epoch: u64,
        opts: TracedSealCurrentEpochOptions,
    },

    LocalStorageEpoch,

    LocalStorageIsDirty,

    TryFlush,

    Flush,
    /// Finish operation of Hummock.
    Finish,
}

impl Operation {
    pub fn get(key: Bytes, epoch: Option<u64>, read_options: TracedReadOptions) -> Operation {
        Operation::Get {
            key: key.into(),
            epoch,
            read_options,
        }
    }

    pub fn insert(key: Bytes, new_val: Bytes, old_val: Option<Bytes>) -> Operation {
        Operation::Insert {
            key: key.into(),
            new_val: new_val.into(),
            old_val: old_val.map(|v| v.into()),
        }
    }
}

#[derive(PartialEq, Eq, Debug, Clone)]
pub struct TracedBytes(Bytes);

impl Deref for TracedBytes {
    type Target = Bytes;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Encode for TracedBytes {
    fn encode<E: bincode::enc::Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
        Encode::encode(&self.0.as_ref(), encoder)
    }
}

impl Decode for TracedBytes {
    fn decode<D: bincode::de::Decoder>(
        decoder: &mut D,
    ) -> Result<Self, bincode::error::DecodeError> {
        let buf: Vec<u8> = Decode::decode(decoder)?;
        let bytes = Bytes::from(buf);
        Ok(Self(bytes))
    }
}

impl<'de> bincode::BorrowDecode<'de> for TracedBytes {
    fn borrow_decode<D: bincode::de::BorrowDecoder<'de>>(
        decoder: &mut D,
    ) -> core::result::Result<Self, bincode::error::DecodeError> {
        let buf: Vec<u8> = Decode::decode(decoder)?;
        let bytes = Bytes::from(buf);
        Ok(Self(bytes))
    }
}

impl From<Vec<u8>> for TracedBytes {
    fn from(value: Vec<u8>) -> Self {
        Self(Bytes::from(value))
    }
}

impl From<Bytes> for TracedBytes {
    fn from(value: Bytes) -> Self {
        Self(value)
    }
}

impl From<TracedBytes> for Bytes {
    fn from(value: TracedBytes) -> Self {
        value.0
    }
}
/// `TraceResult` discards Error and only traces whether succeeded or not.
/// Use Option rather than Result because it's overhead to serialize Error.
#[derive(Encode, Decode, PartialEq, Eq, Debug, Clone)]
pub enum TraceResult<T> {
    Ok(T),
    Err,
}

impl<T> TraceResult<T> {
    pub fn is_ok(&self) -> bool {
        matches!(*self, Self::Ok(_))
    }
}

impl<T, E> From<std::result::Result<T, E>> for TraceResult<T> {
    fn from(value: std::result::Result<T, E>) -> Self {
        match value {
            Ok(v) => Self::Ok(v),
            Err(_) => Self::Err, // discard error
        }
    }
}

#[derive(Encode, Decode, PartialEq, Eq, Debug, Clone)]
pub enum OperationResult {
    Get(TraceResult<Option<TracedBytes>>),
    Insert(TraceResult<()>),
    Delete(TraceResult<()>),
    TryFlush(TraceResult<()>),
    Flush(TraceResult<usize>),
    Iter(TraceResult<()>),
    IterNext(TraceResult<Option<(TracedBytes, TracedBytes)>>),
    Sync(TraceResult<usize>),
    NotifyHummock(TraceResult<()>),
    TryWaitEpoch(TraceResult<()>),
    LocalStorageEpoch(TraceResult<u64>),
    LocalStorageIsDirty(TraceResult<bool>),
}

#[derive(PartialEq, Debug, Clone)]
pub struct TracedSubResp(pub SubscribeResponse);

impl Encode for TracedSubResp {
    fn encode<E: bincode::enc::Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
        // SubscribeResponse and its implementation of Serialize is generated
        // by prost and pbjson for protobuf mapping.
        // Serialization methods like Bincode may not correctly serialize it.
        // So we use prost::Message::encode
        let mut buf = vec![];
        self.0
            .encode(&mut buf)
            .map_err(|_| EncodeError::Other("failed to encode subscribeResponse"))?;
        Encode::encode(&buf, encoder)
    }
}

impl Decode for TracedSubResp {
    fn decode<D: bincode::de::Decoder>(
        decoder: &mut D,
    ) -> Result<Self, bincode::error::DecodeError> {
        let buf: Vec<u8> = Decode::decode(decoder)?;
        let resp = Message::decode(&buf[..]).map_err(|_| {
            DecodeError::OtherString("failed to decode subscribeResponse".to_string())
        })?;
        Ok(Self(resp))
    }
}

impl<'de> bincode::BorrowDecode<'de> for TracedSubResp {
    fn borrow_decode<D: bincode::de::BorrowDecoder<'de>>(
        decoder: &mut D,
    ) -> core::result::Result<Self, bincode::error::DecodeError> {
        let buf: Vec<u8> = Decode::decode(decoder)?;
        let resp = Message::decode(&buf[..]).map_err(|_| {
            DecodeError::OtherString("failed to decode subscribeResponse".to_string())
        })?;
        Ok(Self(resp))
    }
}

impl From<SubscribeResponse> for TracedSubResp {
    fn from(value: SubscribeResponse) -> Self {
        Self(value)
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;
    use std::sync::Arc;

    use parking_lot::Mutex;

    use super::*;

    // test atomic id
    #[tokio::test(flavor = "multi_thread")]
    async fn test_atomic_id() {
        let gen = Arc::new(UniqueIdGenerator::new(AtomicU64::new(0)));
        let mut handles = Vec::new();
        let ids_lock = Arc::new(Mutex::new(HashSet::new()));
        let count: u64 = 5000;

        for _ in 0..count {
            let ids = ids_lock.clone();
            let gen = gen.clone();
            handles.push(tokio::spawn(async move {
                let id = gen.next();
                ids.lock().insert(id);
            }));
        }

        for handle in handles {
            handle.await.unwrap();
        }

        let ids = ids_lock.lock();

        for i in 0..count {
            assert!(ids.contains(&i));
        }
    }

    #[test]
    fn test_record_is_iter_related() {
        let iter_operation = Operation::Iter {
            key_range: (Bound::Unbounded, Bound::Unbounded),
            epoch: None,
            read_options: TracedReadOptions::for_test(0),
        };
        let get_operation = Operation::Get {
            key: TracedBytes(Bytes::from("test")),
            epoch: None,
            read_options: TracedReadOptions::for_test(0),
        };

        let iter_record = Record::new(StorageType::Global, 1, iter_operation);
        let get_record = Record::new(StorageType::Global, 2, get_operation);

        assert!(iter_record.is_iter_related());
        assert!(!get_record.is_iter_related());
    }
}