This repository has been archived by the owner on May 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
worker.go
63 lines (54 loc) · 1.71 KB
/
worker.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
// Package worker provides the actual running of games. It is the core of the
// engine and game logic. It interacts primarily with the controller API writing
// and reading game state.
package worker
import (
"context"
"time"
"github.com/battlesnakeio/engine/controller/pb"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// Worker is the worker interface. It wraps a main Perform functions which is
// where all of the game logic should live.
type Worker struct {
ControllerClient pb.ControllerClient
PollInterval time.Duration
RunGame func(context.Context, pb.ControllerClient, string) error
}
// Run will run the worker in a loop.
func (w *Worker) Run(ctx context.Context, workerID int) {
for {
// We are now holding the lock.
if err := w.run(ctx, workerID); err != nil {
s, ok := status.FromError(err)
if !ok || s.Code() != codes.NotFound {
log.WithError(err).WithField("worker", workerID).Warn("run failed")
}
select {
case <-time.After(w.PollInterval):
case <-ctx.Done():
return
}
}
}
}
func (w *Worker) run(ctx context.Context, workerID int) error {
// Pop an item of work.
pop, err := w.ControllerClient.Pop(ctx, &pb.PopRequest{})
if err != nil {
return err
}
log.WithField("worker", workerID).
WithField("game", pop.ID).
Info("acquired lock")
// Get a context with the lock token.
ctx, cancel := context.WithCancel(ctx)
defer cancel()
ctx = pb.ContextWithLockToken(ctx, pop.Token)
// Perform the actual work, this should respect context and Done() rules.
// Perform should be able to write to storage using the context and have
// a valid lock for the key.
return w.RunGame(ctx, w.ControllerClient, pop.ID)
}