-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.go
More file actions
101 lines (84 loc) · 2.38 KB
/
Copy pathsession.go
File metadata and controls
101 lines (84 loc) · 2.38 KB
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
package netpipe
import (
"sync"
"time"
"github.com/google/uuid"
)
// Session resumption allows a client to reconnect and be recognized as the
// same logical client. The server assigns a session UUID on first connect,
// the client stores it, and sends it back on reconnect.
//
// Wire: server sends [flagSession][16B UUID] after accept.
// client sends [flagSession][16B UUID] as first frame on reconnect.
//
// If the server recognizes the session, the client gets the same ID.
// Sessions expire after sessionTTL if not resumed.
const (
sessionUUIDSize = 16
sessionTTL = 5 * time.Minute // how long a disconnected session is kept
)
// sessionEntry tracks one session.
type sessionEntry struct {
clientID string
createdAt time.Time
lastSeen time.Time
}
// sessionRegistry manages session state on the server.
type sessionRegistry struct {
mu sync.Mutex
sessions map[string]*sessionEntry // key = session UUID string
}
func newSessionRegistry() *sessionRegistry {
return &sessionRegistry{
sessions: make(map[string]*sessionEntry),
}
}
// create makes a new session for a client. Returns the session UUID string.
func (sr *sessionRegistry) create(clientID string) string {
sr.mu.Lock()
defer sr.mu.Unlock()
// clean up expired sessions
sr.cleanExpiredLocked()
sessionID := uuid.New().String()
sr.sessions[sessionID] = &sessionEntry{
clientID: clientID,
createdAt: time.Now(),
lastSeen: time.Now(),
}
return sessionID
}
// resume looks up a session by ID. If found and not expired, returns the
// original clientID and true. Otherwise returns empty and false.
func (sr *sessionRegistry) resume(sessionID string) (string, bool) {
sr.mu.Lock()
defer sr.mu.Unlock()
sr.cleanExpiredLocked()
entry, ok := sr.sessions[sessionID]
if !ok {
return "", false
}
entry.lastSeen = time.Now()
return entry.clientID, true
}
// touch updates the last-seen time for a session.
func (sr *sessionRegistry) touch(sessionID string) {
sr.mu.Lock()
if entry, ok := sr.sessions[sessionID]; ok {
entry.lastSeen = time.Now()
}
sr.mu.Unlock()
}
// remove deletes a session.
func (sr *sessionRegistry) remove(sessionID string) {
sr.mu.Lock()
delete(sr.sessions, sessionID)
sr.mu.Unlock()
}
func (sr *sessionRegistry) cleanExpiredLocked() {
now := time.Now()
for id, entry := range sr.sessions {
if now.Sub(entry.lastSeen) > sessionTTL {
delete(sr.sessions, id)
}
}
}