summaryrefslogtreecommitdiff
path: root/internal/network/network.go
blob: 8b6c6860a82b49bd33a7d874515bbd62dd247461 (plain)
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
package network

import (
	"bufio"
	"encoding/json"
	"fmt"
	"net"
	"sync"
	"time"

	"github.com/boozec/rahanna/internal/logger"
	"go.uber.org/zap"
)

// PeerInfo represents a peer's ID and IP.
type PeerInfo struct {
	ID   string `json:"id"`
	IP   string `json:"ip"`
	Port int    `json:"port"`
}

// Message represents a structured message.
type Message struct {
	Type      string   `json:"type"`
	Payload   []byte   `json:"payload"`
	Source    PeerInfo `json:"source"`
	Target    PeerInfo `json:"target"`
	Timestamp int64    `json:"timestamp"`
}

type NetworkCallback func(msg Message)

// TCPNetwork represents a full-duplex TCP peer.
type TCPNetwork struct {
	localPeer   PeerInfo
	connections map[string]net.Conn
	listener    net.Listener
	callbacks   map[string]NetworkCallback
	callbacksMu sync.RWMutex
	isConnected bool
	retryDelay  time.Duration
	logger      *zap.Logger
	sync.Mutex
}

// initializes a TCP peer
func NewTCPNetwork(localID, localIP string, localPort int, onReceive func()) *TCPNetwork {
	n := &TCPNetwork{
		localPeer:   PeerInfo{ID: localID, IP: localIP, Port: localPort},
		connections: make(map[string]net.Conn),
		callbacks:   make(map[string]NetworkCallback),
		isConnected: false,
		retryDelay:  2 * time.Second,
		logger:      logger.InitLogger("rahanna.log"),
	}

	go n.startServer(onReceive)

	return n
}

// Add a new peer connection to the local peer
func (n *TCPNetwork) AddPeer(remoteID string, remoteIP string, remotePort int) {
	go n.retryConnect(remoteID, remoteIP, remotePort)
}

// startServer starts a TCP server to accept connections.
func (n *TCPNetwork) startServer(callback func()) {
	address := fmt.Sprintf("%s:%d", n.localPeer.IP, n.localPeer.Port)
	listener, err := net.Listen("tcp", address)
	if err != nil {
		n.logger.Sugar().Errorf("failed to start server: %v", err)
		return
	}
	n.listener = listener
	n.logger.Sugar().Infof("server started on %s\n", address)

	for {
		conn, err := listener.Accept()
		if err != nil {
			n.logger.Sugar().Errorf("failed to accept connection: %v\n", err)
			continue
		}

		remoteAddr := conn.RemoteAddr().String()
		n.Lock()
		n.connections[remoteAddr] = conn
		callback()
		n.Unlock()
		n.isConnected = true
		n.retryDelay = 2 * time.Second

		n.logger.Sugar().Infof("connected to remote peer %s\n", remoteAddr)
		go n.listenForMessages(conn)
	}
}

// retryConnect attempts to connect to a remote peer.
func (n *TCPNetwork) retryConnect(remoteID, remoteIP string, remotePort int) {
	for {
		n.Lock()
		_, exists := n.connections[remoteID]
		n.Unlock()

		if exists {
			time.Sleep(5 * time.Second)
			continue
		}

		address := fmt.Sprintf("%s:%d", remoteIP, remotePort)
		conn, err := net.Dial("tcp", address)

		if err != nil {
			n.logger.Sugar().Errorf("failed to connect to %s: %v. Retrying in %v...", remoteID, err, n.retryDelay)
			time.Sleep(n.retryDelay)
			if n.retryDelay < 30*time.Second {
				n.retryDelay *= 2
			}
			continue
		}

		n.Lock()
		n.connections[remoteID] = conn
		n.Unlock()
		n.logger.Sugar().Infof("successfully connected to peer %s!", remoteID)

		go n.listenForMessages(conn)
	}
}

// Send sends a message to a specified remote peer.
func (n *TCPNetwork) Send(remoteID, messageType string, payload []byte) error {
	n.Lock()
	conn, exists := n.connections[remoteID]
	n.Unlock()

	if !exists {
		return fmt.Errorf("not connected to peer %s", remoteID)
	}

	msg := Message{
		Type:      messageType,
		Payload:   payload,
		Source:    n.localPeer,
		Target:    PeerInfo{ID: remoteID},
		Timestamp: time.Now().Unix(),
	}

	data, err := json.Marshal(msg)
	if err != nil {
		return fmt.Errorf("failed to marshal message: %v", err)
	}

	_, err = conn.Write(append(data, '\n'))
	if err != nil {
		n.logger.Sugar().Errorf("failed to send message to %s: %v. Reconnecting...", remoteID, err)
		n.Lock()
		delete(n.connections, remoteID)
		n.Unlock()
		go n.retryConnect(remoteID, "", 0)
		return fmt.Errorf("failed to send message: %v", err)
	}

	return nil
}

// RegisterHandler registers a callback for a message type.
func (n *TCPNetwork) RegisterHandler(messageType string, callback NetworkCallback) {
	n.callbacksMu.Lock()
	n.callbacks[messageType] = callback
	n.callbacksMu.Unlock()
}

// listenForMessages listens for incoming messages.
func (n *TCPNetwork) listenForMessages(conn net.Conn) {
	reader := bufio.NewReader(conn)

	for {
		data, err := reader.ReadBytes('\n')
		if err != nil {
			n.logger.Debug("connection lost. Reconnecting...")
			n.Lock()
			for id, c := range n.connections {
				if c == conn {
					delete(n.connections, id)
					go n.retryConnect(id, "", 0)
					break
				}
			}
			n.Unlock()
			return
		}

		var message Message
		if err := json.Unmarshal(data, &message); err != nil {
			n.logger.Sugar().Errorf("failed to unmarshal message: %v\n", err)
			continue
		}

		n.callbacksMu.RLock()
		callback, exists := n.callbacks[message.Type]
		n.callbacksMu.RUnlock()

		if exists {
			go callback(message)
		}
	}
}

func (n *TCPNetwork) IsConnected() bool {
	n.Lock()
	defer n.Unlock()
	return n.isConnected
}