File size: 1,691 Bytes
6bc074c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package handler

import (
	"aurora/internal/chatgpt"
	"log"
	"sync"
	"time"
)

// SessionManager 按 conversationID 缓存 ChatClientState,
// 使得同一对话的多轮请求复用相同的 DeviceID / SessionID。
type SessionManager struct {
	mu       sync.RWMutex
	sessions map[string]*sessionEntry
	ttl      time.Duration
}

type sessionEntry struct {
	state    *chatgpt.ChatClientState
	lastUsed time.Time
}

const defaultSessionTTL = 30 * time.Minute

func NewSessionManager() *SessionManager {
	sm := &SessionManager{
		sessions: make(map[string]*sessionEntry),
		ttl:      defaultSessionTTL,
	}
	go sm.cleanupLoop()
	return sm
}

func (sm *SessionManager) Get(conversationID string) *chatgpt.ChatClientState {
	if conversationID == "" {
		return nil
	}
	sm.mu.RLock()
	entry, ok := sm.sessions[conversationID]
	sm.mu.RUnlock()
	if !ok {
		return nil
	}
	sm.mu.Lock()
	entry.lastUsed = time.Now()
	sm.mu.Unlock()
	return entry.state
}

func (sm *SessionManager) Register(conversationID string, state *chatgpt.ChatClientState) {
	if conversationID == "" || state == nil {
		return
	}
	sm.mu.Lock()
	defer sm.mu.Unlock()
	sm.sessions[conversationID] = &sessionEntry{
		state:    state,
		lastUsed: time.Now(),
	}
}

func (sm *SessionManager) cleanupLoop() {
	ticker := time.NewTicker(10 * time.Minute)
	defer ticker.Stop()
	for range ticker.C {
		sm.mu.Lock()
		now := time.Now()
		removed := 0
		for convID, entry := range sm.sessions {
			if now.Sub(entry.lastUsed) > sm.ttl {
				delete(sm.sessions, convID)
				removed++
			}
		}
		if removed > 0 {
			log.Printf("[session] 清理过期 session %d 个,当前活跃 %d 个", removed, len(sm.sessions))
		}
		sm.mu.Unlock()
	}
}