This commit introduces a major architectural refactoring to improve quota management, centralize logging, and streamline the relay handling logic. Key changes: - **Pre-consume Quota:** Implements a new mechanism to check and reserve user quota *before* making the request to the upstream provider. This ensures more accurate quota deduction and prevents users from exceeding their limits due to concurrent requests. - **Unified Relay Handlers:** Refactors the relay logic to use generic handlers (e.g., `ChatHandler`, `ImageHandler`) instead of provider-specific implementations. This significantly reduces code duplication and simplifies adding new channels. - **Centralized Logger:** A new dedicated `logger` package is introduced, and all system logging calls are migrated to use it, moving this responsibility out of the `common` package. - **Code Reorganization:** DTOs are generalized (e.g., `dalle.go` -> `openai_image.go`) and utility code is moved to more appropriate packages (e.g., `common/http.go` -> `service/http.go`) for better code structure.
58 lines
1.5 KiB
Go
58 lines
1.5 KiB
Go
package service
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"one-api/logger"
|
|
"one-api/setting"
|
|
"strings"
|
|
)
|
|
|
|
// WorkerRequest Worker请求的数据结构
|
|
type WorkerRequest struct {
|
|
URL string `json:"url"`
|
|
Key string `json:"key"`
|
|
Method string `json:"method,omitempty"`
|
|
Headers map[string]string `json:"headers,omitempty"`
|
|
Body json.RawMessage `json:"body,omitempty"`
|
|
}
|
|
|
|
// DoWorkerRequest 通过Worker发送请求
|
|
func DoWorkerRequest(req *WorkerRequest) (*http.Response, error) {
|
|
if !setting.EnableWorker() {
|
|
return nil, fmt.Errorf("worker not enabled")
|
|
}
|
|
if !setting.WorkerAllowHttpImageRequestEnabled && !strings.HasPrefix(req.URL, "https") {
|
|
return nil, fmt.Errorf("only support https url")
|
|
}
|
|
|
|
workerUrl := setting.WorkerUrl
|
|
if !strings.HasSuffix(workerUrl, "/") {
|
|
workerUrl += "/"
|
|
}
|
|
|
|
// 序列化worker请求数据
|
|
workerPayload, err := json.Marshal(req)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to marshal worker payload: %v", err)
|
|
}
|
|
|
|
return http.Post(workerUrl, "application/json", bytes.NewBuffer(workerPayload))
|
|
}
|
|
|
|
func DoDownloadRequest(originUrl string) (resp *http.Response, err error) {
|
|
if setting.EnableWorker() {
|
|
logger.SysLog(fmt.Sprintf("downloading file from worker: %s", originUrl))
|
|
req := &WorkerRequest{
|
|
URL: originUrl,
|
|
Key: setting.WorkerValidKey,
|
|
}
|
|
return DoWorkerRequest(req)
|
|
} else {
|
|
logger.SysLog(fmt.Sprintf("downloading from origin: %s", originUrl))
|
|
return http.Get(originUrl)
|
|
}
|
|
}
|