image_task_admin_toggle_test.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. //go:build unit
  2. package handler
  3. import (
  4. "context"
  5. "encoding/json"
  6. "net/http"
  7. "net/http/httptest"
  8. "strings"
  9. "sync"
  10. "testing"
  11. "time"
  12. "github.com/Wei-Shaw/sub2api/internal/config"
  13. middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
  14. "github.com/Wei-Shaw/sub2api/internal/service"
  15. "github.com/gin-gonic/gin"
  16. "github.com/stretchr/testify/require"
  17. )
  18. type toggleSettingRepo struct {
  19. mu sync.Mutex
  20. values map[string]string
  21. }
  22. func (r *toggleSettingRepo) Get(context.Context, string) (*service.Setting, error) { return nil, nil }
  23. func (r *toggleSettingRepo) GetValue(_ context.Context, key string) (string, error) {
  24. r.mu.Lock()
  25. defer r.mu.Unlock()
  26. return r.values[key], nil
  27. }
  28. func (r *toggleSettingRepo) Set(_ context.Context, key, value string) error {
  29. r.mu.Lock()
  30. defer r.mu.Unlock()
  31. r.values[key] = value
  32. return nil
  33. }
  34. func (r *toggleSettingRepo) GetMultiple(context.Context, []string) (map[string]string, error) {
  35. return map[string]string{}, nil
  36. }
  37. func (r *toggleSettingRepo) SetMultiple(context.Context, map[string]string) error { return nil }
  38. func (r *toggleSettingRepo) GetAll(context.Context) (map[string]string, error) {
  39. return map[string]string{}, nil
  40. }
  41. func (r *toggleSettingRepo) Delete(context.Context, string) error { return nil }
  42. type passthroughEncryptor struct{}
  43. func (passthroughEncryptor) Encrypt(plaintext string) (string, error) { return plaintext, nil }
  44. func (passthroughEncryptor) Decrypt(ciphertext string) (string, error) { return ciphertext, nil }
  45. type noopImageStorage struct{}
  46. func (noopImageStorage) Save(context.Context, string, string, []byte) (string, error) {
  47. return "https://cdn.example.test/object.png", nil
  48. }
  49. // TestAsyncImageEnablesWithoutRestart drives the actual HTTP path for the bug behind
  50. // #4458 and #4542: with object storage unconfigured the async endpoint 404s, and the
  51. // only way to turn it on used to be editing config.yaml and restarting the container.
  52. // Flipping the admin setting must flip the endpoint over in the same process.
  53. func TestAsyncImageEnablesWithoutRestart(t *testing.T) {
  54. gin.SetMode(gin.TestMode)
  55. repo := &toggleSettingRepo{values: map[string]string{}}
  56. // A fixed encryption key is required to persist a new S3 secret (#4524).
  57. backup := service.NewBackupService(repo, &config.Config{
  58. Totp: config.TotpConfig{EncryptionKeyConfigured: true},
  59. }, passthroughEncryptor{}, nil, nil)
  60. factory := func(context.Context, *config.ImageStorageConfig) (service.ImageStorage, error) {
  61. return noopImageStorage{}, nil
  62. }
  63. settings := service.NewImageStorageSettingService(repo, passthroughEncryptor{}, backup, factory, config.ImageStorageConfig{})
  64. store := &asyncImageMemoryStore{tasks: make(map[string]*service.ImageTaskRecord)}
  65. tasks := service.NewImageTaskServiceWithResolver(store, settings.Resolver(), time.Hour, time.Minute)
  66. h := &AsyncImageHandler{tasks: tasks}
  67. h.execute = func(_ string, c *gin.Context) {
  68. c.JSON(http.StatusOK, gin.H{"created": 1, "data": []gin.H{{"url": "https://upstream.test/i.png"}}})
  69. }
  70. router := gin.New()
  71. router.Use(func(c *gin.Context) {
  72. groupID := int64(3)
  73. c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
  74. ID: 9, UserID: 7, GroupID: &groupID,
  75. Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, AllowImageGeneration: true},
  76. })
  77. c.Next()
  78. })
  79. router.POST("/v1/images/generations/async", h.Submit)
  80. router.GET("/v1/images/tasks/:task_id", h.Get)
  81. submit := func() *httptest.ResponseRecorder {
  82. req := httptest.NewRequest(http.MethodPost, "/v1/images/generations/async",
  83. strings.NewReader(`{"model":"gpt-image-1","prompt":"a lighthouse"}`))
  84. req.Header.Set("Content-Type", "application/json")
  85. rec := httptest.NewRecorder()
  86. router.ServeHTTP(rec, req)
  87. return rec
  88. }
  89. rec := submit()
  90. require.Equal(t, http.StatusNotFound, rec.Code, "disabled until an admin configures object storage")
  91. require.Contains(t, rec.Body.String(), "async image tasks are not enabled")
  92. // The admin saves the setting — no restart, same process.
  93. _, err := settings.Update(context.Background(), service.ImageStorageSettings{
  94. Enabled: true, Bucket: "my-images",
  95. Endpoint: "https://acct.r2.cloudflarestorage.com", AccessKeyID: "ak", SecretAccessKey: "sk",
  96. })
  97. require.NoError(t, err)
  98. rec = submit()
  99. require.Equal(t, http.StatusAccepted, rec.Code, "the endpoint must go live as soon as the setting is saved")
  100. var accepted struct {
  101. TaskID string `json:"task_id"`
  102. PollURL string `json:"poll_url"`
  103. }
  104. require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &accepted))
  105. require.NotEmpty(t, accepted.TaskID)
  106. // Turning the feature back off must not strand a task that was already accepted.
  107. _, err = settings.Update(context.Background(), service.ImageStorageSettings{Enabled: false})
  108. require.NoError(t, err)
  109. require.Equal(t, http.StatusNotFound, submit().Code, "new submissions are refused again")
  110. pollRec := httptest.NewRecorder()
  111. router.ServeHTTP(pollRec, httptest.NewRequest(http.MethodGet, accepted.PollURL, nil))
  112. require.Equal(t, http.StatusOK, pollRec.Code, "an already-accepted task stays pollable after the switch is turned off")
  113. }