-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathaccepted_connection.go
70 lines (57 loc) · 1.8 KB
/
accepted_connection.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
package pluto
import (
"encoding/json"
"net"
"pluto/pkg/random"
"sync"
"time"
"github.com/google/uuid"
"go.uber.org/zap"
)
var (
AcceptedConnections = make(map[uuid.UUID]AcceptedConnection)
AcceptedConnectionsMutex = new(sync.RWMutex)
)
const ConnectionTokenLength = 32
type AcceptedConnection struct {
ID uuid.UUID `json:"connection_id"`
Token string `json:"connection_token"`
net.Conn `json:"-"`
}
var acceptor = NewInlineProcessor(func(processable Processable) (Processable, bool) {
connection := AcceptedConnection{
ID: uuid.New(),
Token: random.String(ConnectionTokenLength),
Conn: processable.GetBody().(map[string]any)["connection"].(net.Conn),
}
b, err := json.Marshal(OutGoingProcessable{
Consumer: ExternalIdentifier{
Name: "CONNECTION_ACCEPTOR",
Kind: KindPipeline,
},
Body: connection,
})
if err != nil {
Log.Error("Marshal OutGoingProcessable", zap.Error(err))
return processable, false
}
if err := connection.SetWriteDeadline(time.Now().Add(time.Second * 2)); err != nil {
Log.Error("Set write deadline", zap.Error(err))
return processable, false
}
if _, err := connection.Write(b); err != nil {
Log.Debug("Write bytes to connection", zap.Error(err))
return processable, false
}
Log.Debug("New connection accepted", zap.String("remote_address", connection.RemoteAddr().String()))
ApplicationLogger.Debug(ApplicationLog{
Message: "New connection accepted",
Extra: map[string]any{"remote_address": connection.RemoteAddr().String()},
})
AcceptedConnectionsMutex.Lock()
AcceptedConnections[connection.ID] = connection
AcceptedConnectionsMutex.Unlock()
processable.GetBody().(map[string]any)["connection_id"] = connection.ID
processable.GetBody().(map[string]any)["connection_token"] = connection.Token
return processable, true
})