File size: 4,891 Bytes
6fefda3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package balancer

import (
	"context"
	"github.com/go-resty/resty/v2"
	"jetbrains-ai-proxy/internal/types"
	"log"
	"sync"
	"time"
)

// HealthChecker JWT健康检查器
type HealthChecker struct {
	balancer      JWTBalancer
	client        *resty.Client
	checkInterval time.Duration
	timeout       time.Duration
	maxRetries    int
	stopChan      chan struct{}
	wg            sync.WaitGroup
	running       bool
	mutex         sync.RWMutex
}

// NewHealthChecker 创建健康检查器
func NewHealthChecker(balancer JWTBalancer) *HealthChecker {
	client := resty.New().
		SetTimeout(10 * time.Second).
		SetHeaders(map[string]string{
			"Content-Type": "application/json",
		})

	return &HealthChecker{
		balancer:      balancer,
		client:        client,
		checkInterval: 30 * time.Second, // 每30秒检查一次
		timeout:       10 * time.Second,
		maxRetries:    3,
		stopChan:      make(chan struct{}),
	}
}

// Start 启动健康检查
func (hc *HealthChecker) Start() {
	hc.mutex.Lock()
	defer hc.mutex.Unlock()

	if hc.running {
		return
	}

	hc.running = true
	hc.wg.Add(1)

	go hc.healthCheckLoop()
	log.Println("JWT health checker started")
}

// Stop 停止健康检查
func (hc *HealthChecker) Stop() {
	hc.mutex.Lock()
	defer hc.mutex.Unlock()

	if !hc.running {
		return
	}

	hc.running = false
	close(hc.stopChan)
	hc.wg.Wait()
	log.Println("JWT health checker stopped")
}

// healthCheckLoop 健康检查循环
func (hc *HealthChecker) healthCheckLoop() {
	defer hc.wg.Done()

	ticker := time.NewTicker(hc.checkInterval)
	defer ticker.Stop()

	// 启动时立即执行一次检查
	hc.performHealthCheck()

	for {
		select {
		case <-ticker.C:
			hc.performHealthCheck()
		case <-hc.stopChan:
			return
		}
	}
}

// performHealthCheck 执行健康检查
func (hc *HealthChecker) performHealthCheck() {
	log.Println("Performing JWT health check...")

	// 获取所有tokens进行检查
	baseBalancer, ok := hc.balancer.(*BaseBalancer)
	if !ok {
		log.Println("Warning: Cannot access tokens for health check")
		return
	}

	baseBalancer.mutex.RLock()
	tokens := make([]string, 0, len(baseBalancer.tokens))
	for token := range baseBalancer.tokens {
		tokens = append(tokens, token)
	}
	baseBalancer.mutex.RUnlock()

	// 并发检查所有tokens
	var wg sync.WaitGroup
	for _, token := range tokens {
		wg.Add(1)
		go func(t string) {
			defer wg.Done()
			hc.checkTokenHealth(t)
		}(token)
	}
	wg.Wait()

	healthyCount := hc.balancer.GetHealthyTokenCount()
	totalCount := hc.balancer.GetTotalTokenCount()
	log.Printf("Health check completed: %d/%d tokens healthy", healthyCount, totalCount)
}

// checkTokenHealth 检查单个token的健康状态
func (hc *HealthChecker) checkTokenHealth(token string) {
	ctx, cancel := context.WithTimeout(context.Background(), hc.timeout)
	defer cancel()

	// 创建一个简单的测试请求
	testRequest := &types.JetbrainsRequest{
		Prompt:  types.PROMPT,
		Profile: "openai-gpt-4o", // 使用一个通用的profile进行测试
		Chat: types.ChatField{
			MessageField: []types.MessageField{
				{
					Type:    "user_message",
					Content: "test", // 简单的测试消息
				},
			},
		},
	}

	success := false
	for retry := 0; retry < hc.maxRetries; retry++ {
		if hc.testTokenRequest(ctx, token, testRequest) {
			success = true
			break
		}

		// 重试前等待一小段时间
		if retry < hc.maxRetries-1 {
			time.Sleep(time.Second)
		}
	}

	if success {
		hc.balancer.MarkTokenHealthy(token)
	} else {
		hc.balancer.MarkTokenUnhealthy(token)
		log.Printf("JWT token health check failed: %s...", token[:min(len(token), 10)])
	}
}

// testTokenRequest 测试token请求
func (hc *HealthChecker) testTokenRequest(ctx context.Context, token string, req *types.JetbrainsRequest) bool {
	resp, err := hc.client.R().
		SetContext(ctx).
		SetHeader(types.JwtTokenKey, token).
		SetBody(req).
		Post(types.ChatStreamV7)

	if err != nil {
		log.Printf("Health check request error for token %s...: %v", token[:min(len(token), 10)], err)
		return false
	}

	// 检查响应状态码
	if resp.StatusCode() == 200 {
		return true
	}

	// 401表示token无效,403可能表示配额用完但token有效
	if resp.StatusCode() == 403 {
		// 配额用完但token有效,仍然标记为健康
		return true
	}

	log.Printf("Health check failed for token %s...: status %d",
		token[:min(len(token), 10)], resp.StatusCode())
	return false
}

// SetCheckInterval 设置检查间隔
func (hc *HealthChecker) SetCheckInterval(interval time.Duration) {
	hc.mutex.Lock()
	defer hc.mutex.Unlock()
	hc.checkInterval = interval
}

// SetTimeout 设置请求超时
func (hc *HealthChecker) SetTimeout(timeout time.Duration) {
	hc.mutex.Lock()
	defer hc.mutex.Unlock()
	hc.timeout = timeout
}

// SetMaxRetries 设置最大重试次数
func (hc *HealthChecker) SetMaxRetries(retries int) {
	hc.mutex.Lock()
	defer hc.mutex.Unlock()
	hc.maxRetries = retries
}