From fd4e5eb9ca63abdab5cba41fed63f96798789d11 Mon Sep 17 00:00:00 2001 From: ErickSkrauch Date: Mon, 15 Apr 2019 02:52:00 +0300 Subject: [PATCH] #1: Pull queue into struct, add storage interface --- api/mojang/queue/queue.go | 35 +++++++++++++++++++++-------------- api/mojang/queue/storage.go | 19 +++++++++++++++++++ 2 files changed, 40 insertions(+), 14 deletions(-) create mode 100644 api/mojang/queue/storage.go diff --git a/api/mojang/queue/queue.go b/api/mojang/queue/queue.go index e5d4506..5ad9101 100644 --- a/api/mojang/queue/queue.go +++ b/api/mojang/queue/queue.go @@ -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) diff --git a/api/mojang/queue/storage.go b/api/mojang/queue/storage.go new file mode 100644 index 0000000..93c99a7 --- /dev/null +++ b/api/mojang/queue/storage.go @@ -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) { +}