chrly/api/mojang/queue/queue.go

111 lines
2.0 KiB
Go
Raw Normal View History

package queue
import (
2019-04-15 01:32:22 +03:00
"strings"
"sync"
2019-04-15 01:32:22 +03:00
"time"
"github.com/elyby/chrly/api/mojang"
)
var usernamesToUuids = mojang.UsernamesToUuids
var uuidToTextures = mojang.UuidToTextures
var delay = time.Second
var forever = func() bool {
return true
}
type JobsQueue struct {
Storage Storage
onFirstCall sync.Once
queue jobsQueue
}
func (ctx *JobsQueue) GetTexturesForUsername(username string) chan *mojang.SignedTexturesResponse {
ctx.onFirstCall.Do(func() {
ctx.queue.New()
ctx.startQueue()
2019-04-15 01:32:22 +03:00
})
resultChan := make(chan *mojang.SignedTexturesResponse)
2019-04-15 01:32:22 +03:00
// TODO: prevent of adding the same username more than once
ctx.queue.Enqueue(&jobItem{username, resultChan})
// TODO: return nil if processing takes more than 5 seconds
return resultChan
}
func (ctx *JobsQueue) startQueue() {
2019-04-15 01:32:22 +03:00
go func() {
time.Sleep(delay)
for forever() {
2019-04-15 01:32:22 +03:00
start := time.Now()
ctx.queueRound()
time.Sleep(delay - time.Since(start))
2019-04-15 01:32:22 +03:00
}
}()
}
func (ctx *JobsQueue) queueRound() {
if ctx.queue.IsEmpty() {
2019-04-15 01:32:22 +03:00
return
}
jobs := ctx.queue.Dequeue(100)
2019-04-15 01:32:22 +03:00
var usernames []string
for _, job := range jobs {
usernames = append(usernames, job.Username)
}
profiles, err := usernamesToUuids(usernames)
2019-04-15 01:32:22 +03:00
switch err.(type) {
case *mojang.TooManyRequestsError:
for _, job := range jobs {
job.RespondTo <- nil
}
2019-04-15 01:32:22 +03:00
return
case error:
panic(err)
}
var wg sync.WaitGroup
for _, job := range jobs {
wg.Add(1)
go func(job *jobItem) {
2019-04-15 01:32:22 +03:00
var result *mojang.SignedTexturesResponse
shouldCache := true
var uuid string
for _, profile := range profiles {
if strings.EqualFold(job.Username, profile.Name) {
uuid = profile.Id
break
}
}
if uuid != "" {
var err error
result, err = uuidToTextures(uuid, true)
2019-04-15 01:32:22 +03:00
if err != nil {
if _, ok := err.(*mojang.TooManyRequestsError); !ok {
panic(err)
}
shouldCache = false
}
}
wg.Done()
job.RespondTo <- result
if shouldCache {
// TODO: store result to cache
}
}(job)
2019-04-15 01:32:22 +03:00
}
2019-04-15 01:32:22 +03:00
wg.Wait()
}