-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmainserver.go
208 lines (175 loc) · 4.73 KB
/
mainserver.go
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
package main
import (
"fmt"
"io"
"net"
"strings"
)
func main() {
fmt.Println("Listening on port :6379")
// Create a new TCP server
l, err := net.Listen("tcp", ":6379")
if err != nil {
fmt.Println(err)
return
}
defer l.Close()
// Initialize the AOF file for persistence
aof, err := NewAof("database.aof")
if err != nil {
fmt.Println(err)
return
}
defer aof.Close()
// Replay commands from the AOF log to restore state
aof.Read(func(value Value) {
command := strings.ToUpper(value.array[0].bulk)
args := value.array[1:]
handler, ok := Handlers[command]
if !ok {
fmt.Println("Invalid command in AOF: ", command)
return
}
handler(args)
})
// Listen for incoming client connections
for {
conn, err := l.Accept()
if err != nil {
fmt.Println(err)
continue
}
go handleConnection(conn, aof) // Handle each connection in a separate goroutine
}
}
func handleConnection(conn net.Conn, aof *Aof) {
defer conn.Close()
resp := NewResp(conn)
writer := NewWriter(conn)
for {
// Read the client's request
value, err := resp.Read()
if err != nil {
if err == io.EOF {
fmt.Println("Client disconnected")
break
}
fmt.Println("Error reading request: ", err)
writer.Write(Value{typ: "error", str: "ERR invalid request"})
continue
}
// Check if the request is a pipeline (array of commands)
if value.typ == "array" && len(value.array) > 0 && value.array[0].typ == "array" {
handlePipeline(value, writer, aof)
continue
}
// Handle single command
handleCommand(value, writer, aof)
}
}
func handlePipeline(value Value, writer *Writer, aof *Aof) {
responses := make([]Value, len(value.array))
for i, commandValue := range value.array {
if commandValue.typ != "array" || len(commandValue.array) == 0 {
responses[i] = Value{typ: "error", str: "ERR invalid pipeline command format"}
continue
}
command := strings.ToUpper(commandValue.array[0].bulk)
args := commandValue.array[1:]
handler, ok := Handlers[command]
if !ok {
responses[i] = Value{typ: "error", str: "ERR unknown command"}
continue
}
// Persist state-changing commands
if command == "SET" || command == "HSET" {
err := aof.Write(commandValue)
if err != nil {
fmt.Println("Error writing to AOF: ", err)
responses[i] = Value{typ: "error", str: "ERR internal server error"}
continue
}
}
// Execute the command
responses[i] = handler(args)
}
// Write all responses as a single array
writer.Write(Value{typ: "array", array: responses})
}
var pubsub = NewPubSub() // Initialize PubSub
func handleCommand(value Value, writer *Writer, aof *Aof) {
// Ensure the request is a valid RESP array
if value.typ != "array" || len(value.array) == 0 {
writer.Write(Value{typ: "error", str: "ERR invalid request format"})
return
}
command := strings.ToUpper(value.array[0].bulk)
args := value.array[1:]
switch command {
case "SUBSCRIBE":
handleSubscribe(args, writer)
case "UNSUBSCRIBE":
handleUnsubscribe(args, writer)
case "PUBLISH":
handlePublish(args, writer)
default:
// Delegate to other command handlers
handler, ok := Handlers[command]
if !ok {
writer.Write(Value{typ: "error", str: "ERR unknown command"})
return
}
if command == "SET" || command == "HSET" {
aof.Write(value) // Persist state-changing commands
}
result := handler(args)
writer.Write(result)
}
}
func handleSubscribe(args []Value, writer *Writer) {
if len(args) < 1 {
writer.Write(Value{typ: "error", str: "ERR wrong number of arguments for 'SUBSCRIBE' command"})
return
}
for _, arg := range args {
channel := arg.bulk
sub := pubsub.Subscribe(channel)
go func(channel string, sub <-chan Value) {
for msg := range sub {
writer.Write(Value{typ: "array", array: []Value{
{typ: "bulk", bulk: "message"},
{typ: "bulk", bulk: channel},
msg,
}})
}
}(channel, sub)
writer.Write(Value{typ: "array", array: []Value{
{typ: "bulk", bulk: "subscribe"},
{typ: "bulk", bulk: channel},
}})
}
}
func handleUnsubscribe(args []Value, writer *Writer) {
if len(args) < 1 {
writer.Write(Value{typ: "error", str: "ERR wrong number of arguments for 'UNSUBSCRIBE' command"})
return
}
for _, arg := range args {
channel := arg.bulk
pubsub.Unsubscribe(channel, nil) // Remove the subscriber
writer.Write(Value{typ: "array", array: []Value{
{typ: "bulk", bulk: "unsubscribe"},
{typ: "bulk", bulk: channel},
}})
}
}
func handlePublish(args []Value, writer *Writer) {
if len(args) < 2 {
writer.Write(Value{typ: "error", str: "ERR wrong number of arguments for 'PUBLISH' command"})
return
}
channel := args[0].bulk
message := args[1]
pubsub.Publish(channel, message)
writer.Write(Value{typ: "integer", num: len(pubsub.subscribers[channel])})
}