risingwave_connector/source/kafka/split.rs
1// Copyright 2022 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use risingwave_common::types::JsonbVal;
16use serde::{Deserialize, Serialize};
17
18use crate::error::ConnectorResult;
19use crate::source::{SplitId, SplitMetaData};
20
21#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Hash)]
22pub struct KafkaSplit {
23 pub(crate) topic: String,
24 pub(crate) partition: i32,
25 /// Note: currently the start offset is **exclusive**. We need to `+1` to create the reader.
26 /// Possible values are:
27 /// - `Earliest`: `low_watermark` - 1
28 /// - `Latest`: `high_watermark` - 1
29 /// - `Timestamp`: `offset_for_timestamp` - 1
30 /// - `last_seen_offset`
31 ///
32 /// A better approach would be to make it **inclusive**. <https://github.com/risingwavelabs/risingwave/pull/16257>
33 pub(crate) start_offset: Option<i64>,
34 pub(crate) stop_offset: Option<i64>,
35}
36
37impl SplitMetaData for KafkaSplit {
38 fn id(&self) -> SplitId {
39 // TODO: should avoid constructing a string every time
40 format!("{}", self.partition).into()
41 }
42
43 fn restore_from_json(value: JsonbVal) -> ConnectorResult<Self> {
44 serde_json::from_value(value.take()).map_err(Into::into)
45 }
46
47 fn encode_to_json(&self) -> JsonbVal {
48 serde_json::to_value(self.clone()).unwrap().into()
49 }
50
51 fn update_offset(&mut self, last_seen_offset: String) -> ConnectorResult<()> {
52 self.start_offset = Some(last_seen_offset.as_str().parse::<i64>().unwrap());
53 Ok(())
54 }
55}
56
57impl KafkaSplit {
58 pub fn new(
59 partition: i32,
60 start_offset: Option<i64>,
61 stop_offset: Option<i64>,
62 topic: String,
63 ) -> KafkaSplit {
64 KafkaSplit {
65 topic,
66 partition,
67 start_offset,
68 stop_offset,
69 }
70 }
71}