-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
connect_requests.go
111 lines (95 loc) · 2.23 KB
/
connect_requests.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
// Copyright 2021 Kirill Scherba <[email protected]>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Teonet connect requests module
package teonet
import (
"sync"
"time"
"github.com/teonet-go/tru"
)
// Struct and methods receiver
type connectRequests struct {
m map[string]*connectRequestsData
sync.RWMutex
}
// Connect request data
type connectRequestsData struct {
*ConnectToData
*chanWait
time.Time
}
// Wait connect result channel
type chanWait chan []byte
// Check if channel is open (is not closed)
func (c chanWait) IsOpen() (ok bool) {
ok = true
select {
case _, ok = <-c:
default:
}
return
}
// newPeerRequests creates new peer request object
func (teo *Teonet) newPeerRequests() {
teo.peerRequests = teo.newConnectRequests()
}
// newConnRequests creates new connection request object
func (teo *Teonet) newConnRequests() {
teo.connRequests = teo.newConnectRequests()
}
// newConnectRequests creates new connect request object
func (teo Teonet) newConnectRequests() *connectRequests {
c := new(connectRequests)
c.m = make(map[string]*connectRequestsData)
go c.process()
return c
}
// add connect request
func (p *connectRequests) add(con *ConnectToData, waits ...*chanWait) {
var wait *chanWait
if len(waits) > 0 {
wait = waits[0]
}
p.Lock()
defer p.Unlock()
p.m[con.ID] = &connectRequestsData{con, wait, time.Now()}
}
// del connect request by id and return ok true and connectRequestsData if
// request exists
func (p *connectRequests) del(id string) (res *connectRequestsData, ok bool) {
p.Lock()
defer p.Unlock()
res, ok = p.m[id]
if ok {
delete(p.m, id)
}
return
}
// get connect request by id
func (p *connectRequests) get(id string) (res *connectRequestsData, ok bool) {
p.RLock()
defer p.RUnlock()
res, ok = p.m[id]
return
}
// removeDummy remove dummy requests
func (p *connectRequests) removeDummy() {
p.RLock()
for id, rec := range p.m {
if time.Since(rec.Time) > tru.ClientConnectTimeout {
p.RUnlock()
p.del(id)
p.removeDummy()
return
}
}
p.RUnlock()
}
// process periodically remove dummy requests
func (p *connectRequests) process() {
for {
time.Sleep(tru.ClientConnectTimeout)
p.removeDummy()
}
}