-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathraft_state_machine.h
99 lines (78 loc) · 2.65 KB
/
raft_state_machine.h
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
#ifndef raft_state_machine_h
#define raft_state_machine_h
#include "rpc.h"
#include <vector>
#include <map>
#include <string>
#include <memory>
#include <chrono>
#include <atomic>
#include <condition_variable>
class raft_command {
public:
virtual ~raft_command() {}
// These interfaces will be used to persistent the command.
virtual int size() const = 0;
virtual void serialize(char* buf, int size) const = 0;
virtual void deserialize(const char* buf, int size) = 0;
};
class raft_state_machine {
public:
virtual ~raft_state_machine() {}
// Apply a log to the state machine.
virtual void apply_log(raft_command&) = 0;
// Generate a snapshot of the current state.
virtual std::vector<char> snapshot() = 0;
// Apply the snapshot to the state mahine.
virtual void apply_snapshot(const std::vector<char>&) = 0;
};
class kv_command : public raft_command {
public:
enum command_type {
CMD_NONE, // Do nothing
CMD_GET, // Get a key-value pair
CMD_PUT, // Put a key-value pair
CMD_DEL // Delete a key-value pair
};
struct result {
std::chrono::system_clock::time_point start;
// Ops Succ Key Value
// Get T key value
// Get F key ""
// Del T key old_value
// Del F key ""
// Put T key new_value
// Put F(replace) key old_value
std::string key, value;
bool succ;
bool done;
std::mutex mtx; // protect the struct
std::condition_variable cv; // notify the caller
};
kv_command();
kv_command(command_type tp, const std::string& key, const std::string& value);
kv_command(const kv_command &);
virtual ~kv_command();
command_type cmd_tp;
std::string key, value;
std::shared_ptr<result> res;
virtual int size() const override;
virtual void serialize(char* buf, int size) const override;
virtual void deserialize(const char* buf, int size);
};
marshall& operator<<(marshall &m, const kv_command& cmd);
unmarshall& operator>>(unmarshall &u, kv_command& cmd);
class kv_state_machine : public raft_state_machine {
public:
virtual ~kv_state_machine();
// Apply a log to the state machine.
virtual void apply_log(raft_command&) override;
// Generate a snapshot of the current state.
virtual std::vector<char> snapshot() override;
// Apply the snapshot to the state mahine.
virtual void apply_snapshot(const std::vector<char>&) override;
private:
std::map<std::string, std::string> kv;
std::mutex mtx;
};
#endif // raft_state_machine_h