-
Notifications
You must be signed in to change notification settings - Fork 0
/
guess.go
110 lines (88 loc) · 2.49 KB
/
guess.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package battleword
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
)
type Guess struct {
Guess string `json:"guess,omitempty"`
// For the lols:
Shout string `json:"shout,omitempty"`
}
func GetNextState(ctx context.Context, log logrus.FieldLogger, c PlayerConnection, s PlayerGameState, answer string) PlayerGameState {
id := uuid.New().String()
log = log.WithField("guess_id", id)
log.WithFields(logrus.Fields{
"turn": len(s.GuessResults),
}).
Debug("queued getting guess")
guessesJson, err := json.Marshal(s)
if err != nil {
log.WithError(err).Error("failed to encode playergamestate")
s.Error = err.Error()
return s
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("%s/guess", c.uri), bytes.NewReader(guessesJson))
if err != nil {
log.WithError(err).Error("failed to form guess request")
s.Error = err.Error()
return s
}
req.Header.Add(GuessIDHeader, id)
// Make sure we don't go over the concurrent connection limit for this player.
// This will halt until there is a free slot in the concurrent request queue.
c.concurrentConnectionLimiter <- struct{}{}
defer func() { <-c.concurrentConnectionLimiter }()
log.Debug("started getting guess")
start := time.Now()
res, err := c.client.Do(req)
if err != nil {
log.WithError(err).Error("failed to get guess")
s.Error = err.Error()
return s
}
defer res.Body.Close()
finish := time.Now()
log.Debug("finished getting guess")
guessDuration := finish.Sub(start)
// want to get full bytes of what player sent to help them out
guessBytes, err := io.ReadAll(res.Body)
if err != nil {
log.WithError(err).Error("failed to read from player response")
s.Error = err.Error()
return s
}
var guess Guess
err = json.Unmarshal(guessBytes, &guess)
if err != nil {
log.WithError(err).Error("failed to decode player guess response")
s.Error = err.Error()
return s
}
if !ValidGuess(guess.Guess, answer) {
log.Warn("received invalid guess")
s.Error = fmt.Sprintf("guess is invalid: %s", guess.Guess)
return s
}
result := GetResult(guess.Guess, answer)
guessResult := GuessResult{
ID: id,
Result: result,
Guess: guess.Guess,
Start: start,
Finish: finish,
}
s.GuessResults = append(s.GuessResults, guessResult)
s.GuessDurationsNS = append(s.GuessDurationsNS, guessDuration.Nanoseconds())
s.shouts = append(s.shouts, guess.Shout)
if guess.Guess == answer {
s.Correct = true
}
return s
}