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
use crate::broker::error::BrokerError;
use crate::subscriber::types::Subscriber;
use std::fmt::{self, Debug};
pub struct Topic {
pub name: String,
pub partitions: Vec<Partition>,
pub subscribers: Vec<Subscriber>,
}
impl Debug for Topic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Topic")
.field("name", &self.name)
.field("partitions", &self.partitions)
.field("subscribers", &self.subscribers.len())
.finish()
}
}
pub struct Partition {
pub id: usize,
pub messages: Vec<String>,
pub replicas: Vec<Replica>,
pub next_offset: usize,
}
impl Debug for Partition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Partition")
.field("id", &self.id)
.field("messages", &self.messages)
.field("replicas", &self.replicas)
.finish()
}
}
pub struct Replica {
pub broker_id: String,
pub messages: Vec<String>,
}
impl Debug for Replica {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Replica")
.field("broker_id", &self.broker_id)
.field("messages", &self.messages)
.finish()
}
}
impl Topic {
/// Creates a new topic.
///
/// # Arguments
///
/// * `name` - The name of the topic.
/// * `num_partitions` - The number of partitions for the topic.
/// * `replication_factor` - The replication factor for the topic.
///
/// # Examples
///
/// ```
/// use rust_kafka_like::broker::topic::Topic;
///
/// let topic = Topic::new("test_topic", 3, 2);
/// assert_eq!(topic.name, "test_topic");
/// assert_eq!(topic.partitions.len(), 3);
/// assert_eq!(topic.partitions[0].replicas.len(), 2);
/// ```
pub fn new(name: &str, num_partitions: usize, replication_factor: usize) -> Self {
let partitions = (0..num_partitions)
.map(|i| Partition {
id: i,
messages: Vec::new(),
replicas: (0..replication_factor)
.map(|_| Replica {
broker_id: String::new(),
messages: Vec::new(),
})
.collect(),
next_offset: 0, // 初期化
})
.collect();
Topic {
name: name.to_string(),
partitions,
subscribers: Vec::new(),
}
}
/// Adds a subscriber to the topic.
///
/// # Arguments
///
/// * `subscriber` - The subscriber to add.
///
/// # Examples
///
/// ```
/// use rust_kafka_like::broker::topic::Topic;
/// use rust_kafka_like::subscriber::types::Subscriber;
///
/// let mut topic = Topic::new("test_topic", 3, 2);
/// let subscriber = Subscriber::new("sub1", Box::new(|msg: String| {
/// println!("Received message: {}", msg);
/// }));
/// topic.add_subscriber(subscriber);
/// assert_eq!(topic.subscribers.len(), 1);
/// ```
pub fn add_subscriber(&mut self, subscriber: Subscriber) {
self.subscribers.push(subscriber);
}
pub fn remove_subscriber(&mut self, _subscriber_id: &str) {
// TODO: Because the Subscriber does not have an ID, the implementation of this function needs to be reviewed.
}
/// Publishes a message to the topic.
///
/// # Arguments
///
/// * `message` - The message to publish.
/// * `partition_key` - An optional key for partitioning.
///
/// # Examples
///
/// ```
/// use rust_kafka_like::broker::topic::Topic;
/// use rust_kafka_like::broker::error::BrokerError;
///
/// let mut topic = Topic::new("test_topic", 3, 2);
/// let result = topic.publish("test_message".to_string(), None);
/// assert!(result.is_ok());
/// ```
pub fn publish(
&mut self,
message: String,
partition_key: Option<&str>,
) -> Result<usize, BrokerError> {
let partition_id = match partition_key {
Some(key) => self.get_partition_id(key),
None => self.get_next_partition(),
};
if let Some(partition) = self.partitions.get_mut(partition_id) {
partition.add_message(message.clone());
// Add a message to the replica
for replica in &mut partition.replicas {
replica.messages.push(message.clone());
}
// Notification to all subscribers
for subscriber in &self.subscribers {
(subscriber.callback)(message.clone());
}
Ok(partition_id)
} else {
Err(BrokerError::PartitionError(format!(
"Invalid partition id: {}",
partition_id
)))
}
}
fn get_partition_id(&self, key: &str) -> usize {
let hash = key.bytes().fold(0u64, |acc, b| acc.wrapping_add(b as u64));
(hash % self.partitions.len() as u64) as usize
}
fn get_next_partition(&self) -> usize {
use std::time::SystemTime;
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_millis();
(now % self.partitions.len() as u128) as usize
}
}
impl Partition {
/// Adds a message to the partition.
///
/// # Arguments
///
/// * `message` - The message to add.
///
/// # Examples
///
/// ```
/// use rust_kafka_like::broker::topic::Partition;
///
/// let mut partition = Partition {
/// id: 0,
/// messages: Vec::new(),
/// replicas: Vec::new(),
/// next_offset: 0,
/// };
/// partition.add_message("test_message".to_string());
/// assert_eq!(partition.messages.len(), 1);
/// assert_eq!(partition.messages[0], "test_message");
/// ```
pub fn add_message(&mut self, message: String) {
self.messages.push(message);
self.next_offset += 1;
}
/// Fetches messages from the partition starting from a given offset.
///
/// # Arguments
///
/// * `start_offset` - The offset to start fetching messages from.
///
/// # Examples
///
/// ```
/// use rust_kafka_like::broker::topic::Partition;
///
/// let mut partition = Partition {
/// id: 0,
/// messages: vec!["message_1".to_string(), "message_2".to_string()],
/// replicas: Vec::new(),
/// next_offset: 2,
/// };
/// let messages = partition.fetch_messages_in_order(1);
/// assert_eq!(messages.len(), 1);
/// assert_eq!(messages[0], "message_2");
/// ```
pub fn fetch_messages_in_order(&self, start_offset: usize) -> &[String] {
if start_offset >= self.messages.len() {
&[]
} else {
&self.messages[start_offset..]
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::subscriber::types::Subscriber;
use std::sync::{Arc, Mutex};
#[test]
fn test_topic_creation() {
let topic = Topic::new("test_topic", 3, 2);
assert_eq!(topic.name, "test_topic");
assert_eq!(topic.partitions.len(), 3);
assert_eq!(topic.partitions[0].replicas.len(), 2);
}
#[test]
fn test_add_subscriber() {
let mut topic = Topic::new("test_topic", 3, 2);
let subscriber = Subscriber::new(
"test_sub",
Box::new(|msg: String| {
println!("Received message: {}", msg);
}),
);
topic.add_subscriber(subscriber);
assert_eq!(topic.subscribers.len(), 1);
}
#[test]
fn test_publish_message() {
let mut topic = Topic::new("test_topic", 3, 2);
let subscriber = Subscriber::new(
"test_sub",
Box::new(|msg: String| {
println!("Received test message: {}", msg);
}),
);
topic.add_subscriber(subscriber);
let result = topic.publish("test_message".to_string(), None);
assert!(result.is_ok());
let partition_id = result.unwrap();
assert!(partition_id < 3);
assert_eq!(topic.partitions[partition_id].messages[0], "test_message");
}
#[test]
fn test_get_partition_id() {
let topic = Topic::new("test_topic", 3, 2);
let partition_id = topic.get_partition_id("key");
assert!(partition_id < 3);
}
#[test]
fn test_get_next_partition() {
let topic = Topic::new("test_topic", 3, 2);
let partition_id = topic.get_next_partition();
assert!(partition_id < 3);
}
#[test]
fn test_message_ordering() {
let mut topic = Topic::new("test_topic", 1, 1);
topic.publish("message_1".to_string(), None).unwrap();
topic.publish("message_2".to_string(), None).unwrap();
topic.publish("message_3".to_string(), None).unwrap();
let partition = &topic.partitions[0];
let messages = partition.fetch_messages_in_order(0);
assert_eq!(messages.len(), 3);
assert_eq!(messages[0], "message_1");
assert_eq!(messages[1], "message_2");
assert_eq!(messages[2], "message_3");
}
#[test]
fn test_fetch_messages_from_offset() {
let mut topic = Topic::new("test_topic", 1, 1);
topic.publish("message_1".to_string(), None).unwrap();
topic.publish("message_2".to_string(), None).unwrap();
topic.publish("message_3".to_string(), None).unwrap();
let partition = &topic.partitions[0];
let messages = partition.fetch_messages_in_order(1);
assert_eq!(messages.len(), 2);
assert_eq!(messages[0], "message_2");
assert_eq!(messages[1], "message_3");
}
#[test]
fn test_subscriber_receives_messages() {
let mut topic = Topic::new("test_topic", 1, 1);
let received_messages = Arc::new(Mutex::new(Vec::new()));
let subscriber = Subscriber::new("sub1", {
let received_messages = Arc::clone(&received_messages);
Box::new(move |msg: String| {
received_messages.lock().unwrap().push(msg);
})
});
topic.add_subscriber(subscriber);
topic.publish("message_1".to_string(), None).unwrap();
topic.publish("message_2".to_string(), None).unwrap();
let received_messages = received_messages.lock().unwrap();
assert_eq!(received_messages.len(), 2);
assert_eq!(received_messages[0], "message_1");
assert_eq!(received_messages[1], "message_2");
}
}