-
Notifications
You must be signed in to change notification settings - Fork 5
/
generate.go
869 lines (816 loc) · 29.2 KB
/
generate.go
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
package scworker
import (
"encoding/json"
"errors"
"fmt"
"math"
"net/http"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/google/uuid"
"github.com/stablecog/sc-go/database/ent"
"github.com/stablecog/sc-go/database/ent/upscale"
"github.com/stablecog/sc-go/database/enttypes"
"github.com/stablecog/sc-go/database/repository"
"github.com/stablecog/sc-go/log"
"github.com/stablecog/sc-go/server/clip"
"github.com/stablecog/sc-go/server/discord"
"github.com/stablecog/sc-go/server/requests"
"github.com/stablecog/sc-go/server/responses"
"github.com/stablecog/sc-go/server/stripe"
"github.com/stablecog/sc-go/shared"
"github.com/stablecog/sc-go/utils"
"golang.org/x/exp/slices"
)
func (w *SCWorker) CreateGeneration(source enttypes.SourceType,
r *http.Request,
user *ent.User,
apiTokenId *uuid.UUID,
clipSvc *clip.ClipService,
generateReq requests.CreateGenerationRequest) (*responses.ApiSucceededResponse, *responses.ImageGenerationSettingsResponse, *WorkerError) {
// Queue priority for MQ
var queuePriority uint8 = shared.QUEUE_PRIORITY_2
free := user.ActiveProductID == nil
if free {
// Re-evaluate if they have paid credits
count, err := w.Repo.GetNonFreeCreditSum(user.ID)
if err != nil {
log.Error("Error getting paid credit sum for users", "err", err)
return nil, nil, WorkerInternalServerError()
}
free = count <= 0
if !free {
queuePriority = shared.QUEUE_PRIORITY_3
}
}
var qMax int
roles, err := w.Repo.GetRoles(user.ID)
if err != nil {
log.Error("Error getting roles for user", "err", err)
return nil, nil, WorkerInternalServerError()
}
isSuperAdmin := slices.Contains(roles, "SUPER_ADMIN")
if isSuperAdmin {
qMax = math.MaxInt64
} else {
qMax = shared.MAX_QUEUED_ITEMS_FREE
}
if !isSuperAdmin && user.ActiveProductID != nil {
switch *user.ActiveProductID {
// Starter
case stripe.GetProductIDs()[1]:
qMax = shared.MAX_QUEUED_ITEMS_STARTER
queuePriority = shared.QUEUE_PRIORITY_5
// Pro
case stripe.GetProductIDs()[2]:
qMax = shared.MAX_QUEUED_ITEMS_PRO
queuePriority = shared.QUEUE_PRIORITY_5
// Ultimate
case stripe.GetProductIDs()[3]:
qMax = shared.MAX_QUEUED_ITEMS_ULTIMATE
queuePriority = shared.QUEUE_PRIORITY_5
default:
log.Warn("Unknown product ID", "product_id", *user.ActiveProductID)
}
// // Get product level
// for level, product := range GetProductIDs() {
// if product == *user.ActiveProductID {
// prodLevel = level
// break
// }
// }
}
for _, role := range roles {
switch role {
case "ULTIMATE":
free = false
if qMax < shared.MAX_QUEUED_ITEMS_ULTIMATE {
qMax = shared.MAX_QUEUED_ITEMS_ULTIMATE
}
case "PRO":
free = false
if qMax < shared.MAX_QUEUED_ITEMS_PRO {
qMax = shared.MAX_QUEUED_ITEMS_PRO
}
case "STARTER":
free = false
if qMax < shared.MAX_QUEUED_ITEMS_STARTER {
qMax = shared.MAX_QUEUED_ITEMS_STARTER
}
}
}
if isSuperAdmin {
queuePriority = shared.QUEUE_PRIORITY_4
}
// With gift credits, give them a priority in between super admins and paid credits
if !free && queuePriority < shared.QUEUE_PRIORITY_5 {
// Re-evaluate if they have paid credits
paidCount, err := w.Repo.GetPaidCreditSum(user.ID)
if err != nil {
log.Error("Error getting paid credit sum for users", "err", err)
return nil, nil, WorkerInternalServerError()
}
if paidCount > 0 {
queuePriority = shared.QUEUE_PRIORITY_5
}
}
if user.BannedAt != nil {
return nil, nil, &WorkerError{http.StatusForbidden, fmt.Errorf("user_banned"), ""}
}
// Validation
if !isSuperAdmin {
err = generateReq.Validate(source != enttypes.SourceTypeWebUI)
if err != nil {
return nil, nil, &WorkerError{http.StatusBadRequest, err, ""}
}
} else {
generateReq.ApplyDefaults()
}
// Set settings resp
initSettings := responses.ImageGenerationSettingsResponse{
ModelId: *generateReq.ModelId,
SchedulerId: *generateReq.SchedulerId,
Width: *generateReq.Width,
Height: *generateReq.Height,
NumOutputs: *generateReq.NumOutputs,
GuidanceScale: *generateReq.GuidanceScale,
InferenceSteps: *generateReq.InferenceSteps,
Seed: generateReq.Seed,
InitImageURL: generateReq.InitImageUrl,
MaskImageURL: generateReq.MaskImageUrl,
PromptStrength: generateReq.PromptStrength,
}
// The URL we send worker
var signedInitImageUrl string
// See if init image specified, validate it belongs to user, validate it exists in bucket
if generateReq.InitImageUrl != "" {
if utils.IsValidHTTPURL(generateReq.InitImageUrl) {
// Custom image, do some validation on size, format, etc.
_, _, err = utils.GetImageWidthHeightFromUrl(generateReq.InitImageUrl, "", shared.MAX_GENERATE_IMAGE_SIZE)
if err != nil {
return nil, &initSettings, &WorkerError{http.StatusBadRequest, fmt.Errorf("image_url_width_height_error"), ""}
}
signedInitImageUrl = generateReq.InitImageUrl
} else if w.S3Img != nil {
// Remove s3 prefix
signedInitImageUrl = strings.TrimPrefix(generateReq.InitImageUrl, "s3://")
// Hash user ID to see if it belongs to this user
uidHash := utils.Sha256(user.ID.String())
if !strings.HasPrefix(signedInitImageUrl, fmt.Sprintf("%s/", uidHash)) {
return nil, &initSettings, &WorkerError{http.StatusUnauthorized, fmt.Errorf("init_image_not_owned"), ""}
}
// Verify exists in bucket
_, err := w.S3Img.HeadObject(&s3.HeadObjectInput{
Bucket: aws.String(utils.GetEnv().S3Img2ImgBucketName),
Key: aws.String(signedInitImageUrl),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case "NotFound": // s3.ErrCodeNoSuchKey does not work, aws is missing this error code so we hardwire a string
return nil, &initSettings, &WorkerError{http.StatusBadRequest, fmt.Errorf("init_image_not_found"), ""}
default:
log.Error("Error checking if init image exists in bucket", "err", err)
return nil, &initSettings, &WorkerError{http.StatusInternalServerError, fmt.Errorf("unknown_error"), ""}
}
}
return nil, &initSettings, &WorkerError{http.StatusBadRequest, fmt.Errorf("init_image_not_found"), ""}
}
// Sign object URL to pass to worker
req, _ := w.S3Img.GetObjectRequest(&s3.GetObjectInput{
Bucket: aws.String(utils.GetEnv().S3Img2ImgBucketName),
Key: aws.String(signedInitImageUrl),
})
urlStr, err := req.Presign(24 * time.Hour)
if err != nil {
log.Error("Error signing init image URL", "err", err)
return nil, &initSettings, &WorkerError{http.StatusInternalServerError, fmt.Errorf("unknown_error"), ""}
}
signedInitImageUrl = urlStr
}
if signedInitImageUrl == "" {
return nil, &initSettings, &WorkerError{http.StatusBadRequest, fmt.Errorf("invalid_image_url"), ""}
}
}
// The URL we send worker
var signedMaskImageUrl string
// See if init image specified, validate it belongs to user, validate it exists in bucket
if generateReq.MaskImageUrl != "" {
if utils.IsValidHTTPURL(generateReq.MaskImageUrl) {
// Custom image, do some validation on size, format, etc.
_, _, err = utils.GetImageWidthHeightFromUrl(generateReq.MaskImageUrl, "", shared.MAX_GENERATE_IMAGE_SIZE)
if err != nil {
return nil, &initSettings, &WorkerError{http.StatusBadRequest, fmt.Errorf("image_url_width_height_error"), ""}
}
signedMaskImageUrl = generateReq.MaskImageUrl
} else if w.S3Img != nil {
// Remove s3 prefix
signedMaskImageUrl = strings.TrimPrefix(generateReq.MaskImageUrl, "s3://")
// Hash user ID to see if it belongs to this user
uidHash := utils.Sha256(user.ID.String())
if !strings.HasPrefix(signedMaskImageUrl, fmt.Sprintf("%s/", uidHash)) {
return nil, &initSettings, &WorkerError{http.StatusUnauthorized, fmt.Errorf("init_image_not_owned"), ""}
}
// Verify exists in bucket
_, err := w.S3Img.HeadObject(&s3.HeadObjectInput{
Bucket: aws.String(utils.GetEnv().S3Img2ImgBucketName),
Key: aws.String(signedMaskImageUrl),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case "NotFound": // s3.ErrCodeNoSuchKey does not work, aws is missing this error code so we hardwire a string
return nil, &initSettings, &WorkerError{http.StatusBadRequest, fmt.Errorf("mask_image_not_found"), ""}
default:
log.Error("Error checking if mask image exists in bucket", "err", err)
return nil, &initSettings, &WorkerError{http.StatusInternalServerError, fmt.Errorf("unknown_error"), ""}
}
}
return nil, &initSettings, &WorkerError{http.StatusBadRequest, fmt.Errorf("mask_image_not_found"), ""}
}
// Sign object URL to pass to worker
req, _ := w.S3Img.GetObjectRequest(&s3.GetObjectInput{
Bucket: aws.String(utils.GetEnv().S3Img2ImgBucketName),
Key: aws.String(signedMaskImageUrl),
})
urlStr, err := req.Presign(5 * time.Minute)
if err != nil {
log.Error("Error signing init image URL", "err", err)
return nil, &initSettings, &WorkerError{http.StatusInternalServerError, fmt.Errorf("unknown_error"), ""}
}
signedMaskImageUrl = urlStr
}
if signedMaskImageUrl == "" {
return nil, &initSettings, &WorkerError{http.StatusBadRequest, fmt.Errorf("invalid_mask_image_url"), ""}
}
}
// Get queue count
nq, err := w.QueueThrottler.NumQueued(fmt.Sprintf("g:%s", user.ID.String()))
if err != nil {
log.Warn("Error getting queue count", "err", err, "user_id", user.ID.String())
}
if err == nil && nq > qMax {
// Get queue overflow size
overflowSize, err := w.QueueThrottler.NumQueued(fmt.Sprintf("of:%s", user.ID.String()))
if err != nil {
log.Warn("Error getting queue overflow count", "err", err, "user_id", user.ID.String())
}
// If overflow size is greater than max, return error
if overflowSize > shared.QUEUE_OVERFLOW_MAX {
return nil, &initSettings, &WorkerError{http.StatusBadRequest, fmt.Errorf("queue_limit_reached"), ""}
}
// Overflow size can be 0 so we need to add 1
overflowSize++
w.QueueThrottler.IncrementBy(1, fmt.Sprintf("of:%s", user.ID.String()))
for {
time.Sleep(time.Duration(shared.QUEUE_OVERFLOW_PENALTY_MS*overflowSize) * time.Millisecond)
nq, err = w.QueueThrottler.NumQueued(fmt.Sprintf("g:%s", user.ID.String()))
if err != nil {
log.Warn("Error getting queue count", "err", err, "user_id", user.ID.String())
}
if err == nil && nq <= qMax {
w.QueueThrottler.DecrementBy(1, fmt.Sprintf("of:%s", user.ID.String()))
break
}
// Update overflow size
overflowSize, err = w.QueueThrottler.NumQueued(fmt.Sprintf("of:%s", user.ID.String()))
if err != nil {
log.Warn("Error getting queue overflow count", "err", err, "user_id", user.ID.String())
}
overflowSize++
}
}
// Enforce submit to gallery
if free {
generateReq.WasAutoSubmitted = true
generateReq.SubmitToGallery = true
}
// Parse request headers
var countryCode string
var thumbmarkID string
var deviceInfo utils.ClientDeviceInfo
ipAddress := "system"
if r != nil {
thumbmarkID = utils.GetThumbmarkID(r)
countryCode = utils.GetCountryCode(r)
deviceInfo = utils.GetClientDeviceInfo(r)
ipAddress = utils.GetIPAddress(r)
} else {
countryCode = "US"
deviceInfo = utils.ClientDeviceInfo{
DeviceType: utils.Bot,
DeviceOs: "Linux",
DeviceBrowser: "Discord",
}
}
// Get model and scheduler name for cog
modelName := shared.GetCache().GetGenerationModelNameFromID(*generateReq.ModelId)
schedulerName := shared.GetCache().GetSchedulerNameFromID(*generateReq.SchedulerId)
if modelName == "" || schedulerName == "" {
log.Error("Error getting model or scheduler name: %s - %s", modelName, schedulerName)
return nil, &initSettings, &WorkerError{http.StatusBadRequest, fmt.Errorf("invalid_model_or_scheduler"), ""}
}
// Format prompts
generateReq.Prompt = utils.FormatPrompt(generateReq.Prompt)
generateReq.NegativePrompt = utils.FormatPrompt(generateReq.NegativePrompt)
// For live page update
var livePageMsg shared.LivePageMessage
// For keeping track of this request as it gets sent to the worker
var requestId uuid.UUID
var queueId string
// Cog request
var cogReqBody requests.CogQueueRequest
// Credits left after this operation
var remainingCredits int
// Create channel to track request
// Create channel
activeChl := make(chan requests.CogWebhookMessage)
// Cleanup
defer close(activeChl)
// Wrap everything in a DB transaction
// We do this since we want our credit deduction to be atomic with the whole process
if err := w.Repo.WithTx(func(tx *ent.Tx) error {
// Bind a client to the transaction
DB := tx.Client()
// Deduct credits from user
deducted, err := w.Repo.DeductCreditsFromUser(user.ID, *generateReq.NumOutputs, false, DB)
if err != nil {
log.Error("Error deducting credits", "err", err)
return err
} else if !deducted {
return responses.InsufficientCreditsErr
}
// Translate prompts
translatedPrompt, translatedNegativePrompt, err := w.SafetyChecker.TranslatePrompt(generateReq.Prompt, generateReq.NegativePrompt)
if err != nil {
log.Error("Error translating prompt", "err", err)
return err
}
nsfwModerationAPIResultChan := make(chan bool)
bannedPromptResultChan := make(chan bool)
errChan := make(chan error)
// Goroutine to check NSFW
go func() {
isNSFW, reason, score, err := w.SafetyChecker.IsPromptNSFW(translatedPrompt)
if err != nil {
log.Error("Error checking prompt NSFW", "err", err)
errChan <- err
return
}
if isNSFW {
w.Track.GenerationFailedNSFWPrompt(
user,
requests.BaseCogRequest{
Prompt: generateReq.Prompt,
},
"Moderation API",
source,
translatedPrompt,
"",
0.0,
reason,
score,
ipAddress,
)
errChan <- fmt.Errorf("nsfw: %s", reason)
return
}
nsfwModerationAPIResultChan <- true
}()
// Goroutine to check banned embedding
if clipSvc != nil {
go func() {
embedding, err := clipSvc.GetEmbeddingFromText(translatedPrompt, 3, false)
if err != nil {
log.Error("Error fetching embedding", "err", err)
errChan <- err
return
}
bannedMatches, err := w.Repo.IsBannedPromptEmbedding(embedding, DB)
if err != nil {
log.Error("Error checking banned embedding", "err", err)
// errChan <- err
bannedPromptResultChan <- true
return
}
if len(bannedMatches) > 0 {
// Special case for prompts that should also cause a user ban
isSpecialBanned := false
hasShouldBanUser := false
for _, match := range bannedMatches {
if match.ShouldBanUser {
hasShouldBanUser = true
break
}
}
isNewAccount := time.Since(user.CreatedAt) < 24*time.Hour
if hasShouldBanUser && isNewAccount {
err := discord.FireBannedUserWebhook(ipAddress, user.Email, user.Email, user.ID.String(), countryCode, thumbmarkID, []string{"New account used special banned prompt."})
if err == nil {
_, err = w.Repo.BanUsers([]uuid.UUID{user.ID}, false)
if err != nil {
log.Error("Error banning user", "err", err)
}
time.Sleep(150 * time.Second)
isSpecialBanned = true
}
}
w.Track.GenerationFailedNSFWPrompt(
user,
requests.BaseCogRequest{
Prompt: generateReq.Prompt,
},
"Banned Prompt Embedding",
source,
translatedPrompt,
bannedMatches[0].ID.String(),
float64(bannedMatches[0].Similarity),
"",
0,
ipAddress,
)
if isSpecialBanned {
errChan <- fmt.Errorf("error: unknown")
} else {
errChan <- fmt.Errorf("nsfw: %s", "sexual_minors")
}
return
}
bannedPromptResultChan <- true
}()
}
// Wait for either of the two to complete successfully or fail
nsfwModerationAPIDone, bannedPromptDone := false, clipSvc == nil // If clipSvc is nil, mark bannedPromptDone as true
for !(nsfwModerationAPIDone && bannedPromptDone) {
select {
case <-nsfwModerationAPIResultChan:
nsfwModerationAPIDone = true
case <-bannedPromptResultChan:
bannedPromptDone = true
case err := <-errChan:
return err
}
}
remainingCredits, err = w.Repo.GetNonExpiredCreditTotalForUser(user.ID, DB)
if err != nil {
log.Error("Error getting remaining credits", "err", err)
return err
}
// Create generation
g, err := w.Repo.CreateGeneration(
user.ID,
string(deviceInfo.DeviceType),
deviceInfo.DeviceOs,
deviceInfo.DeviceBrowser,
countryCode,
generateReq,
user.ActiveProductID,
apiTokenId,
source,
DB)
if err != nil {
log.Error("Error creating generation", "err", err)
return err
}
// Request Id matches generation ID
requestId = g.ID
// message_id in amqp
queueId = utils.Sha256(requestId.String())
// For live page update
livePageMsg = shared.LivePageMessage{
ProcessType: shared.GENERATE,
ID: utils.Sha256(requestId.String()),
CountryCode: countryCode,
Status: shared.LivePageQueued,
TargetNumOutputs: *generateReq.NumOutputs,
Width: generateReq.Width,
Height: generateReq.Height,
CreatedAt: g.CreatedAt,
ProductID: user.ActiveProductID,
Source: source,
}
cogReqBody = requests.CogQueueRequest{
WebhookEventsFilter: []requests.CogEventFilter{requests.CogEventFilterStart, requests.CogEventFilterStart},
WebhookUrl: fmt.Sprintf("%s/v1/worker/webhook", utils.GetEnv().PublicApiUrl),
Input: requests.BaseCogRequest{
SkipSafetyChecker: true,
SkipTranslation: true,
WasAutoSubmitted: generateReq.WasAutoSubmitted,
APIRequest: source != enttypes.SourceTypeWebUI,
ID: requestId,
IP: ipAddress,
ThumbmarkID: thumbmarkID,
UserID: &user.ID,
DeviceInfo: deviceInfo,
LivePageData: &livePageMsg,
Prompt: translatedPrompt,
NegativePrompt: translatedNegativePrompt,
OriginalPrompt: generateReq.Prompt,
OriginalNegativePrompt: generateReq.NegativePrompt,
Width: generateReq.Width,
Height: generateReq.Height,
NumInferenceSteps: generateReq.InferenceSteps,
GuidanceScale: generateReq.GuidanceScale,
Model: modelName,
ModelId: *generateReq.ModelId,
Scheduler: schedulerName,
SchedulerId: *generateReq.SchedulerId,
Seed: generateReq.Seed,
NumOutputs: generateReq.NumOutputs,
WebhookToken: g.WebhookToken,
OutputImageExtension: string(shared.DEFAULT_GENERATE_OUTPUT_EXTENSION),
OutputImageQuality: utils.ToPtr(shared.DEFAULT_GENERATE_OUTPUT_QUALITY),
ProcessType: shared.GENERATE,
SubmitToGallery: generateReq.SubmitToGallery,
InitImageUrl: signedInitImageUrl,
MaskImageUrl: signedMaskImageUrl,
PromptStrength: generateReq.PromptStrength,
},
}
if generateReq.NumOutputs != nil {
cogReqBody.Input.SignedUrls = make([]string, *generateReq.NumOutputs)
for i := 0; i < int(*generateReq.NumOutputs); i++ {
imgId := fmt.Sprintf("%s.%s", uuid.NewString(), cogReqBody.Input.OutputImageExtension)
// Sign the URL and append to array
// If the file does not exist, generate a pre-signed URL
req, _ := w.S3.PutObjectRequest(&s3.PutObjectInput{
Bucket: aws.String(utils.GetEnv().S3BucketName),
Key: aws.String(imgId),
})
urlStr, err := req.Presign(24 * time.Hour) // URL is valid for 15 minutes
if err != nil {
log.Errorf("Failed to sign request: %v\n", err)
return err
}
cogReqBody.Input.SignedUrls[i] = urlStr
}
}
if source == enttypes.SourceTypeWebUI {
cogReqBody.Input.UIId = generateReq.UIId
cogReqBody.Input.StreamID = generateReq.StreamID
}
if cogReqBody.Input.InitImageUrl != "" {
cogReqBody.Input.InitImageUrlS3 = generateReq.InitImageUrl
}
if cogReqBody.Input.MaskImageUrl != "" {
cogReqBody.Input.MaskImageUrlS3 = generateReq.MaskImageUrl
}
_, err = w.Repo.AddToQueueLog(queueId, int(queuePriority), DB)
if err != nil {
log.Error("Error adding to queue log", "err", err)
return err
}
err = w.MQClient.Publish(queueId, cogReqBody, queuePriority)
if err != nil {
log.Error("Failed to write request %s to exchange: %v", queueId, err)
return err
}
w.QueueThrottler.IncrementBy(1, fmt.Sprintf("g:%s", user.ID.String()))
return nil
}); err != nil {
log.Error("Error in transaction", "err", err)
if errors.Is(err, responses.InsufficientCreditsErr) {
return nil, &initSettings, &WorkerError{http.StatusBadRequest, responses.InsufficientCreditsErr, ""}
}
if strings.Contains(err.Error(), "nsfw:") {
// Get reason
reason := ""
splitStr := strings.Split(err.Error(), "nsfw:")
if len(splitStr) > 1 {
reason = splitStr[1]
}
return nil, &initSettings, &WorkerError{http.StatusBadRequest, fmt.Errorf("nsfw_prompt"), reason}
}
return nil, &initSettings, WorkerInternalServerError()
}
// Add channel to sync array (basically a thread-safe map)
if source != enttypes.SourceTypeWebUI {
w.SMap.Put(requestId.String(), activeChl)
defer w.SMap.Delete(requestId.String())
defer w.QueueThrottler.DecrementBy(1, fmt.Sprintf("g:%s", user.ID.String()))
}
// Send live page update
go func() {
liveResp := repository.TaskStatusUpdateResponse{
ForLivePage: true,
LivePageMessage: &livePageMsg,
}
respBytes, err := json.Marshal(liveResp)
if err != nil {
log.Error("Error marshalling sse live response", "err", err)
return
}
err = w.Redis.Client.Publish(w.Redis.Ctx, shared.REDIS_SSE_BROADCAST_CHANNEL, respBytes).Err()
if err != nil {
log.Error("Failed to publish live page update", "err", err)
}
}()
// Analytics
go w.Track.GenerationStarted(user, cogReqBody.Input, source, ipAddress)
// Set timeout delay for UI
if source == enttypes.SourceTypeWebUI {
// Set timeout key
err = w.Redis.SetCogRequestStreamID(w.Redis.Ctx, requestId.String(), generateReq.StreamID)
if err != nil {
// Don't time it out if this fails
log.Error("Failed to set timeout key", "err", err)
} else {
// Start the timeout timer
go func() {
// sleep
time.Sleep(shared.REQUEST_COG_TIMEOUT)
// this will trigger timeout if it hasnt been finished
w.Repo.FailCogMessageDueToTimeoutIfTimedOut(requests.CogWebhookMessage{
Input: cogReqBody.Input,
Error: shared.TIMEOUT_ERROR,
Status: requests.CogFailed,
})
}()
}
// Get queued position
queueLog, err := w.Repo.GetQueuedItems(nil)
if err != nil {
log.Error("Error getting queue log", "err", err)
}
// Return queued indication
return &responses.ApiSucceededResponse{
RemainingCredits: remainingCredits,
Settings: initSettings,
QueuedResponse: &responses.TaskQueuedResponse{
ID: requestId.String(),
UIId: generateReq.UIId,
RemainingCredits: remainingCredits,
WasAutoSubmitted: generateReq.SubmitToGallery,
IsPublic: generateReq.SubmitToGallery,
QueuedId: queueId,
QueueItems: queueLog,
},
}, &initSettings, nil
}
// Wait for result
for {
select {
case cogMsg := <-activeChl:
// Always remove from queue log
_, err := w.Repo.DeleteFromQueueLog(queueId, nil)
if err != nil {
log.Error("Error deleting from queue log", "err", err)
}
switch cogMsg.Status {
case requests.CogProcessing:
err := w.Repo.SetGenerationStarted(requestId.String())
if err != nil {
log.Error("Failed to set generate started", "id", requestId, "err", err)
return nil, &initSettings, WorkerInternalServerError()
}
// Send live page update
go func() {
cogMsg.Input.LivePageData.Status = shared.LivePageProcessing
now := time.Now()
cogMsg.Input.LivePageData.StartedAt = &now
liveResp := repository.TaskStatusUpdateResponse{
ForLivePage: true,
LivePageMessage: cogMsg.Input.LivePageData,
}
respBytes, err := json.Marshal(liveResp)
if err != nil {
log.Error("Error marshalling sse live response", "err", err)
return
}
err = w.Redis.Client.Publish(w.Redis.Ctx, shared.REDIS_SSE_BROADCAST_CHANNEL, respBytes).Err()
if err != nil {
log.Error("Failed to publish live page update", "err", err)
}
}()
case requests.CogSucceeded:
outputs, err := w.Repo.SetGenerationSucceeded(requestId.String(), generateReq.Prompt, generateReq.NegativePrompt, generateReq.SubmitToGallery, cogMsg.Output, cogMsg.NSFWCount)
if err != nil {
log.Error("Failed to set generation succeeded", "id", upscale.ID, "err", err)
return nil, &initSettings, WorkerInternalServerError()
}
// Send live page update
go func() {
cogMsg.Input.LivePageData.Status = shared.LivePageSucceeded
now := time.Now()
cogMsg.Input.LivePageData.CompletedAt = &now
cogMsg.Input.LivePageData.ActualNumOutputs = len(outputs)
liveResp := repository.TaskStatusUpdateResponse{
ForLivePage: true,
LivePageMessage: cogMsg.Input.LivePageData,
}
respBytes, err := json.Marshal(liveResp)
if err != nil {
log.Error("Error marshalling sse live response", "err", err)
return
}
err = w.Redis.Client.Publish(w.Redis.Ctx, shared.REDIS_SSE_BROADCAST_CHANNEL, respBytes).Err()
if err != nil {
log.Error("Failed to publish live page update", "err", err)
}
}()
// Analytics
generation, err := w.Repo.GetGeneration(requestId)
if err != nil {
log.Error("Error getting generation for analytics", "err", err)
}
// Get durations in seconds
if generation.StartedAt == nil {
log.Error("Generation started at is nil", "id", cogMsg.Input.ID)
}
// Analytics
duration := time.Now().Sub(*generation.StartedAt).Seconds()
qDuration := (*generation.StartedAt).Sub(generation.CreatedAt).Seconds()
go w.Track.GenerationSucceeded(user, cogMsg.Input, duration, qDuration, source, ipAddress)
// Format response
resOutputs := make([]responses.ApiOutput, len(outputs))
for i, output := range outputs {
resOutputs[i] = responses.ApiOutput{
URL: utils.GetEnv().GetURLFromImagePath(output.ImagePath),
ImageURL: utils.ToPtr(utils.GetEnv().GetURLFromImagePath(output.ImagePath)),
ID: output.ID,
}
}
// Set token used
if generation.APITokenID != nil {
err = w.Repo.SetTokenUsedAndIncrementCreditsSpent(int(*generateReq.NumOutputs), *generation.APITokenID)
if err != nil {
log.Error("Failed to set token used", "err", err)
}
}
return &responses.ApiSucceededResponse{
Outputs: resOutputs,
RemainingCredits: remainingCredits,
Settings: initSettings,
}, &initSettings, nil
case requests.CogFailed:
if err := w.Repo.WithTx(func(tx *ent.Tx) error {
DB := tx.Client()
err := w.Repo.SetGenerationFailed(requestId.String(), cogMsg.Error, cogMsg.NSFWCount, DB)
if err != nil {
log.Error("Failed to set generation failed", "id", upscale.ID, "err", err)
return err
}
// Send live page update
go func() {
cogMsg.Input.LivePageData.Status = shared.LivePageFailed
now := time.Now()
cogMsg.Input.LivePageData.CompletedAt = &now
liveResp := repository.TaskStatusUpdateResponse{
ForLivePage: true,
LivePageMessage: cogMsg.Input.LivePageData,
}
respBytes, err := json.Marshal(liveResp)
if err != nil {
log.Error("Error marshalling sse live response", "err", err)
return
}
err = w.Redis.Client.Publish(w.Redis.Ctx, shared.REDIS_SSE_BROADCAST_CHANNEL, respBytes).Err()
if err != nil {
log.Error("Failed to publish live page update", "err", err)
}
}()
// Analytics
duration := time.Now().Sub(cogMsg.Input.LivePageData.CreatedAt).Seconds()
go w.Track.GenerationFailed(user, cogMsg.Input, duration, cogMsg.Error, source, ipAddress)
// Refund credits
_, err = w.Repo.RefundCreditsToUser(user.ID, *generateReq.NumOutputs, DB)
if err != nil {
log.Error("Failed to refund credits", "err", err)
return err
}
return nil
}); err != nil {
log.Error("Failed to set generation failed", "id", requestId, "err", err)
return nil, &initSettings, WorkerInternalServerError()
}
return nil, &initSettings, &WorkerError{http.StatusInternalServerError, fmt.Errorf(cogMsg.Error), ""}
}
case <-time.After(shared.REQUEST_COG_TIMEOUT):
_, err := w.Repo.DeleteFromQueueLog(queueId, nil)
if err != nil {
log.Error("Error deleting from queue log", "err", err)
}
if err := w.Repo.WithTx(func(tx *ent.Tx) error {
DB := tx.Client()
err := w.Repo.SetGenerationFailed(requestId.String(), shared.TIMEOUT_ERROR, 0, DB)
if err != nil {
log.Error("Failed to set generation failed", "id", upscale.ID, "err", err)
}
// Refund credits
_, err = w.Repo.RefundCreditsToUser(user.ID, *generateReq.NumOutputs, DB)
if err != nil {
log.Error("Failed to refund credits", "err", err)
return err
}
return nil
}); err != nil {
log.Error("Failed to set generation failed", "id", requestId, "err", err)
return nil, &initSettings, WorkerInternalServerError()
}
return nil, &initSettings, &WorkerError{http.StatusInternalServerError, fmt.Errorf(shared.TIMEOUT_ERROR), ""}
}
}
}