1use std::borrow::Borrow;
16use std::cmp::Ordering;
17use std::fmt::Debug;
18use std::iter::once;
19use std::ops::Bound::*;
20use std::ops::{Bound, Deref, DerefMut, RangeBounds};
21use std::ptr;
22
23use bytes::{Buf, BufMut, Bytes, BytesMut};
24use risingwave_common::catalog::TableId;
25use risingwave_common::hash::VirtualNode;
26use risingwave_common_estimate_size::EstimateSize;
27
28use crate::{EpochWithGap, HummockEpoch};
29
30pub const EPOCH_LEN: usize = std::mem::size_of::<HummockEpoch>();
31pub const TABLE_PREFIX_LEN: usize = std::mem::size_of::<u32>();
32pub const MAX_KEY_LEN: usize = u16::MAX as usize;
34
35pub type KeyPayloadType = Bytes;
36pub type TableKeyRange = (
37 Bound<TableKey<KeyPayloadType>>,
38 Bound<TableKey<KeyPayloadType>>,
39);
40pub type UserKeyRange = (
41 Bound<UserKey<KeyPayloadType>>,
42 Bound<UserKey<KeyPayloadType>>,
43);
44pub type UserKeyRangeRef<'a> = (Bound<UserKey<&'a [u8]>>, Bound<UserKey<&'a [u8]>>);
45pub type FullKeyRange = (
46 Bound<FullKey<KeyPayloadType>>,
47 Bound<FullKey<KeyPayloadType>>,
48);
49
50pub fn is_empty_key_range(key_range: &TableKeyRange) -> bool {
51 match key_range {
52 (Included(start), Excluded(end)) => start == end,
53 _ => false,
54 }
55}
56
57pub fn vnode_range(range: &TableKeyRange) -> (usize, usize) {
67 let (left, right) = range;
68 let left = match left {
69 Included(key) | Excluded(key) => key.vnode_part().to_index(),
70 Unbounded => 0,
71 };
72 let right = match right {
73 Included(key) => key.vnode_part().to_index() + 1,
74 Excluded(key) => {
75 let (vnode, inner_key) = key.split_vnode();
76 if inner_key.is_empty() {
77 vnode.to_index()
80 } else {
81 vnode.to_index() + 1
82 }
83 }
84 Unbounded => VirtualNode::MAX_REPRESENTABLE.to_index() + 1,
85 };
86 (left, right)
87}
88
89pub fn vnode(range: &TableKeyRange) -> VirtualNode {
99 let (l, r_exclusive) = vnode_range(range);
100 assert_eq!(r_exclusive - l, 1);
101 VirtualNode::from_index(l)
102}
103
104pub fn key_with_epoch(mut user_key: Vec<u8>, epoch: HummockEpoch) -> Vec<u8> {
106 let res = epoch.to_be();
107 user_key.reserve(EPOCH_LEN);
108 let buf = user_key.chunk_mut();
109
110 unsafe {
112 ptr::copy_nonoverlapping(
113 &res as *const _ as *const u8,
114 buf.as_mut_ptr() as *mut _,
115 EPOCH_LEN,
116 );
117 user_key.advance_mut(EPOCH_LEN);
118 }
119
120 user_key
121}
122
123#[inline]
125pub fn split_key_epoch(full_key: &[u8]) -> (&[u8], &[u8]) {
126 let pos = full_key
127 .len()
128 .checked_sub(EPOCH_LEN)
129 .unwrap_or_else(|| panic!("bad full key format: {:?}", full_key));
130 full_key.split_at(pos)
131}
132
133pub fn user_key(full_key: &[u8]) -> &[u8] {
135 split_key_epoch(full_key).0
136}
137
138pub fn table_key(user_key: &[u8]) -> &[u8] {
140 &user_key[TABLE_PREFIX_LEN..]
141}
142
143#[inline(always)]
144pub fn get_user_key(full_key: &[u8]) -> Vec<u8> {
146 if full_key.is_empty() {
147 vec![]
148 } else {
149 user_key(full_key).to_vec()
150 }
151}
152
153#[inline(always)]
155pub fn get_table_id(full_key: &[u8]) -> u32 {
156 let mut buf = full_key;
157 buf.get_u32()
158}
159
160pub fn next_key(key: &[u8]) -> Vec<u8> {
179 if let Some((s, e)) = next_key_no_alloc(key) {
180 let mut res = Vec::with_capacity(s.len() + 1);
181 res.extend_from_slice(s);
182 res.push(e);
183 res
184 } else {
185 Vec::new()
186 }
187}
188
189pub fn prev_key(key: &[u8]) -> Vec<u8> {
206 let pos = key.iter().rposition(|b| *b != 0x00);
207 match pos {
208 Some(pos) => {
209 let mut res = Vec::with_capacity(key.len());
210 res.extend_from_slice(&key[0..pos]);
211 res.push(key[pos] - 1);
212 if pos + 1 < key.len() {
213 res.push(b"\xff".to_owned()[0]);
214 }
215 res
216 }
217 None => {
218 vec![0xff; key.len()]
219 }
220 }
221}
222
223fn next_key_no_alloc(key: &[u8]) -> Option<(&[u8], u8)> {
224 let pos = key.iter().rposition(|b| *b != 0xff)?;
225 Some((&key[..pos], key[pos] + 1))
226}
227
228pub fn next_epoch(epoch: &[u8]) -> Vec<u8> {
243 let pos = epoch.iter().rposition(|b| *b != 0xff);
244 match pos {
245 Some(mut pos) => {
246 let mut res = Vec::with_capacity(epoch.len());
247 res.extend_from_slice(&epoch[0..pos]);
248 res.push(epoch[pos] + 1);
249 while pos + 1 < epoch.len() {
250 res.push(0x00);
251 pos += 1;
252 }
253 res
254 }
255 None => {
256 vec![0x00; epoch.len()]
257 }
258 }
259}
260
261pub fn prev_epoch(epoch: &[u8]) -> Vec<u8> {
274 let pos = epoch.iter().rposition(|b| *b != 0x00);
275 match pos {
276 Some(mut pos) => {
277 let mut res = Vec::with_capacity(epoch.len());
278 res.extend_from_slice(&epoch[0..pos]);
279 res.push(epoch[pos] - 1);
280 while pos + 1 < epoch.len() {
281 res.push(0xff);
282 pos += 1;
283 }
284 res
285 }
286 None => {
287 vec![0xff; epoch.len()]
288 }
289 }
290}
291
292pub fn next_full_key(full_key: &[u8]) -> Vec<u8> {
296 let (user_key, epoch) = split_key_epoch(full_key);
297 let prev_epoch = prev_epoch(epoch);
298 let mut res = Vec::with_capacity(full_key.len());
299 if prev_epoch.cmp(&vec![0xff; prev_epoch.len()]) == Ordering::Equal {
300 let next_user_key = next_key(user_key);
301 if next_user_key.is_empty() {
302 return Vec::new();
303 }
304 res.extend_from_slice(next_user_key.as_slice());
305 res.extend_from_slice(prev_epoch.as_slice());
306 res
307 } else {
308 res.extend_from_slice(user_key);
309 res.extend_from_slice(prev_epoch.as_slice());
310 res
311 }
312}
313
314pub fn prev_full_key(full_key: &[u8]) -> Vec<u8> {
318 let (user_key, epoch) = split_key_epoch(full_key);
319 let next_epoch = next_epoch(epoch);
320 let mut res = Vec::with_capacity(full_key.len());
321 if next_epoch.cmp(&vec![0x00; next_epoch.len()]) == Ordering::Equal {
322 let prev_user_key = prev_key(user_key);
323 if prev_user_key.cmp(&vec![0xff; prev_user_key.len()]) == Ordering::Equal {
324 return Vec::new();
325 }
326 res.extend_from_slice(prev_user_key.as_slice());
327 res.extend_from_slice(next_epoch.as_slice());
328 res
329 } else {
330 res.extend_from_slice(user_key);
331 res.extend_from_slice(next_epoch.as_slice());
332 res
333 }
334}
335
336pub fn end_bound_of_vnode(vnode: VirtualNode) -> Bound<Bytes> {
344 if vnode == VirtualNode::MAX_REPRESENTABLE {
345 Unbounded
346 } else {
347 let end_bound_index = vnode.to_index() + 1;
348 Excluded(Bytes::copy_from_slice(
349 &VirtualNode::from_index(end_bound_index).to_be_bytes(),
350 ))
351 }
352}
353
354pub fn end_bound_of_prefix(prefix: &[u8]) -> Bound<Bytes> {
356 if let Some((s, e)) = next_key_no_alloc(prefix) {
357 let mut buf = BytesMut::with_capacity(s.len() + 1);
358 buf.extend_from_slice(s);
359 buf.put_u8(e);
360 Excluded(buf.freeze())
361 } else {
362 Unbounded
363 }
364}
365
366pub fn start_bound_of_excluded_prefix(prefix: &[u8]) -> Bound<Bytes> {
368 if let Some((s, e)) = next_key_no_alloc(prefix) {
369 let mut buf = BytesMut::with_capacity(s.len() + 1);
370 buf.extend_from_slice(s);
371 buf.put_u8(e);
372 Included(buf.freeze())
373 } else {
374 panic!("the prefix is the maximum value")
375 }
376}
377
378pub fn range_of_prefix(prefix: &[u8]) -> (Bound<Bytes>, Bound<Bytes>) {
380 if prefix.is_empty() {
381 (Unbounded, Unbounded)
382 } else {
383 (
384 Included(Bytes::copy_from_slice(prefix)),
385 end_bound_of_prefix(prefix),
386 )
387 }
388}
389
390pub fn prefix_slice_with_vnode(vnode: VirtualNode, slice: &[u8]) -> Bytes {
391 let prefix = vnode.to_be_bytes();
392 let mut buf = BytesMut::with_capacity(prefix.len() + slice.len());
393 buf.extend_from_slice(&prefix);
394 buf.extend_from_slice(slice);
395 buf.freeze()
396}
397
398pub fn prefixed_range_with_vnode<B: AsRef<[u8]>>(
400 range: impl RangeBounds<B>,
401 vnode: VirtualNode,
402) -> TableKeyRange {
403 let prefixed = |b: &B| -> Bytes { prefix_slice_with_vnode(vnode, b.as_ref()) };
404
405 let start: Bound<Bytes> = match range.start_bound() {
406 Included(b) => Included(prefixed(b)),
407 Excluded(b) => {
408 assert!(!b.as_ref().is_empty());
409 Excluded(prefixed(b))
410 }
411 Unbounded => Included(Bytes::copy_from_slice(&vnode.to_be_bytes())),
412 };
413
414 let end = match range.end_bound() {
415 Included(b) => Included(prefixed(b)),
416 Excluded(b) => {
417 assert!(!b.as_ref().is_empty());
418 Excluded(prefixed(b))
419 }
420 Unbounded => end_bound_of_vnode(vnode),
421 };
422
423 map_table_key_range((start, end))
424}
425
426pub trait SetSlice<S: AsRef<[u8]> + ?Sized> {
427 fn set(&mut self, value: &S);
428}
429
430impl<S: AsRef<[u8]> + ?Sized> SetSlice<S> for Vec<u8> {
431 fn set(&mut self, value: &S) {
432 self.clear();
433 self.extend_from_slice(value.as_ref());
434 }
435}
436
437impl SetSlice<Bytes> for Bytes {
438 fn set(&mut self, value: &Bytes) {
439 *self = value.clone()
440 }
441}
442
443pub trait CopyFromSlice: Send + 'static {
444 fn copy_from_slice(slice: &[u8]) -> Self;
445}
446
447impl CopyFromSlice for Vec<u8> {
448 fn copy_from_slice(slice: &[u8]) -> Self {
449 Vec::from(slice)
450 }
451}
452
453impl CopyFromSlice for Bytes {
454 fn copy_from_slice(slice: &[u8]) -> Self {
455 Bytes::copy_from_slice(slice)
456 }
457}
458
459impl CopyFromSlice for () {
460 fn copy_from_slice(_: &[u8]) -> Self {}
461}
462
463#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
469pub struct TableKey<T: AsRef<[u8]>>(pub T);
470
471impl<T: AsRef<[u8]>> Debug for TableKey<T> {
472 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
473 write!(f, "TableKey {{ {} }}", hex::encode(self.0.as_ref()))
474 }
475}
476
477impl<T: AsRef<[u8]>> Deref for TableKey<T> {
478 type Target = T;
479
480 fn deref(&self) -> &Self::Target {
481 &self.0
482 }
483}
484
485impl<T: AsRef<[u8]>> DerefMut for TableKey<T> {
486 fn deref_mut(&mut self) -> &mut Self::Target {
487 &mut self.0
488 }
489}
490
491impl<T: AsRef<[u8]>> AsRef<[u8]> for TableKey<T> {
492 fn as_ref(&self) -> &[u8] {
493 self.0.as_ref()
494 }
495}
496
497impl TableKey<Bytes> {
498 pub fn split_vnode_bytes(&self) -> (VirtualNode, Bytes) {
499 debug_assert!(
500 self.0.len() >= VirtualNode::SIZE,
501 "too short table key: {:?}",
502 self.0.as_ref()
503 );
504 let (vnode, _) = self.0.split_first_chunk::<{ VirtualNode::SIZE }>().unwrap();
505 (
506 VirtualNode::from_be_bytes(*vnode),
507 self.0.slice(VirtualNode::SIZE..),
508 )
509 }
510}
511
512impl<T: AsRef<[u8]>> TableKey<T> {
513 pub fn split_vnode(&self) -> (VirtualNode, &[u8]) {
514 debug_assert!(
515 self.0.as_ref().len() >= VirtualNode::SIZE,
516 "too short table key: {:?}",
517 self.0.as_ref()
518 );
519 let (vnode, inner_key) = self
520 .0
521 .as_ref()
522 .split_first_chunk::<{ VirtualNode::SIZE }>()
523 .unwrap();
524 (VirtualNode::from_be_bytes(*vnode), inner_key)
525 }
526
527 pub fn vnode_part(&self) -> VirtualNode {
528 self.split_vnode().0
529 }
530
531 pub fn key_part(&self) -> &[u8] {
532 self.split_vnode().1
533 }
534
535 pub fn to_ref(&self) -> TableKey<&[u8]> {
536 TableKey(self.0.as_ref())
537 }
538}
539
540impl<T: AsRef<[u8]>> Borrow<[u8]> for TableKey<T> {
541 fn borrow(&self) -> &[u8] {
542 self.0.as_ref()
543 }
544}
545
546impl EstimateSize for TableKey<Bytes> {
547 fn estimated_heap_size(&self) -> usize {
548 self.0.estimated_heap_size()
549 }
550}
551
552impl TableKey<&[u8]> {
553 pub fn copy_into<T: CopyFromSlice + AsRef<[u8]>>(&self) -> TableKey<T> {
554 TableKey(T::copy_from_slice(self.as_ref()))
555 }
556}
557
558#[inline]
559pub fn map_table_key_range(range: (Bound<KeyPayloadType>, Bound<KeyPayloadType>)) -> TableKeyRange {
560 (range.0.map(TableKey), range.1.map(TableKey))
561}
562
563pub fn gen_key_from_bytes(vnode: VirtualNode, payload: &[u8]) -> TableKey<Bytes> {
564 TableKey(Bytes::from(
565 [vnode.to_be_bytes().as_slice(), payload].concat(),
566 ))
567}
568
569pub fn gen_key_from_str(vnode: VirtualNode, payload: &str) -> TableKey<Bytes> {
570 gen_key_from_bytes(vnode, payload.as_bytes())
571}
572
573#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
579pub struct UserKey<T: AsRef<[u8]>> {
580 pub table_id: TableId,
583 pub table_key: TableKey<T>,
584}
585
586impl<T: AsRef<[u8]>> Debug for UserKey<T> {
587 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
588 write!(f, "UserKey {{ {}, {:?} }}", self.table_id, self.table_key)
589 }
590}
591
592impl<T: AsRef<[u8]>> UserKey<T> {
593 pub fn new(table_id: TableId, table_key: TableKey<T>) -> Self {
594 Self {
595 table_id,
596 table_key,
597 }
598 }
599
600 pub fn for_test(table_id: TableId, table_key: T) -> Self {
602 Self {
603 table_id,
604 table_key: TableKey(table_key),
605 }
606 }
607
608 pub fn encode_into(&self, buf: &mut impl BufMut) {
610 buf.put_u32(self.table_id.as_raw_id());
611 buf.put_slice(self.table_key.as_ref());
612 }
613
614 pub fn encode_table_key_into(&self, buf: &mut impl BufMut) {
615 buf.put_slice(self.table_key.as_ref());
616 }
617
618 pub fn encode(&self) -> Vec<u8> {
619 let mut ret = Vec::with_capacity(TABLE_PREFIX_LEN + self.table_key.as_ref().len());
620 self.encode_into(&mut ret);
621 ret
622 }
623
624 pub fn is_empty(&self) -> bool {
625 self.table_key.as_ref().is_empty()
626 }
627
628 pub fn encoded_len(&self) -> usize {
630 self.table_key.as_ref().len() + TABLE_PREFIX_LEN
631 }
632
633 pub fn get_vnode_id(&self) -> usize {
634 self.table_key.vnode_part().to_index()
635 }
636}
637
638impl<'a> UserKey<&'a [u8]> {
639 pub fn decode(slice: &'a [u8]) -> Self {
642 let table_id: u32 = (&slice[..]).get_u32();
643
644 Self {
645 table_id: TableId::new(table_id),
646 table_key: TableKey(&slice[TABLE_PREFIX_LEN..]),
647 }
648 }
649
650 pub fn to_vec(self) -> UserKey<Vec<u8>> {
651 self.copy_into()
652 }
653
654 pub fn copy_into<T: CopyFromSlice + AsRef<[u8]>>(self) -> UserKey<T> {
655 UserKey {
656 table_id: self.table_id,
657 table_key: TableKey(T::copy_from_slice(self.table_key.0)),
658 }
659 }
660}
661
662impl<T: AsRef<[u8]> + Clone> UserKey<&T> {
663 pub fn cloned(self) -> UserKey<T> {
664 UserKey {
665 table_id: self.table_id,
666 table_key: TableKey(self.table_key.0.clone()),
667 }
668 }
669}
670
671impl<T: AsRef<[u8]>> UserKey<T> {
672 pub fn as_ref(&self) -> UserKey<&[u8]> {
673 UserKey::new(self.table_id, TableKey(self.table_key.as_ref()))
674 }
675}
676
677impl<T: AsRef<[u8]>> UserKey<T> {
678 pub fn set<F>(&mut self, other: UserKey<F>)
681 where
682 T: SetSlice<F>,
683 F: AsRef<[u8]>,
684 {
685 self.table_id = other.table_id;
686 self.table_key.0.set(&other.table_key.0);
687 }
688}
689
690impl UserKey<Vec<u8>> {
691 pub fn into_bytes(self) -> UserKey<Bytes> {
692 UserKey {
693 table_id: self.table_id,
694 table_key: TableKey(Bytes::from(self.table_key.0)),
695 }
696 }
697}
698
699#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
703pub struct FullKey<T: AsRef<[u8]>> {
704 pub user_key: UserKey<T>,
705 pub epoch_with_gap: EpochWithGap,
706}
707
708impl<T: AsRef<[u8]>> Debug for FullKey<T> {
709 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
710 write!(
711 f,
712 "FullKey {{ {:?}, epoch: {}, epoch_with_gap: {}, spill_offset: {}}}",
713 self.user_key,
714 self.epoch_with_gap.pure_epoch(),
715 self.epoch_with_gap.as_u64(),
716 self.epoch_with_gap.as_u64() - self.epoch_with_gap.pure_epoch(),
717 )
718 }
719}
720
721impl<T: AsRef<[u8]>> FullKey<T> {
722 pub fn new(table_id: TableId, table_key: TableKey<T>, epoch: HummockEpoch) -> Self {
723 Self {
724 user_key: UserKey::new(table_id, table_key),
725 epoch_with_gap: EpochWithGap::new(epoch, 0),
726 }
727 }
728
729 pub fn new_with_gap_epoch(
730 table_id: TableId,
731 table_key: TableKey<T>,
732 epoch_with_gap: EpochWithGap,
733 ) -> Self {
734 Self {
735 user_key: UserKey::new(table_id, table_key),
736 epoch_with_gap,
737 }
738 }
739
740 pub fn from_user_key(user_key: UserKey<T>, epoch: HummockEpoch) -> Self {
741 Self {
742 user_key,
743 epoch_with_gap: EpochWithGap::new_from_epoch(epoch),
744 }
745 }
746
747 pub fn for_test(table_id: TableId, table_key: T, epoch: HummockEpoch) -> Self {
749 Self {
750 user_key: UserKey::for_test(table_id, table_key),
751 epoch_with_gap: EpochWithGap::new(epoch, 0),
752 }
753 }
754
755 pub fn encode_into(&self, buf: &mut impl BufMut) {
757 self.user_key.encode_into(buf);
758 buf.put_u64(self.epoch_with_gap.as_u64());
759 }
760
761 pub fn encode(&self) -> Vec<u8> {
762 let mut buf = Vec::with_capacity(
763 TABLE_PREFIX_LEN + self.user_key.table_key.as_ref().len() + EPOCH_LEN,
764 );
765 self.encode_into(&mut buf);
766 buf
767 }
768
769 pub fn encode_reverse_epoch(&self) -> Vec<u8> {
770 let mut buf = Vec::with_capacity(
771 TABLE_PREFIX_LEN + self.user_key.table_key.as_ref().len() + EPOCH_LEN,
772 );
773 self.user_key.encode_into(&mut buf);
774 buf.put_u64(u64::MAX - self.epoch_with_gap.as_u64());
775 buf
776 }
777
778 pub fn is_empty(&self) -> bool {
779 self.user_key.is_empty()
780 }
781
782 pub fn encoded_len(&self) -> usize {
784 self.user_key.encoded_len() + EPOCH_LEN
785 }
786}
787
788impl<'a> FullKey<&'a [u8]> {
789 pub fn decode(slice: &'a [u8]) -> Self {
791 let epoch_pos = slice.len() - EPOCH_LEN;
792 let epoch = (&slice[epoch_pos..]).get_u64();
793
794 Self {
795 user_key: UserKey::decode(&slice[..epoch_pos]),
796 epoch_with_gap: EpochWithGap::from_u64(epoch),
797 }
798 }
799
800 pub fn from_slice_without_table_id(
802 table_id: TableId,
803 slice_without_table_id: &'a [u8],
804 ) -> Self {
805 let epoch_pos = slice_without_table_id.len() - EPOCH_LEN;
806 let epoch = (&slice_without_table_id[epoch_pos..]).get_u64();
807
808 Self {
809 user_key: UserKey::new(table_id, TableKey(&slice_without_table_id[..epoch_pos])),
810 epoch_with_gap: EpochWithGap::from_u64(epoch),
811 }
812 }
813
814 pub fn decode_reverse_epoch(slice: &'a [u8]) -> Self {
816 let epoch_pos = slice.len() - EPOCH_LEN;
817 let epoch = (&slice[epoch_pos..]).get_u64();
818
819 Self {
820 user_key: UserKey::decode(&slice[..epoch_pos]),
821 epoch_with_gap: EpochWithGap::from_u64(u64::MAX - epoch),
822 }
823 }
824
825 pub fn to_vec(self) -> FullKey<Vec<u8>> {
826 self.copy_into()
827 }
828
829 pub fn copy_into<T: CopyFromSlice + AsRef<[u8]>>(self) -> FullKey<T> {
830 FullKey {
831 user_key: self.user_key.copy_into(),
832 epoch_with_gap: self.epoch_with_gap,
833 }
834 }
835}
836
837impl FullKey<Vec<u8>> {
838 pub fn into_bytes(self) -> FullKey<Bytes> {
841 FullKey {
842 epoch_with_gap: self.epoch_with_gap,
843 user_key: self.user_key.into_bytes(),
844 }
845 }
846}
847
848impl<T: AsRef<[u8]>> FullKey<T> {
849 pub fn to_ref(&self) -> FullKey<&[u8]> {
850 FullKey {
851 user_key: self.user_key.as_ref(),
852 epoch_with_gap: self.epoch_with_gap,
853 }
854 }
855}
856
857impl<T: AsRef<[u8]>> FullKey<T> {
858 pub fn set<F>(&mut self, other: FullKey<F>)
861 where
862 T: SetSlice<F>,
863 F: AsRef<[u8]>,
864 {
865 self.user_key.set(other.user_key);
866 self.epoch_with_gap = other.epoch_with_gap;
867 }
868}
869
870impl<T: AsRef<[u8]> + Ord + Eq> Ord for FullKey<T> {
871 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
872 self.user_key
874 .cmp(&other.user_key)
875 .then_with(|| other.epoch_with_gap.cmp(&self.epoch_with_gap))
876 }
877}
878
879impl<T: AsRef<[u8]> + Ord + Eq> PartialOrd for FullKey<T> {
880 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
881 Some(self.cmp(other))
882 }
883}
884
885pub mod range_delete_backward_compatibility_serde_struct {
886 use bytes::{Buf, BufMut};
887 use risingwave_common::catalog::TableId;
888 use serde::{Deserialize, Serialize};
889
890 #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
891 pub struct TableKey(Vec<u8>);
892
893 #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
894 #[serde(from = "UserKeySerde", into = "UserKeySerde")]
895 pub struct UserKey {
896 pub table_id: TableId,
899 pub table_key: TableKey,
900 }
901
902 #[derive(Deserialize, Serialize)]
903 pub struct TableIdSerde {
904 table_id: u32,
905 }
906
907 #[derive(Deserialize, Serialize)]
908 struct UserKeySerde {
909 table_id: TableIdSerde,
910 table_key: TableKey,
911 }
912
913 impl From<UserKeySerde> for UserKey {
914 fn from(value: UserKeySerde) -> Self {
915 Self {
916 table_id: TableId::new(value.table_id.table_id),
917 table_key: value.table_key,
918 }
919 }
920 }
921
922 impl From<UserKey> for UserKeySerde {
923 fn from(value: UserKey) -> Self {
924 Self {
925 table_id: TableIdSerde {
926 table_id: value.table_id.as_raw_id(),
927 },
928 table_key: value.table_key,
929 }
930 }
931 }
932
933 impl UserKey {
934 pub fn decode_length_prefixed(buf: &mut &[u8]) -> Self {
935 let table_id = buf.get_u32();
936 let len = buf.get_u32() as usize;
937 let data = buf[..len].to_vec();
938 buf.advance(len);
939 UserKey {
940 table_id: TableId::new(table_id),
941 table_key: TableKey(data),
942 }
943 }
944
945 pub fn encode_length_prefixed(&self, mut buf: impl BufMut) {
946 buf.put_u32(self.table_id.as_raw_id());
947 buf.put_u32(self.table_key.0.as_slice().len() as u32);
948 buf.put_slice(self.table_key.0.as_slice());
949 }
950 }
951
952 #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
953 pub struct PointRange {
954 pub left_user_key: UserKey,
957 pub is_exclude_left_key: bool,
961 }
962}
963
964pub trait EmptySliceRef {
965 fn empty_slice_ref<'a>() -> &'a Self;
966}
967
968static EMPTY_BYTES: Bytes = Bytes::new();
969impl EmptySliceRef for Bytes {
970 fn empty_slice_ref<'a>() -> &'a Self {
971 &EMPTY_BYTES
972 }
973}
974
975static EMPTY_VEC: Vec<u8> = Vec::new();
976impl EmptySliceRef for Vec<u8> {
977 fn empty_slice_ref<'a>() -> &'a Self {
978 &EMPTY_VEC
979 }
980}
981
982const EMPTY_SLICE: &[u8] = b"";
983impl EmptySliceRef for &[u8] {
984 fn empty_slice_ref<'b>() -> &'b Self {
985 &EMPTY_SLICE
986 }
987}
988
989pub fn bound_table_key_range<T: AsRef<[u8]> + EmptySliceRef>(
991 table_id: TableId,
992 table_key_range: &impl RangeBounds<TableKey<T>>,
993) -> (Bound<UserKey<&T>>, Bound<UserKey<&T>>) {
994 let start = match table_key_range.start_bound() {
995 Included(b) => Included(UserKey::new(table_id, TableKey(&b.0))),
996 Excluded(b) => Excluded(UserKey::new(table_id, TableKey(&b.0))),
997 Unbounded => Included(UserKey::new(table_id, TableKey(T::empty_slice_ref()))),
998 };
999
1000 let end = match table_key_range.end_bound() {
1001 Included(b) => Included(UserKey::new(table_id, TableKey(&b.0))),
1002 Excluded(b) => Excluded(UserKey::new(table_id, TableKey(&b.0))),
1003 Unbounded => {
1004 if let Some(next_table_id) = table_id.as_raw_id().checked_add(1) {
1005 Excluded(UserKey::new(
1006 next_table_id.into(),
1007 TableKey(T::empty_slice_ref()),
1008 ))
1009 } else {
1010 Unbounded
1011 }
1012 }
1013 };
1014
1015 (start, end)
1016}
1017
1018pub struct FullKeyTracker<T: AsRef<[u8]> + Ord + Eq, const SKIP_DEDUP: bool = false> {
1020 pub latest_full_key: FullKey<T>,
1021 last_observed_epoch_with_gap: EpochWithGap,
1022}
1023
1024impl<T: AsRef<[u8]> + Ord + Eq, const SKIP_DEDUP: bool> FullKeyTracker<T, SKIP_DEDUP> {
1025 pub fn new(init_full_key: FullKey<T>) -> Self {
1026 let epoch_with_gap = init_full_key.epoch_with_gap;
1027 Self {
1028 latest_full_key: init_full_key,
1029 last_observed_epoch_with_gap: epoch_with_gap,
1030 }
1031 }
1032
1033 pub fn observe<F>(&mut self, key: FullKey<F>) -> bool
1068 where
1069 T: SetSlice<F>,
1070 F: AsRef<[u8]>,
1071 {
1072 self.observe_multi_version(key.user_key, once(key.epoch_with_gap))
1073 }
1074
1075 pub fn observe_multi_version<F>(
1077 &mut self,
1078 user_key: UserKey<F>,
1079 mut epochs: impl Iterator<Item = EpochWithGap>,
1080 ) -> bool
1081 where
1082 T: SetSlice<F>,
1083 F: AsRef<[u8]>,
1084 {
1085 let max_epoch_with_gap = epochs.next().expect("non-empty");
1086 let min_epoch_with_gap = epochs.fold(
1087 max_epoch_with_gap,
1088 |prev_epoch_with_gap, curr_epoch_with_gap| {
1089 assert!(
1090 prev_epoch_with_gap > curr_epoch_with_gap,
1091 "epoch list not sorted. prev: {:?}, curr: {:?}, user_key: {:?}",
1092 prev_epoch_with_gap,
1093 curr_epoch_with_gap,
1094 user_key
1095 );
1096 curr_epoch_with_gap
1097 },
1098 );
1099 match self
1100 .latest_full_key
1101 .user_key
1102 .as_ref()
1103 .cmp(&user_key.as_ref())
1104 {
1105 Ordering::Less => {
1106 self.last_observed_epoch_with_gap = min_epoch_with_gap;
1110
1111 self.latest_full_key.set(FullKey {
1113 user_key,
1114 epoch_with_gap: min_epoch_with_gap,
1115 });
1116 true
1117 }
1118 Ordering::Equal => {
1119 if max_epoch_with_gap > self.last_observed_epoch_with_gap
1120 || (!SKIP_DEDUP && max_epoch_with_gap == self.last_observed_epoch_with_gap)
1121 {
1122 panic!(
1124 "key {:?} epoch {:?} >= prev epoch {:?}",
1125 user_key, max_epoch_with_gap, self.last_observed_epoch_with_gap
1126 );
1127 }
1128 self.last_observed_epoch_with_gap = min_epoch_with_gap;
1129 false
1130 }
1131 Ordering::Greater => {
1132 panic!(
1134 "key {:?} <= prev key {:?}",
1135 user_key,
1136 FullKey {
1137 user_key: self.latest_full_key.user_key.as_ref(),
1138 epoch_with_gap: self.last_observed_epoch_with_gap
1139 }
1140 );
1141 }
1142 }
1143 }
1144
1145 pub fn latest_user_key(&self) -> &UserKey<T> {
1146 &self.latest_full_key.user_key
1147 }
1148}
1149
1150#[cfg(test)]
1151mod tests {
1152 use risingwave_common::util::epoch::test_epoch;
1153
1154 use super::*;
1155
1156 #[test]
1157 fn test_encode_decode() {
1158 let epoch = test_epoch(1);
1159 let table_key = b"abc".to_vec();
1160 let key = FullKey::for_test(TableId::new(0), &table_key[..], 0);
1161 let buf = key.encode();
1162 assert_eq!(FullKey::decode(&buf), key);
1163 let key = FullKey::for_test(TableId::new(1), &table_key[..], epoch);
1164 let buf = key.encode();
1165 assert_eq!(FullKey::decode(&buf), key);
1166 let mut table_key = vec![1];
1167 let a = FullKey::for_test(TableId::new(1), table_key.clone(), epoch);
1168 table_key[0] = 2;
1169 let b = FullKey::for_test(TableId::new(1), table_key.clone(), epoch);
1170 table_key[0] = 129;
1171 let c = FullKey::for_test(TableId::new(1), table_key, epoch);
1172 assert!(a.lt(&b));
1173 assert!(b.lt(&c));
1174 }
1175
1176 #[test]
1177 fn test_key_cmp() {
1178 let epoch = test_epoch(1);
1179 let epoch2 = test_epoch(2);
1180 let key1 = FullKey::for_test(TableId::new(0), b"0".to_vec(), epoch);
1182 let key2 = FullKey::for_test(TableId::new(1), b"0".to_vec(), epoch);
1183 let key3 = FullKey::for_test(TableId::new(1), b"1".to_vec(), epoch2);
1184 let key4 = FullKey::for_test(TableId::new(1), b"1".to_vec(), epoch);
1185
1186 assert_eq!(key1.cmp(&key1), Ordering::Equal);
1187 assert_eq!(key1.cmp(&key2), Ordering::Less);
1188 assert_eq!(key2.cmp(&key3), Ordering::Less);
1189 assert_eq!(key3.cmp(&key4), Ordering::Less);
1190 }
1191
1192 #[test]
1193 fn test_prev_key() {
1194 assert_eq!(prev_key(b"123"), b"122");
1195 assert_eq!(prev_key(b"12\x00"), b"11\xff");
1196 assert_eq!(prev_key(b"\x00\x00"), b"\xff\xff");
1197 assert_eq!(prev_key(b"\x00\x01"), b"\x00\x00");
1198 assert_eq!(prev_key(b"T"), b"S");
1199 assert_eq!(prev_key(b""), b"");
1200 }
1201
1202 #[test]
1203 fn test_bound_table_key_range() {
1204 assert_eq!(
1205 bound_table_key_range(
1206 TableId::default(),
1207 &(
1208 Included(TableKey(b"a".to_vec())),
1209 Included(TableKey(b"b".to_vec()))
1210 )
1211 ),
1212 (
1213 Included(UserKey::for_test(TableId::default(), &b"a".to_vec())),
1214 Included(UserKey::for_test(TableId::default(), &b"b".to_vec()),)
1215 )
1216 );
1217 assert_eq!(
1218 bound_table_key_range(
1219 TableId::from(1),
1220 &(Included(TableKey(b"a".to_vec())), Unbounded)
1221 ),
1222 (
1223 Included(UserKey::for_test(TableId::from(1), &b"a".to_vec())),
1224 Excluded(UserKey::for_test(TableId::from(2), &b"".to_vec()),)
1225 )
1226 );
1227 assert_eq!(
1228 bound_table_key_range(
1229 TableId::from(u32::MAX),
1230 &(Included(TableKey(b"a".to_vec())), Unbounded)
1231 ),
1232 (
1233 Included(UserKey::for_test(TableId::from(u32::MAX), &b"a".to_vec())),
1234 Unbounded,
1235 )
1236 );
1237 }
1238
1239 #[test]
1240 fn test_next_full_key() {
1241 let user_key = b"aaa".to_vec();
1242 let epoch: HummockEpoch = 3;
1243 let mut full_key = key_with_epoch(user_key, epoch);
1244 full_key = next_full_key(full_key.as_slice());
1245 assert_eq!(full_key, key_with_epoch(b"aaa".to_vec(), 2));
1246 full_key = next_full_key(full_key.as_slice());
1247 assert_eq!(full_key, key_with_epoch(b"aaa".to_vec(), 1));
1248 full_key = next_full_key(full_key.as_slice());
1249 assert_eq!(full_key, key_with_epoch(b"aaa".to_vec(), 0));
1250 full_key = next_full_key(full_key.as_slice());
1251 assert_eq!(
1252 full_key,
1253 key_with_epoch("aab".as_bytes().to_vec(), HummockEpoch::MAX)
1254 );
1255 assert_eq!(
1256 next_full_key(&key_with_epoch(b"\xff".to_vec(), 0)),
1257 Vec::<u8>::new()
1258 );
1259 }
1260
1261 #[test]
1262 fn test_prev_full_key() {
1263 let user_key = b"aab";
1264 let epoch: HummockEpoch = HummockEpoch::MAX - 3;
1265 let mut full_key = key_with_epoch(user_key.to_vec(), epoch);
1266 full_key = prev_full_key(full_key.as_slice());
1267 assert_eq!(
1268 full_key,
1269 key_with_epoch(b"aab".to_vec(), HummockEpoch::MAX - 2)
1270 );
1271 full_key = prev_full_key(full_key.as_slice());
1272 assert_eq!(
1273 full_key,
1274 key_with_epoch(b"aab".to_vec(), HummockEpoch::MAX - 1)
1275 );
1276 full_key = prev_full_key(full_key.as_slice());
1277 assert_eq!(full_key, key_with_epoch(b"aab".to_vec(), HummockEpoch::MAX));
1278 full_key = prev_full_key(full_key.as_slice());
1279 assert_eq!(full_key, key_with_epoch(b"aaa".to_vec(), 0));
1280
1281 assert_eq!(
1282 prev_full_key(&key_with_epoch(b"\x00".to_vec(), HummockEpoch::MAX)),
1283 Vec::<u8>::new()
1284 );
1285 }
1286
1287 #[test]
1288 fn test_user_key_order() {
1289 let a = UserKey::new(TableId::new(1), TableKey(b"aaa".to_vec()));
1290 let b = UserKey::new(TableId::new(2), TableKey(b"aaa".to_vec()));
1291 let c = UserKey::new(TableId::new(2), TableKey(b"bbb".to_vec()));
1292 assert!(a.lt(&b));
1293 assert!(b.lt(&c));
1294 let a = a.encode();
1295 let b = b.encode();
1296 let c = c.encode();
1297 assert!(a.lt(&b));
1298 assert!(b.lt(&c));
1299 }
1300
1301 #[test]
1302 fn test_prefixed_range_with_vnode() {
1303 let concat = |vnode: usize, b: &[u8]| -> Bytes {
1304 prefix_slice_with_vnode(VirtualNode::from_index(vnode), b)
1305 };
1306 assert_eq!(
1307 prefixed_range_with_vnode(
1308 (Included(Bytes::from("1")), Included(Bytes::from("2"))),
1309 VirtualNode::from_index(233),
1310 ),
1311 (
1312 Included(TableKey(concat(233, b"1"))),
1313 Included(TableKey(concat(233, b"2")))
1314 )
1315 );
1316 assert_eq!(
1317 prefixed_range_with_vnode(
1318 (Excluded(Bytes::from("1")), Excluded(Bytes::from("2"))),
1319 VirtualNode::from_index(233),
1320 ),
1321 (
1322 Excluded(TableKey(concat(233, b"1"))),
1323 Excluded(TableKey(concat(233, b"2")))
1324 )
1325 );
1326 assert_eq!(
1327 prefixed_range_with_vnode(
1328 (Bound::<Bytes>::Unbounded, Bound::<Bytes>::Unbounded),
1329 VirtualNode::from_index(233),
1330 ),
1331 (
1332 Included(TableKey(concat(233, b""))),
1333 Excluded(TableKey(concat(234, b"")))
1334 )
1335 );
1336 let max_vnode = VirtualNode::MAX_REPRESENTABLE.to_index();
1337 assert_eq!(
1338 prefixed_range_with_vnode(
1339 (Bound::<Bytes>::Unbounded, Bound::<Bytes>::Unbounded),
1340 VirtualNode::from_index(max_vnode),
1341 ),
1342 (Included(TableKey(concat(max_vnode, b""))), Unbounded)
1343 );
1344 let second_max_vnode = max_vnode - 1;
1345 assert_eq!(
1346 prefixed_range_with_vnode(
1347 (Bound::<Bytes>::Unbounded, Bound::<Bytes>::Unbounded),
1348 VirtualNode::from_index(second_max_vnode),
1349 ),
1350 (
1351 Included(TableKey(concat(second_max_vnode, b""))),
1352 Excluded(TableKey(concat(max_vnode, b"")))
1353 )
1354 );
1355 }
1356
1357 #[test]
1358 fn test_single_vnode_range() {
1359 let left_bound = vec![
1360 Included(b"0".as_slice()),
1361 Excluded(b"0".as_slice()),
1362 Unbounded,
1363 ];
1364 let right_bound = vec![
1365 Included(b"1".as_slice()),
1366 Excluded(b"1".as_slice()),
1367 Unbounded,
1368 ];
1369 for vnode in 0..VirtualNode::MAX_COUNT {
1370 for left in &left_bound {
1371 for right in &right_bound {
1372 assert_eq!(
1373 (vnode, vnode + 1),
1374 vnode_range(&prefixed_range_with_vnode::<&[u8]>(
1375 (*left, *right),
1376 VirtualNode::from_index(vnode)
1377 ))
1378 )
1379 }
1380 }
1381 }
1382 }
1383}