forked from jcelliott/turnpike
-
Notifications
You must be signed in to change notification settings - Fork 3
/
session.go
79 lines (66 loc) · 1.35 KB
/
session.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
package turnpike
import (
"fmt"
)
const (
MAX_REQUEST_ID = 1 << 53
)
// Session represents an active WAMP session
type Session struct {
Peer
Id ID
Details map[string]interface{}
lastRequestId ID
kill chan URI
}
func (s Session) String() string {
return fmt.Sprintf("%d", s.Id)
}
func (s *Session) NextRequestId() ID {
s.lastRequestId++
// max value is 2^53
if s.lastRequestId > MAX_REQUEST_ID {
s.lastRequestId = 1
}
return s.lastRequestId
}
// localPipe creates two linked sessions. Messages sent to one will
// appear in the Receive of the other. This is useful for implementing
// client sessions
func localPipe() (*localPeer, *localPeer) {
aToB := make(chan Message, 100)
bToA := make(chan Message, 100)
a := &localPeer{
incoming: bToA,
outgoing: aToB,
}
b := &localPeer{
incoming: aToB,
outgoing: bToA,
}
return a, b
}
type localPeer struct {
outgoing chan<- Message
incoming <-chan Message
}
func (s *localPeer) Receive() <-chan Message {
return s.incoming
}
func (s *localPeer) Send(msg Message) (err error) {
defer func() {
// just in case Close is called before Send
if r := recover(); r != nil {
err = fmt.Errorf("Attempt to write after Close()")
}
}()
s.outgoing <- msg
return
}
func (s *localPeer) Close() error {
if s.outgoing != nil {
close(s.outgoing)
s.outgoing = nil
}
return nil
}