Skip to content
This repository was archived by the owner on May 13, 2026. It is now read-only.

Commit 90610a5

Browse files
authored
Merge pull request #93 from latticeon/feature/session-management
feat: 添加会话管理功能
2 parents 71cdcb4 + f6296d5 commit 90610a5

26 files changed

Lines changed: 1648 additions & 930 deletions

‎internal/adapter/openai/deps.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ type DeepSeekCaller interface {
1919
CreateSession(ctx context.Context, a *auth.RequestAuth, maxAttempts int) (string, error)
2020
GetPow(ctx context.Context, a *auth.RequestAuth, maxAttempts int) (string, error)
2121
CallCompletion(ctx context.Context, a *auth.RequestAuth, payload map[string]any, powResp string, maxAttempts int) (*http.Response, error)
22+
DeleteAllSessionsForToken(ctx context.Context, token string) error
2223
}
2324

2425
type ConfigReader interface {
@@ -28,6 +29,7 @@ type ConfigReader interface {
2829
ToolcallEarlyEmitConfidence() string
2930
ResponsesStoreTTLSeconds() int
3031
EmbeddingsProvider() string
32+
AutoDeleteSessions() bool
3133
}
3234

3335
var _ AuthResolver = (*auth.Resolver)(nil)

‎internal/adapter/openai/deps_injection_test.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ func (m mockOpenAIConfig) ToolcallMode() string { return m.toolMo
1919
func (m mockOpenAIConfig) ToolcallEarlyEmitConfidence() string { return m.earlyEmit }
2020
func (m mockOpenAIConfig) ResponsesStoreTTLSeconds() int { return m.responsesTTL }
2121
func (m mockOpenAIConfig) EmbeddingsProvider() string { return m.embedProv }
22+
func (m mockOpenAIConfig) AutoDeleteSessions() bool { return false }
2223

2324
func TestNormalizeOpenAIChatRequestWithConfigInterface(t *testing.T) {
2425
cfg := mockOpenAIConfig{

‎internal/adapter/openai/handler_chat.go‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,23 @@ func (h *Handler) ChatCompletions(w http.ResponseWriter, r *http.Request) {
3535
writeOpenAIError(w, status, detail)
3636
return
3737
}
38-
defer h.Auth.Release(a)
38+
defer func() {
39+
// 自动删除会话(同步)
40+
// 必须在 Release 之前同步删除,否则:
41+
// 1. 异步删除时账号已被 Release
42+
// 2. 新请求可能获取到同一账号并开始使用
43+
// 3. 异步删除仍在进行,会截断新请求正在使用的会话
44+
if h.Store.AutoDeleteSessions() && a.DeepSeekToken != "" {
45+
err := h.DS.DeleteAllSessionsForToken(context.Background(), a.DeepSeekToken)
46+
if err != nil {
47+
config.Logger.Warn("[auto_delete_sessions] failed", "account", a.AccountID, "error", err)
48+
} else {
49+
config.Logger.Debug("[auto_delete_sessions] success", "account", a.AccountID)
50+
}
51+
}
52+
h.Auth.Release(a)
53+
}()
54+
3955
r = r.WithContext(auth.WithAuth(r.Context(), a))
4056

4157
var req map[string]any

‎internal/adapter/openai/stream_status_test.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,10 @@ func (m streamStatusDSStub) CallCompletion(_ context.Context, _ *auth.RequestAut
5353
return m.resp, nil
5454
}
5555

56+
func (m streamStatusDSStub) DeleteAllSessionsForToken(_ context.Context, _ string) error {
57+
return nil
58+
}
59+
5660
func makeOpenAISSEHTTPResponse(lines ...string) *http.Response {
5761
body := strings.Join(lines, "\n")
5862
if !strings.HasSuffix(body, "\n") {

‎internal/admin/deps.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ type ConfigStore interface {
2727
RuntimeAccountMaxInflight() int
2828
RuntimeAccountMaxQueue(defaultSize int) int
2929
RuntimeGlobalMaxInflight(defaultSize int) int
30+
AutoDeleteSessions() bool
3031
}
3132

3233
type PoolController interface {
@@ -40,6 +41,8 @@ type DeepSeekCaller interface {
4041
CreateSession(ctx context.Context, a *auth.RequestAuth, maxAttempts int) (string, error)
4142
GetPow(ctx context.Context, a *auth.RequestAuth, maxAttempts int) (string, error)
4243
CallCompletion(ctx context.Context, a *auth.RequestAuth, payload map[string]any, powResp string, maxAttempts int) (*http.Response, error)
44+
GetSessionCountForToken(ctx context.Context, token string) (*deepseek.SessionStats, error)
45+
DeleteAllSessionsForToken(ctx context.Context, token string) error
4346
}
4447

4548
var _ ConfigStore = (*config.Store)(nil)

‎internal/admin/handler.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ func RegisterRoutes(r chi.Router, h *Handler) {
3131
pr.Get("/queue/status", h.queueStatus)
3232
pr.Post("/accounts/test", h.testSingleAccount)
3333
pr.Post("/accounts/test-all", h.testAllAccounts)
34+
pr.Post("/accounts/sessions/delete-all", h.deleteAllSessions)
3435
pr.Post("/import", h.batchImport)
3536
pr.Post("/test", h.testAPI)
3637
pr.Post("/vercel/sync", h.syncVercel)

‎internal/admin/handler_accounts_testing.go‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ func runAccountTestsConcurrently(accounts []config.Account, maxConcurrency int,
8989
func (h *Handler) testAccount(ctx context.Context, acc config.Account, model, message string) map[string]any {
9090
start := time.Now()
9191
identifier := acc.Identifier()
92-
result := map[string]any{"account": identifier, "success": false, "response_time": 0, "message": "", "model": model}
92+
result := map[string]any{"account": identifier, "success": false, "response_time": 0, "message": "", "model": model, "session_count": 0}
9393
defer func() {
9494
status := "failed"
9595
if ok, _ := result["success"].(bool); ok {
@@ -124,6 +124,13 @@ func (h *Handler) testAccount(ctx context.Context, acc config.Account, model, me
124124
return result
125125
}
126126
}
127+
128+
// 获取会话数量
129+
sessionStats, sessionErr := h.DS.GetSessionCountForToken(ctx, token)
130+
if sessionErr == nil && sessionStats != nil {
131+
result["session_count"] = sessionStats.FirstPageCount
132+
}
133+
127134
if strings.TrimSpace(message) == "" {
128135
result["success"] = true
129136
result["message"] = "API 测试成功(仅会话创建)"
@@ -210,3 +217,39 @@ func (h *Handler) testAPI(w http.ResponseWriter, r *http.Request) {
210217
}
211218
writeJSON(w, http.StatusOK, map[string]any{"success": false, "status_code": resp.StatusCode, "response": string(body)})
212219
}
220+
221+
func (h *Handler) deleteAllSessions(w http.ResponseWriter, r *http.Request) {
222+
var req map[string]any
223+
_ = json.NewDecoder(r.Body).Decode(&req)
224+
identifier, _ := req["identifier"].(string)
225+
if strings.TrimSpace(identifier) == "" {
226+
writeJSON(w, http.StatusBadRequest, map[string]any{"detail": "需要账号标识(identifier / email / mobile)"})
227+
return
228+
}
229+
acc, ok := findAccountByIdentifier(h.Store, identifier)
230+
if !ok {
231+
writeJSON(w, http.StatusNotFound, map[string]any{"detail": "账号不存在"})
232+
return
233+
}
234+
235+
// 获取 token
236+
token := strings.TrimSpace(acc.Token)
237+
if token == "" {
238+
newToken, err := h.DS.Login(r.Context(), acc)
239+
if err != nil {
240+
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "登录失败: " + err.Error()})
241+
return
242+
}
243+
token = newToken
244+
_ = h.Store.UpdateAccountToken(acc.Identifier(), token)
245+
}
246+
247+
// 删除所有会话
248+
err := h.DS.DeleteAllSessionsForToken(r.Context(), token)
249+
if err != nil {
250+
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "删除失败: " + err.Error()})
251+
return
252+
}
253+
254+
writeJSON(w, http.StatusOK, map[string]any{"success": true, "message": "删除成功"})
255+
}

‎internal/admin/handler_accounts_testing_test.go‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99

1010
"ds2api/internal/auth"
1111
"ds2api/internal/config"
12+
"ds2api/internal/deepseek"
1213
)
1314

1415
type testingDSMock struct {
@@ -38,6 +39,14 @@ func (m *testingDSMock) CallCompletion(_ context.Context, _ *auth.RequestAuth, _
3839
return nil, errors.New("should not call CallCompletion in this test")
3940
}
4041

42+
func (m *testingDSMock) DeleteAllSessionsForToken(_ context.Context, _ string) error {
43+
return nil
44+
}
45+
46+
func (m *testingDSMock) GetSessionCountForToken(_ context.Context, _ string) (*deepseek.SessionStats, error) {
47+
return &deepseek.SessionStats{Success: true}, nil
48+
}
49+
4150
func TestTestAccount_BatchModeOnlyCreatesSession(t *testing.T) {
4251
t.Setenv("DS2API_CONFIG_JSON", `{"accounts":[{"email":"batch@example.com","password":"pwd","token":""}]}`)
4352
store := config.LoadStore()

‎internal/admin/handler_settings_parse.go‎

Lines changed: 40 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,38 @@ import (
77
"ds2api/internal/config"
88
)
99

10-
func parseSettingsUpdateRequest(req map[string]any) (*config.AdminConfig, *config.RuntimeConfig, *config.ToolcallConfig, *config.ResponsesConfig, *config.EmbeddingsConfig, map[string]string, map[string]string, error) {
10+
func boolFrom(v any) bool {
11+
if v == nil {
12+
return false
13+
}
14+
switch x := v.(type) {
15+
case bool:
16+
return x
17+
case string:
18+
return strings.ToLower(strings.TrimSpace(x)) == "true"
19+
default:
20+
return false
21+
}
22+
}
23+
24+
func parseSettingsUpdateRequest(req map[string]any) (*config.AdminConfig, *config.RuntimeConfig, *config.ToolcallConfig, *config.ResponsesConfig, *config.EmbeddingsConfig, *config.AutoDeleteConfig, map[string]string, map[string]string, error) {
1125
var (
12-
adminCfg *config.AdminConfig
13-
runtimeCfg *config.RuntimeConfig
14-
toolcallCfg *config.ToolcallConfig
15-
respCfg *config.ResponsesConfig
16-
embCfg *config.EmbeddingsConfig
17-
claudeMap map[string]string
18-
aliasMap map[string]string
26+
adminCfg *config.AdminConfig
27+
runtimeCfg *config.RuntimeConfig
28+
toolcallCfg *config.ToolcallConfig
29+
respCfg *config.ResponsesConfig
30+
embCfg *config.EmbeddingsConfig
31+
autoDeleteCfg *config.AutoDeleteConfig
32+
claudeMap map[string]string
33+
aliasMap map[string]string
1934
)
2035

2136
if raw, ok := req["admin"].(map[string]any); ok {
2237
cfg := &config.AdminConfig{}
2338
if v, exists := raw["jwt_expire_hours"]; exists {
2439
n := intFrom(v)
2540
if n < 1 || n > 720 {
26-
return nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("admin.jwt_expire_hours must be between 1 and 720")
41+
return nil, nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("admin.jwt_expire_hours must be between 1 and 720")
2742
}
2843
cfg.JWTExpireHours = n
2944
}
@@ -35,26 +50,26 @@ func parseSettingsUpdateRequest(req map[string]any) (*config.AdminConfig, *confi
3550
if v, exists := raw["account_max_inflight"]; exists {
3651
n := intFrom(v)
3752
if n < 1 || n > 256 {
38-
return nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("runtime.account_max_inflight must be between 1 and 256")
53+
return nil, nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("runtime.account_max_inflight must be between 1 and 256")
3954
}
4055
cfg.AccountMaxInflight = n
4156
}
4257
if v, exists := raw["account_max_queue"]; exists {
4358
n := intFrom(v)
4459
if n < 1 || n > 200000 {
45-
return nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("runtime.account_max_queue must be between 1 and 200000")
60+
return nil, nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("runtime.account_max_queue must be between 1 and 200000")
4661
}
4762
cfg.AccountMaxQueue = n
4863
}
4964
if v, exists := raw["global_max_inflight"]; exists {
5065
n := intFrom(v)
5166
if n < 1 || n > 200000 {
52-
return nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("runtime.global_max_inflight must be between 1 and 200000")
67+
return nil, nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("runtime.global_max_inflight must be between 1 and 200000")
5368
}
5469
cfg.GlobalMaxInflight = n
5570
}
5671
if cfg.AccountMaxInflight > 0 && cfg.GlobalMaxInflight > 0 && cfg.GlobalMaxInflight < cfg.AccountMaxInflight {
57-
return nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("runtime.global_max_inflight must be >= runtime.account_max_inflight")
72+
return nil, nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("runtime.global_max_inflight must be >= runtime.account_max_inflight")
5873
}
5974
runtimeCfg = cfg
6075
}
@@ -67,7 +82,7 @@ func parseSettingsUpdateRequest(req map[string]any) (*config.AdminConfig, *confi
6782
case "feature_match", "off":
6883
cfg.Mode = mode
6984
default:
70-
return nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("toolcall.mode must be feature_match or off")
85+
return nil, nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("toolcall.mode must be feature_match or off")
7186
}
7287
}
7388
if v, exists := raw["early_emit_confidence"]; exists {
@@ -76,7 +91,7 @@ func parseSettingsUpdateRequest(req map[string]any) (*config.AdminConfig, *confi
7691
case "high", "low", "off":
7792
cfg.EarlyEmitConfidence = level
7893
default:
79-
return nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("toolcall.early_emit_confidence must be high, low or off")
94+
return nil, nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("toolcall.early_emit_confidence must be high, low or off")
8095
}
8196
}
8297
toolcallCfg = cfg
@@ -87,7 +102,7 @@ func parseSettingsUpdateRequest(req map[string]any) (*config.AdminConfig, *confi
87102
if v, exists := raw["store_ttl_seconds"]; exists {
88103
n := intFrom(v)
89104
if n < 30 || n > 86400 {
90-
return nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("responses.store_ttl_seconds must be between 30 and 86400")
105+
return nil, nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("responses.store_ttl_seconds must be between 30 and 86400")
91106
}
92107
cfg.StoreTTLSeconds = n
93108
}
@@ -98,9 +113,6 @@ func parseSettingsUpdateRequest(req map[string]any) (*config.AdminConfig, *confi
98113
cfg := &config.EmbeddingsConfig{}
99114
if v, exists := raw["provider"]; exists {
100115
p := strings.TrimSpace(fmt.Sprintf("%v", v))
101-
if p == "" {
102-
return nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("embeddings.provider cannot be empty")
103-
}
104116
cfg.Provider = p
105117
}
106118
embCfg = cfg
@@ -130,5 +142,13 @@ func parseSettingsUpdateRequest(req map[string]any) (*config.AdminConfig, *confi
130142
}
131143
}
132144

133-
return adminCfg, runtimeCfg, toolcallCfg, respCfg, embCfg, claudeMap, aliasMap, nil
145+
if raw, ok := req["auto_delete"].(map[string]any); ok {
146+
cfg := &config.AutoDeleteConfig{}
147+
if v, exists := raw["sessions"]; exists {
148+
cfg.Sessions = boolFrom(v)
149+
}
150+
autoDeleteCfg = cfg
151+
}
152+
153+
return adminCfg, runtimeCfg, toolcallCfg, respCfg, embCfg, autoDeleteCfg, claudeMap, aliasMap, nil
134154
}

‎internal/admin/handler_settings_read.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ func (h *Handler) getSettings(w http.ResponseWriter, _ *http.Request) {
2828
"toolcall": snap.Toolcall,
2929
"responses": snap.Responses,
3030
"embeddings": snap.Embeddings,
31+
"auto_delete": snap.AutoDelete,
3132
"claude_mapping": settingsClaudeMapping(snap),
3233
"model_aliases": snap.ModelAliases,
3334
"env_backed": h.Store.IsEnvBacked(),

0 commit comments

Comments
 (0)