drive_client.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. package geminicli
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "math/rand"
  7. "net/http"
  8. "strconv"
  9. "time"
  10. "github.com/Wei-Shaw/sub2api/internal/pkg/httpclient"
  11. )
  12. // DriveStorageInfo represents Google Drive storage quota information
  13. type DriveStorageInfo struct {
  14. Limit int64 `json:"limit"` // Storage limit in bytes
  15. Usage int64 `json:"usage"` // Current usage in bytes
  16. }
  17. // DriveClient interface for Google Drive API operations
  18. type DriveClient interface {
  19. GetStorageQuota(ctx context.Context, accessToken, proxyURL string) (*DriveStorageInfo, error)
  20. }
  21. type driveClient struct{}
  22. // NewDriveClient creates a new Drive API client
  23. func NewDriveClient() DriveClient {
  24. return &driveClient{}
  25. }
  26. // GetStorageQuota fetches storage quota from Google Drive API
  27. func (c *driveClient) GetStorageQuota(ctx context.Context, accessToken, proxyURL string) (*DriveStorageInfo, error) {
  28. const driveAPIURL = "https://www.googleapis.com/drive/v3/about?fields=storageQuota"
  29. req, err := http.NewRequestWithContext(ctx, "GET", driveAPIURL, nil)
  30. if err != nil {
  31. return nil, fmt.Errorf("failed to create request: %w", err)
  32. }
  33. req.Header.Set("Authorization", "Bearer "+accessToken)
  34. // Get HTTP client with proxy support
  35. client, err := httpclient.GetClient(httpclient.Options{
  36. ProxyURL: proxyURL,
  37. Timeout: 10 * time.Second,
  38. })
  39. if err != nil {
  40. return nil, fmt.Errorf("failed to create HTTP client: %w", err)
  41. }
  42. sleepWithContext := func(d time.Duration) error {
  43. timer := time.NewTimer(d)
  44. defer timer.Stop()
  45. select {
  46. case <-ctx.Done():
  47. return ctx.Err()
  48. case <-timer.C:
  49. return nil
  50. }
  51. }
  52. // Retry logic with exponential backoff (+ jitter) for rate limits and transient failures
  53. var resp *http.Response
  54. maxRetries := 3
  55. rng := rand.New(rand.NewSource(time.Now().UnixNano()))
  56. for attempt := 0; attempt < maxRetries; attempt++ {
  57. if ctx.Err() != nil {
  58. return nil, fmt.Errorf("request cancelled: %w", ctx.Err())
  59. }
  60. resp, err = client.Do(req)
  61. if err != nil {
  62. // Network error retry
  63. if attempt < maxRetries-1 {
  64. backoff := time.Duration(1<<uint(attempt)) * time.Second
  65. jitter := time.Duration(rng.Intn(1000)) * time.Millisecond
  66. if err := sleepWithContext(backoff + jitter); err != nil {
  67. return nil, fmt.Errorf("request cancelled: %w", err)
  68. }
  69. continue
  70. }
  71. return nil, fmt.Errorf("network error after %d attempts: %w", maxRetries, err)
  72. }
  73. // Success
  74. if resp.StatusCode == http.StatusOK {
  75. break
  76. }
  77. // Retry 429, 500, 502, 503 with exponential backoff + jitter
  78. if (resp.StatusCode == http.StatusTooManyRequests ||
  79. resp.StatusCode == http.StatusInternalServerError ||
  80. resp.StatusCode == http.StatusBadGateway ||
  81. resp.StatusCode == http.StatusServiceUnavailable) && attempt < maxRetries-1 {
  82. if err := func() error {
  83. defer func() { _ = resp.Body.Close() }()
  84. backoff := time.Duration(1<<uint(attempt)) * time.Second
  85. jitter := time.Duration(rng.Intn(1000)) * time.Millisecond
  86. return sleepWithContext(backoff + jitter)
  87. }(); err != nil {
  88. return nil, fmt.Errorf("request cancelled: %w", err)
  89. }
  90. continue
  91. }
  92. break
  93. }
  94. if resp == nil {
  95. return nil, fmt.Errorf("request failed: no response received")
  96. }
  97. if resp.StatusCode != http.StatusOK {
  98. _ = resp.Body.Close()
  99. statusText := http.StatusText(resp.StatusCode)
  100. if statusText == "" {
  101. statusText = resp.Status
  102. }
  103. fmt.Printf("[DriveClient] Drive API error: status=%d, msg=%s\n", resp.StatusCode, statusText)
  104. // 只返回通用错误
  105. return nil, fmt.Errorf("drive API error: status %d", resp.StatusCode)
  106. }
  107. defer func() { _ = resp.Body.Close() }()
  108. // Parse response
  109. var result struct {
  110. StorageQuota struct {
  111. Limit string `json:"limit"` // Can be string or number
  112. Usage string `json:"usage"`
  113. } `json:"storageQuota"`
  114. }
  115. if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
  116. return nil, fmt.Errorf("failed to decode response: %w", err)
  117. }
  118. // Parse limit and usage (handle both string and number formats)
  119. var limit, usage int64
  120. if result.StorageQuota.Limit != "" {
  121. if val, err := strconv.ParseInt(result.StorageQuota.Limit, 10, 64); err == nil {
  122. limit = val
  123. }
  124. }
  125. if result.StorageQuota.Usage != "" {
  126. if val, err := strconv.ParseInt(result.StorageQuota.Usage, 10, 64); err == nil {
  127. usage = val
  128. }
  129. }
  130. return &DriveStorageInfo{
  131. Limit: limit,
  132. Usage: usage,
  133. }, nil
  134. }