/
kafka.rs
190 lines (171 loc) · 7.02 KB
/
kafka.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
use crate::codec::kafka::RequestHeader as CodecRequestHeader;
use anyhow::{anyhow, Context, Result};
use bytes::{BufMut, Bytes, BytesMut};
use kafka_protocol::messages::{
ApiKey, DescribeClusterResponse, FetchResponse, FindCoordinatorRequest,
FindCoordinatorResponse, LeaderAndIsrRequest, MetadataResponse, ProduceRequest,
ProduceResponse, RequestHeader, ResponseHeader,
};
use kafka_protocol::protocol::{Decodable, Encodable, HeaderVersion};
#[derive(Debug, PartialEq, Clone)]
pub enum KafkaFrame {
Request {
header: RequestHeader,
body: RequestBody,
},
Response {
version: i16,
header: ResponseHeader,
body: ResponseBody,
},
}
#[derive(Debug, PartialEq, Clone)]
pub enum RequestBody {
Produce(ProduceRequest),
FindCoordinator(FindCoordinatorRequest),
LeaderAndIsr(LeaderAndIsrRequest),
Unknown { api_key: ApiKey, message: Bytes },
}
#[derive(Debug, PartialEq, Clone)]
pub enum ResponseBody {
Produce(ProduceResponse),
FindCoordinator(FindCoordinatorResponse),
Fetch(FetchResponse),
Metadata(MetadataResponse),
DescribeCluster(DescribeClusterResponse),
Unknown { api_key: ApiKey, message: Bytes },
}
impl ResponseBody {
fn header_version(&self, version: i16) -> i16 {
match self {
ResponseBody::Produce(_) => ProduceResponse::header_version(version),
ResponseBody::FindCoordinator(_) => FindCoordinatorResponse::header_version(version),
ResponseBody::Fetch(_) => FetchResponse::header_version(version),
ResponseBody::Metadata(_) => MetadataResponse::header_version(version),
ResponseBody::DescribeCluster(_) => DescribeClusterResponse::header_version(version),
ResponseBody::Unknown { api_key, .. } => api_key.response_header_version(version),
}
}
}
impl KafkaFrame {
pub fn from_bytes(
mut bytes: Bytes,
request_header: Option<CodecRequestHeader>,
) -> Result<Self> {
// remove length header
let _ = bytes.split_to(4);
match request_header {
Some(request_header) => KafkaFrame::parse_response(bytes, request_header),
None => KafkaFrame::parse_request(bytes),
}
}
fn parse_request(mut bytes: Bytes) -> Result<Self> {
let api_key = i16::from_be_bytes(bytes[0..2].try_into().unwrap());
let api_version = i16::from_be_bytes(bytes[2..4].try_into().unwrap());
let header_version = ApiKey::try_from(api_key)
.unwrap()
.request_header_version(api_version);
let header = RequestHeader::decode(&mut bytes, header_version)
.context("Failed to decode request header")?;
let api_key = ApiKey::try_from(header.request_api_key)
.map_err(|_| anyhow!("unknown api key {}", header.request_api_key))?;
let version = header.request_api_version;
let body = match api_key {
ApiKey::ProduceKey => RequestBody::Produce(decode(&mut bytes, version)?),
ApiKey::FindCoordinatorKey => {
RequestBody::FindCoordinator(decode(&mut bytes, version)?)
}
ApiKey::LeaderAndIsrKey => RequestBody::LeaderAndIsr(decode(&mut bytes, version)?),
api_key => RequestBody::Unknown {
api_key,
message: bytes,
},
};
Ok(KafkaFrame::Request { header, body })
}
fn parse_response(mut bytes: Bytes, request_header: CodecRequestHeader) -> Result<Self> {
let header = ResponseHeader::decode(
&mut bytes,
request_header
.api_key
.response_header_version(request_header.version),
)
.context("Failed to decode response header")?;
let version = request_header.version;
let body = match request_header.api_key {
ApiKey::ProduceKey => ResponseBody::Produce(decode(&mut bytes, version)?),
ApiKey::FindCoordinatorKey => {
ResponseBody::FindCoordinator(decode(&mut bytes, version)?)
}
ApiKey::FetchKey => ResponseBody::Fetch(decode(&mut bytes, version)?),
ApiKey::MetadataKey => ResponseBody::Metadata(decode(&mut bytes, version)?),
ApiKey::DescribeClusterKey => {
ResponseBody::DescribeCluster(decode(&mut bytes, version)?)
}
api_key => ResponseBody::Unknown {
api_key,
message: bytes,
},
};
Ok(KafkaFrame::Response {
version,
header,
body,
})
}
pub fn encode(self, bytes: &mut BytesMut) -> Result<()> {
// write dummy length
let length_start = bytes.len();
let bytes_start = length_start + 4;
bytes.put_i32(0);
// write message
match self {
KafkaFrame::Request { header, body } => {
let header_version = ApiKey::try_from(header.request_api_key)
.map_err(|_| anyhow!("unknown api key {}", header.request_api_key))?
.request_header_version(header.request_api_version);
header.encode(bytes, header_version)?;
let version = header.request_api_version;
match body {
RequestBody::Produce(x) => encode(x, bytes, version)?,
RequestBody::FindCoordinator(x) => encode(x, bytes, version)?,
RequestBody::LeaderAndIsr(x) => encode(x, bytes, version)?,
RequestBody::Unknown { message, .. } => bytes.extend_from_slice(&message),
}
}
KafkaFrame::Response {
version,
header,
body,
} => {
header.encode(bytes, body.header_version(version))?;
match body {
ResponseBody::Produce(x) => encode(x, bytes, version)?,
ResponseBody::FindCoordinator(x) => encode(x, bytes, version)?,
ResponseBody::Fetch(x) => encode(x, bytes, version)?,
ResponseBody::Metadata(x) => encode(x, bytes, version)?,
ResponseBody::DescribeCluster(x) => encode(x, bytes, version)?,
ResponseBody::Unknown { message, .. } => bytes.extend_from_slice(&message),
}
}
}
// overwrite dummy length with actual length of serialized bytes
let bytes_len = bytes.len() - bytes_start;
bytes[length_start..bytes_start].copy_from_slice(&(bytes_len as i32).to_be_bytes());
Ok(())
}
}
fn decode<T: Decodable>(bytes: &mut Bytes, version: i16) -> Result<T> {
T::decode(bytes, version).context(format!(
"Failed to decode {} v{} body",
std::any::type_name::<T>(),
version
))
}
fn encode<T: Encodable>(encodable: T, bytes: &mut BytesMut, version: i16) -> Result<()> {
encodable.encode(bytes, version).context(format!(
"Failed to encode {} v{} body",
std::any::type_name::<T>(),
version
))
}