Skip to content

Commit

Permalink
#1: Fix race conditions errors and rewrite tests
Browse files Browse the repository at this point in the history
  • Loading branch information
erickskrauch committed Apr 18, 2019
1 parent e14619e commit 8244351
Show file tree
Hide file tree
Showing 4 changed files with 191 additions and 190 deletions.
17 changes: 16 additions & 1 deletion Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 7 additions & 2 deletions api/mojang/queue/jobs_structure.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,24 +25,29 @@ func (s *jobsQueue) New() *jobsQueue {

func (s *jobsQueue) Enqueue(t *jobItem) {
s.lock.Lock()
defer s.lock.Unlock()

s.items = append(s.items, t)
s.lock.Unlock()
}

func (s *jobsQueue) Dequeue(n int) []*jobItem {
s.lock.Lock()
defer s.lock.Unlock()

if n > s.Size() {
n = s.Size()
}

items := s.items[0:n]
s.items = s.items[n:len(s.items)]
s.lock.Unlock()

return items
}

func (s *jobsQueue) IsEmpty() bool {
s.lock.Lock()
defer s.lock.Unlock()

return len(s.items) == 0
}

Expand Down
11 changes: 8 additions & 3 deletions api/mojang/queue/queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ import (
var usernamesToUuids = mojang.UsernamesToUuids
var uuidToTextures = mojang.UuidToTextures
var delay = time.Second
var forever = func() bool {
return true
}

type JobsQueue struct {
Storage Storage
Expand All @@ -19,7 +22,7 @@ type JobsQueue struct {
queue jobsQueue
}

func (ctx *JobsQueue) GetTexturesForUsername(username string) *mojang.SignedTexturesResponse {
func (ctx *JobsQueue) GetTexturesForUsername(username string) chan *mojang.SignedTexturesResponse {
ctx.onFirstCall.Do(func() {
ctx.queue.New()
ctx.startQueue()
Expand All @@ -28,14 +31,15 @@ func (ctx *JobsQueue) GetTexturesForUsername(username string) *mojang.SignedText
resultChan := make(chan *mojang.SignedTexturesResponse)
// 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
return resultChan
}

func (ctx *JobsQueue) startQueue() {
go func() {
time.Sleep(delay)
for true {
for forever() {
start := time.Now()
ctx.queueRound()
time.Sleep(delay - time.Since(start))
Expand Down Expand Up @@ -81,6 +85,7 @@ func (ctx *JobsQueue) queueRound() {
}

if uuid != "" {
var err error
result, err = uuidToTextures(uuid, true)
if err != nil {
if _, ok := err.(*mojang.TooManyRequestsError); !ok {
Expand Down
Loading

0 comments on commit 8244351

Please sign in to comment.