-
Notifications
You must be signed in to change notification settings - Fork 0
/
fibergun.go
406 lines (355 loc) · 9.72 KB
/
fibergun.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
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
package fibergun
import (
"encoding/json"
"fmt"
"log"
"sync"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/websocket/v2"
)
// GunMessage represents various GunDB message types
type GunMessage struct {
Get *GunGet `json:"get,omitempty"`
Put *GunPut `json:"put,omitempty"`
Hash string `json:"#,omitempty"`
Ok *GunOk `json:"ok,omitempty"`
Err string `json:"err,omitempty"`
}
// GunGet represents a GET request in GunDB
type GunGet struct {
Hash string `json:"#,omitempty"`
Key string `json:".,omitempty"`
Soul string `json:"#,omitempty"`
}
type GunPut struct {
Chat map[string]interface{} `json:"chat,omitempty"`
ChatMessage map[string]interface{} `json:"chat/message,omitempty"`
Messages map[string]interface{} `json:"messages,omitempty"`
Ok map[string]interface{} `json:"ok,omitempty"`
}
// GunOk represents an acknowledgment in GunDB
type GunOk struct {
Hash string `json:"@,omitempty"`
Data map[string]interface{} `json:"/,omitempty"`
}
// PeerConnection represents a connected peer
type PeerConnection struct {
ID string
Conn *websocket.Conn
LastSeen time.Time
Store *sync.Map
Active bool
}
// GunDB represents the main handler structure
type GunDB struct {
config *Config
peers *sync.Map
}
// New creates a new GunDB middleware instance
func New(config ...*Config) fiber.Handler {
var cfg *Config
if len(config) > 0 {
cfg = config[0]
} else {
cfg = ConfigDefault()
}
gundb := &GunDB{
config: cfg,
peers: &sync.Map{},
}
// Start cleanup goroutine
go gundb.cleanupInactivePeers()
return func(c *fiber.Ctx) error {
if cfg.Next != nil && cfg.Next(c) {
return c.Next()
}
if c.Path() == cfg.WebSocketEndpoint {
if websocket.IsWebSocketUpgrade(c) {
c.Locals("allowed", true)
return websocket.New(gundb.handleWebSocket(), websocket.Config{
EnableCompression: true,
ReadBufferSize: 1024 * 1024,
WriteBufferSize: 1024 * 1024,
})(c)
}
return fiber.ErrUpgradeRequired
}
if c.Path() == "/" {
return c.SendFile(cfg.StaticPath + "/index.html")
}
c.Locals("gundb", gundb)
return c.Next()
}
}
func (g *GunDB) cleanupInactivePeers() {
ticker := time.NewTicker(g.config.HeartbeatInterval)
defer ticker.Stop()
for range ticker.C {
now := time.Now()
g.peers.Range(func(key, value interface{}) bool {
peer := value.(*PeerConnection)
if !peer.Active || now.Sub(peer.LastSeen) > g.config.PeerTimeout {
log.Printf("Cleaning up inactive peer: %s", peer.ID)
g.peers.Delete(key)
peer.Conn.Close()
}
return true
})
}
}
func (g *GunDB) handleWebSocket() func(*websocket.Conn) {
return func(c *websocket.Conn) {
peerID := fmt.Sprintf("peer_%d", time.Now().UnixNano())
peer := &PeerConnection{
ID: peerID,
Conn: c,
LastSeen: time.Now(),
Store: &sync.Map{},
Active: true,
}
g.peers.Store(peerID, peer)
log.Printf("New peer connected: %s", peerID)
g.sendAck(c, peerID)
defer func() {
peer.Active = false
g.peers.Delete(peerID)
c.Close()
log.Printf("Peer disconnected: %s", peerID)
}()
// Start heartbeat
go g.maintainHeartbeat(peer)
for {
messageType, msg, err := c.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("Error reading message from peer %s: %v", peerID, err)
}
break
}
peer.LastSeen = time.Now()
if messageType == websocket.TextMessage {
g.handleMessage(peer, msg)
}
}
}
}
func (g *GunDB) maintainHeartbeat(peer *PeerConnection) {
ticker := time.NewTicker(15 * time.Second)
defer ticker.Stop()
for range ticker.C {
if !peer.Active {
return
}
if err := peer.Conn.WriteMessage(websocket.PingMessage, nil); err != nil {
peer.Active = false
return
}
}
}
// Add this at the package level
var globalStore = &sync.Map{}
func (g *GunDB) handleMessage(peer *PeerConnection, msg []byte) {
log.Printf("Raw message from peer %s: %s", peer.ID, string(msg))
// Try to parse as array first
var messages []json.RawMessage
if err := json.Unmarshal(msg, &messages); err == nil {
for _, rawMsg := range messages {
// Look for PUT message in array
var message map[string]interface{}
if err := json.Unmarshal(rawMsg, &message); err == nil {
if putData, ok := message["put"]; ok {
log.Printf("Found PUT in array: %v", putData)
// Create GunMessage and process
gunMsg := GunMessage{
Put: &GunPut{
Chat: putData.(map[string]interface{}),
},
Hash: message["#"].(string),
}
g.processGunMessage(peer, &gunMsg, rawMsg)
}
}
// Also try as GunMessage
var arrayMsg GunMessage
if err := json.Unmarshal(rawMsg, &arrayMsg); err == nil {
g.processGunMessage(peer, &arrayMsg, rawMsg)
}
}
return
}
// Try as single message if not array
var gunMsg GunMessage
if err := json.Unmarshal(msg, &gunMsg); err == nil {
g.processGunMessage(peer, &gunMsg, msg)
}
}
// Update processGunMessage to handle rawMsg
func (g *GunDB) processGunMessage(peer *PeerConnection, msg *GunMessage, rawMsg []byte) {
log.Printf("Processing message from peer %s: %+v", peer.ID, msg)
if msg.Get != nil {
g.handleGet(peer, msg)
}
if msg.Put != nil {
log.Printf("Found PUT message: %+v", msg.Put)
g.handlePut(peer, msg, rawMsg)
}
if msg.Ok != nil {
log.Printf("OK acknowledgment from %s: %+v", peer.ID, msg.Ok)
}
}
// Remove the standalone broadcast function and update handlePut to handle broadcasting directly
func (g *GunDB) handlePut(peer *PeerConnection, msg *GunMessage, rawMsg []byte) {
log.Printf("Processing PUT from peer %s: %+v", peer.ID, msg.Put)
// Extract data from the nested structure
if msg.Put.Chat != nil {
for k, v := range msg.Put.Chat {
if messageData, ok := v.(map[string]interface{}); ok {
log.Printf("Storing chat message: %v", messageData)
globalStore.Store(k, messageData)
peer.Store.Store(k, messageData)
}
}
// Broadcast to other peers
g.broadcast(peer, rawMsg)
}
// Handle direct messages if present
if msg.Put.Messages != nil {
for k, v := range msg.Put.Messages {
globalStore.Store(k, v)
peer.Store.Store(k, v)
}
g.broadcast(peer, rawMsg)
}
// Send acknowledgment
ack := map[string]interface{}{
"#": msg.Hash,
"@": msg.Hash,
"ok": true,
}
g.sendJSON(peer.Conn, ack)
}
// Update handleGet to check globalStore first
func (g *GunDB) handleGet(peer *PeerConnection, msg *GunMessage) {
log.Printf("Processing GET from peer %s: %+v", peer.ID, msg.Get)
if msg.Get.Soul != "" {
// Check global store first
if data, ok := globalStore.Load(msg.Get.Soul); ok {
response := map[string]interface{}{
"#": time.Now().UnixNano(),
"@": msg.Hash,
"put": data,
}
g.sendJSON(peer.Conn, response)
return
}
// Check peer stores if not in global store
g.peers.Range(func(_, value interface{}) bool {
if p := value.(*PeerConnection); p.Active {
if data, ok := p.Store.Load(msg.Get.Soul); ok {
response := map[string]interface{}{
"#": time.Now().UnixNano(),
"@": msg.Hash,
"put": data,
}
g.sendJSON(peer.Conn, response)
return false
}
}
return true
})
}
}
func (g *GunDB) sendJSON(c *websocket.Conn, data interface{}) {
if msg, err := json.Marshal(data); err == nil {
if err := c.WriteMessage(websocket.TextMessage, msg); err != nil {
log.Printf("Error sending JSON: %v", err)
}
}
}
func (g *GunDB) sendAck(c *websocket.Conn, peerID string) {
ack := map[string]interface{}{
"#": time.Now().UnixNano(),
"ok": true,
"pid": peerID,
}
g.sendJSON(c, ack)
}
func (g *GunDB) broadcast(sender *PeerConnection, msg []byte) {
log.Printf("Broadcasting message from peer %s: %+v", sender.ID, string(msg))
g.peers.Range(func(_, value interface{}) bool {
peer := value.(*PeerConnection)
if peer.Active && peer.ID != sender.ID {
for attempts := 0; attempts < 3; attempts++ {
if err := peer.Conn.WriteMessage(websocket.TextMessage, msg); err != nil {
log.Printf("Error broadcasting to peer %s (attempt %d): %v", peer.ID, attempts+1, err)
if attempts == 2 {
peer.Active = false
}
time.Sleep(100 * time.Millisecond)
} else {
log.Printf("Successfully broadcast to peer %s", peer.ID)
break
}
}
}
return true
})
}
func (g *GunDB) Put(key string, value interface{}) error {
// Store in global store first
globalStore.Store(key, value)
msg := GunMessage{
Hash: time.Now().Format("20060102150405.000000000"),
Put: &GunPut{
Messages: map[string]interface{}{
key: value,
},
},
}
data, err := json.Marshal(msg)
if err != nil {
return err
}
// Store and broadcast to all peers
g.peers.Range(func(_, value interface{}) bool {
if peer := value.(*PeerConnection); peer.Active {
// Store data
peer.Store.Store(key, value)
// Send with retry
for attempts := 0; attempts < 3; attempts++ {
if err := peer.Conn.WriteMessage(websocket.TextMessage, data); err != nil {
log.Printf("Error sending to peer %s (attempt %d): %v", peer.ID, attempts+1, err)
if attempts == 2 {
peer.Active = false
}
time.Sleep(100 * time.Millisecond)
} else {
log.Printf("Successfully sent to peer %s", peer.ID)
break
}
}
}
return true
})
return nil
}
// Update Get to check globalStore first
func (g *GunDB) Get(key string) (interface{}, error) {
// Check global store first
if value, ok := globalStore.Load(key); ok {
return value, nil
}
// Check peer stores if not found in global store
var result interface{}
g.peers.Range(func(_, value interface{}) bool {
if peer := value.(*PeerConnection); peer.Active {
if data, ok := peer.Store.Load(key); ok {
result = data
return false
}
}
return true
})
return result, nil
}