-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.go
More file actions
335 lines (287 loc) · 7.59 KB
/
session.go
File metadata and controls
335 lines (287 loc) · 7.59 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package flowengine
import (
"sync"
"time"
)
// ===========================================================================
// Session - Session Context Management
// ===========================================================================
// Session represents a session with context chaining.
type Session struct {
// id is the session root identifier.
id string
// rootResponseID is the LLM response ID for the root node (cache prefix).
rootResponseID string
// nodeResponses maps step names to LLM response IDs.
nodeResponses map[string]string
// chain records execution order for cleanup.
chain []string
// messages accumulates session history.
messages []Message
// lastAccessed records the last access time.
lastAccessed time.Time
mu sync.RWMutex
}
// Message represents a session message.
type Message struct {
Role string `json:"role"` // system, user, assistant
Content string `json:"content"`
}
// NewSession creates a new session with the given ID.
func NewSession(id string) *Session {
return &Session{
id: id,
nodeResponses: make(map[string]string),
chain: make([]string, 0),
messages: make([]Message, 0),
lastAccessed: time.Now(),
}
}
// touch updates the last access time.
func (s *Session) touch() {
s.mu.Lock()
defer s.mu.Unlock()
s.touchLocked()
}
func (s *Session) touchLocked() {
s.lastAccessed = time.Now()
}
// LastAccessed returns the session's last access time.
func (s *Session) LastAccessed() time.Time {
s.mu.RLock()
defer s.mu.RUnlock()
return s.lastAccessed
}
// ID returns the session ID.
func (s *Session) ID() string {
return s.id
}
// SetRootResponseID sets the root LLM response ID.
func (s *Session) SetRootResponseID(id string) {
s.mu.Lock()
defer s.mu.Unlock()
s.rootResponseID = id
s.touchLocked()
}
// RootResponseID returns the root LLM response ID.
func (s *Session) RootResponseID() string {
s.mu.RLock()
defer s.mu.RUnlock()
return s.rootResponseID
}
// RecordNode records step execution with its LLM response ID.
func (s *Session) RecordNode(stepName, responseID string) {
s.mu.Lock()
defer s.mu.Unlock()
s.nodeResponses[stepName] = responseID
s.chain = append(s.chain, stepName)
s.touchLocked()
}
// GetResponseID returns the LLM response ID for a step.
func (s *Session) GetResponseID(stepName string) (string, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
id, ok := s.nodeResponses[stepName]
return id, ok
}
// LastResponseID returns the most recent LLM response ID.
func (s *Session) LastResponseID() string {
s.mu.RLock()
defer s.mu.RUnlock()
if len(s.chain) == 0 {
return s.rootResponseID
}
lastStep := s.chain[len(s.chain)-1]
return s.nodeResponses[lastStep]
}
// AppendMessage adds a message to session history.
func (s *Session) AppendMessage(role, content string) {
s.mu.Lock()
defer s.mu.Unlock()
s.messages = append(s.messages, Message{Role: role, Content: content})
s.touchLocked()
}
// Messages returns all session messages.
func (s *Session) Messages() []Message {
s.mu.RLock()
defer s.mu.RUnlock()
result := make([]Message, len(s.messages))
copy(result, s.messages)
return result
}
// Chain returns the execution chain.
func (s *Session) Chain() []string {
s.mu.RLock()
defer s.mu.RUnlock()
result := make([]string, len(s.chain))
copy(result, s.chain)
return result
}
// Clear resets the session state.
func (s *Session) Clear() {
s.mu.Lock()
defer s.mu.Unlock()
s.rootResponseID = ""
s.nodeResponses = make(map[string]string)
s.chain = make([]string, 0)
s.messages = make([]Message, 0)
s.touchLocked()
}
// ===========================================================================
// SessionManager - Manages Multiple Sessions with TTL and Size Limits
// ===========================================================================
// DefaultSessionTTL is the default session TTL (30 minutes).
const DefaultSessionTTL = 30 * time.Minute
// DefaultMaxSessions is the default maximum session count.
const DefaultMaxSessions = 1000
// SessionManager manages sessions.
type SessionManager struct {
sessions map[string]*Session
ttl time.Duration
maxSize int
mu sync.RWMutex
stopClean chan struct{}
cleanOnce sync.Once
}
// SessionManagerOption configures SessionManager.
type SessionManagerOption func(*SessionManager)
// WithTTL sets the session TTL.
func WithTTL(ttl time.Duration) SessionManagerOption {
return func(m *SessionManager) {
m.ttl = ttl
}
}
// WithMaxSessions sets the maximum session count.
func WithMaxSessions(max int) SessionManagerOption {
return func(m *SessionManager) {
m.maxSize = max
}
}
// NewSessionManager creates a new session manager.
func NewSessionManager(opts ...SessionManagerOption) *SessionManager {
m := &SessionManager{
sessions: make(map[string]*Session),
ttl: DefaultSessionTTL,
maxSize: DefaultMaxSessions,
stopClean: make(chan struct{}),
}
for _, opt := range opts {
opt(m)
}
// Start background cleanup goroutine
go m.cleanupLoop()
return m
}
// cleanupLoop periodically removes expired sessions.
func (m *SessionManager) cleanupLoop() {
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for {
select {
case <-m.stopClean:
return
case <-ticker.C:
m.cleanup()
}
}
}
// cleanup removes expired sessions and enforces size limits.
func (m *SessionManager) cleanup() {
m.mu.Lock()
defer m.mu.Unlock()
now := time.Now()
var toDelete []string
// Find expired sessions
for id, sess := range m.sessions {
if now.Sub(sess.LastAccessed()) > m.ttl {
toDelete = append(toDelete, id)
}
}
// Delete expired sessions
for _, id := range toDelete {
delete(m.sessions, id)
}
// Enforce max size by removing oldest sessions
if len(m.sessions) > m.maxSize {
excess := len(m.sessions) - m.maxSize
type sessionAge struct {
id string
time time.Time
}
ages := make([]sessionAge, 0, len(m.sessions))
for id, sess := range m.sessions {
ages = append(ages, sessionAge{id: id, time: sess.LastAccessed()})
}
// Sort oldest first (simple selection for small overflow)
for i := 0; i < excess; i++ {
oldest := i
for j := i + 1; j < len(ages); j++ {
if ages[j].time.Before(ages[oldest].time) {
oldest = j
}
}
ages[i], ages[oldest] = ages[oldest], ages[i]
delete(m.sessions, ages[i].id)
}
}
}
// Stop stops the cleanup goroutine.
func (m *SessionManager) Stop() {
m.cleanOnce.Do(func() {
close(m.stopClean)
})
}
// Get returns or creates a session.
func (m *SessionManager) Get(id string) *Session {
m.mu.Lock()
defer m.mu.Unlock()
if s, ok := m.sessions[id]; ok {
s.touch()
return s
}
s := NewSession(id)
m.sessions[id] = s
return s
}
// GetIfExists returns a session if it exists, nil otherwise.
func (m *SessionManager) GetIfExists(id string) *Session {
m.mu.RLock()
defer m.mu.RUnlock()
if s, ok := m.sessions[id]; ok {
return s
}
return nil
}
// Delete removes a session and all its contexts.
func (m *SessionManager) Delete(id string) {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.sessions, id)
}
// Exists checks if a session exists.
func (m *SessionManager) Exists(id string) bool {
m.mu.RLock()
defer m.mu.RUnlock()
_, ok := m.sessions[id]
return ok
}
// Count returns the number of active sessions.
func (m *SessionManager) Count() int {
m.mu.RLock()
defer m.mu.RUnlock()
return len(m.sessions)
}
// Clear removes all sessions.
func (m *SessionManager) Clear() {
m.mu.Lock()
defer m.mu.Unlock()
m.sessions = make(map[string]*Session)
}
// TTL returns the current TTL setting.
func (m *SessionManager) TTL() time.Duration {
return m.ttl
}
// MaxSize returns the current max size setting.
func (m *SessionManager) MaxSize() int {
return m.maxSize
}