#1: Pull queue into struct, add storage interface

This commit is contained in:
ErickSkrauch 2019-04-15 02:52:00 +03:00
parent 879a33344b
commit fd4e5eb9ca
2 changed files with 40 additions and 14 deletions

View File

@ -8,43 +8,50 @@ import (
"github.com/elyby/chrly/api/mojang"
)
var onFirstCall sync.Once
var queue = jobsQueue{}
var usernamesToUuids = mojang.UsernamesToUuids
var uuidToTextures = mojang.UuidToTextures
func ScheduleTexturesForUsername(username string) (resultChan chan *mojang.SignedTexturesResponse) {
onFirstCall.Do(func() {
queue.New()
startQueue()
type JobsQueue struct {
Storage Storage
onFirstCall sync.Once
queue jobsQueue
}
func (ctx *JobsQueue) GetTexturesForUsername(username string) (resultChan chan *mojang.SignedTexturesResponse) {
ctx.onFirstCall.Do(func() {
ctx.queue.New()
ctx.startQueue()
})
// TODO: prevent of adding the same username more than once
queue.Enqueue(&jobItem{username, resultChan})
ctx.queue.Enqueue(&jobItem{username, resultChan})
return
}
func startQueue() {
func (ctx *JobsQueue) startQueue() {
go func() {
for {
start := time.Now()
queueRound()
ctx.queueRound()
time.Sleep(time.Second - time.Since(start))
}
}()
}
func queueRound() {
if queue.IsEmpty() {
func (ctx *JobsQueue) queueRound() {
if ctx.queue.IsEmpty() {
return
}
jobs := queue.Dequeue(100)
jobs := ctx.queue.Dequeue(100)
var usernames []string
for _, job := range jobs {
usernames = append(usernames, job.Username)
}
profiles, err := mojang.UsernamesToUuids(usernames)
profiles, err := usernamesToUuids(usernames)
switch err.(type) {
case *mojang.TooManyRequestsError:
for _, job := range jobs {
@ -71,7 +78,7 @@ func queueRound() {
}
if uuid != "" {
result, err = mojang.UuidToTextures(uuid, true)
result, err = uuidToTextures(uuid, true)
if err != nil {
if _, ok := err.(*mojang.TooManyRequestsError); !ok {
panic(err)

View File

@ -0,0 +1,19 @@
package queue
import "github.com/elyby/chrly/api/mojang"
type Storage interface {
Get(username string) *mojang.SignedTexturesResponse
Set(textures *mojang.SignedTexturesResponse)
}
// NilStorage used for testing purposes
type NilStorage struct {
}
func (*NilStorage) Get(username string) *mojang.SignedTexturesResponse {
return nil
}
func (*NilStorage) Set(textures *mojang.SignedTexturesResponse) {
}