-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathincoming_connection.go
81 lines (71 loc) · 2.01 KB
/
incoming_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
71
72
73
74
75
76
77
78
79
80
81
package stableinterfaces
import (
"errors"
"sync"
"sync/atomic"
)
type (
IncomingConnection struct {
instanceID, ConnectionID string
Meta map[string]any
acceptChan chan *connectionPair
rejectChan chan error
}
Connection struct {
ConnectionID string
}
)
var (
ErrIncomingConnectionRejected = errors.New("incoming connection rejected")
ErrIncomingConnectionNotHandled = errors.New("incoming connection rejected due to not being handled")
)
func newIncomingConnection(instanceID, connectionID string, meta map[string]any) *IncomingConnection {
return &IncomingConnection{
ConnectionID: connectionID,
instanceID: instanceID,
Meta: meta,
acceptChan: make(chan *connectionPair, 1),
rejectChan: make(chan error, 1),
}
}
// Accept binds the connection to the interface, and you can now send messages to the InterfaceConnection.
func (ic *IncomingConnection) Accept() *InterfaceConnection {
managerToInterface := make(chan any)
interfaceToManager := make(chan any)
closedChan := make(chan any)
closed := atomic.Bool{}
connPair := connectionPair{
ID: ic.ConnectionID,
closedChan: closedChan,
InterfaceSide: InterfaceConnection{
ID: ic.ConnectionID,
onClose: nil,
onCloseMu: &sync.Mutex{},
OnRecv: nil,
closed: &closed,
closedChan: closedChan,
sendChan: interfaceToManager,
recvChan: managerToInterface,
side: interfaceSide,
},
ManagerSide: InterfaceConnection{
ID: ic.ConnectionID,
onClose: nil,
onCloseMu: &sync.Mutex{},
OnRecv: nil,
closed: &closed,
closedChan: closedChan,
sendChan: managerToInterface,
recvChan: interfaceToManager,
side: managerSide,
},
}
// Setup listeners in goroutines
go launchConnectionPairListener(&connPair)
ic.acceptChan <- &connPair
return &connPair.InterfaceSide
}
// Reject denies a connection with a given reason
func (ic *IncomingConnection) Reject(err error) {
ic.rejectChan <- err
}