-
Notifications
You must be signed in to change notification settings - Fork 1
/
connection.go
92 lines (89 loc) · 1.68 KB
/
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
82
83
84
85
86
87
88
89
90
91
92
package lagoon
import (
"net"
"sync"
"time"
)
type Connection struct {
// safe
l *Lagoon
// unsafe
net.Conn
disabled bool
idle time.Time
mu sync.Mutex
}
func (self *Connection) IsValid() bool {
if self == nil {
return false
}
return true
}
func (self *Lagoon) createConnection(
conn net.Conn,
) *Connection {
return &Connection{
l: self,
Conn: conn,
idle: time.Now(),
}
}
func (self *Connection) Disable() {
self.mu.Lock()
self.disabled = true
self.mu.Unlock()
}
func (self *Connection) Close() error {
// lock parent
self.l.mu.Lock()
defer self.l.mu.Unlock()
return self.close()
}
func (self *Connection) close() error {
// lock self
self.mu.Lock()
defer self.mu.Unlock()
return self.remove()
}
func (self *Connection) remove() error {
// assumed that parent and self are both locked
var err error
// check if connection is in active
if _, ok := self.l.active[self]; ok {
// remove from active
delete(self.l.active, self)
if self.disabled {
// close connection
err = self.Conn.Close()
// release buffer
self.l.config.Buffer.release()
} else {
// return to available
self.idle = time.Now()
self.l.available[self] = struct{}{}
// DO NOT RELEASE BUFFER!!!
}
} else {
// check if connection is in available
if _, ok := self.l.available[self]; ok {
// remove from available
delete(self.l.available, self)
// close connection
err = self.Conn.Close()
// release buffer
self.l.config.Buffer.release()
} else {
// not found, wtf?
// close connection
err = self.Conn.Close()
// DO NOT RELEASE BUFFER!!!
}
}
// toggle tick
self.l.toggleTick()
// closed
if err != nil {
return err
}
return nil
}