Skip to content

Commit

Permalink
#1: Pull queue into struct, add storage interface
Browse files Browse the repository at this point in the history
  • Loading branch information
erickskrauch committed Apr 14, 2019
1 parent 879a333 commit fd4e5eb
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 14 deletions.
35 changes: 21 additions & 14 deletions api/mojang/queue/queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
Expand Down
19 changes: 19 additions & 0 deletions api/mojang/queue/storage.go
Original file line number Diff line number Diff line change
@@ -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) {
}

0 comments on commit fd4e5eb

Please sign in to comment.