-
Notifications
You must be signed in to change notification settings - Fork 8
/
fixtures.go
99 lines (81 loc) · 2.5 KB
/
fixtures.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
package main
import (
"context"
"math/rand"
"time"
"github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/common/client"
"github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainer/app"
"github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainer/app/command"
"github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainer/app/query"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
const daysToSet = 30
func loadFixtures(app app.Application) {
start := time.Now()
ctx := context.Background()
logrus.Debug("Waiting for trainer service")
working := client.WaitForTrainerService(time.Second * 30)
if !working {
logrus.Error("Trainer gRPC service is not up")
return
}
logrus.WithField("after", time.Since(start)).Debug("Trainer service is available")
if !canLoadFixtures(app, ctx) {
logrus.Debug("Trainer fixtures are already loaded")
return
}
for {
err := loadTrainerFixtures(ctx, app)
if err == nil {
break
}
logrus.WithError(err).Error("Cannot load trainer fixtures")
time.Sleep(10 * time.Second)
}
logrus.WithField("after", time.Since(start)).Debug("Trainer fixtures loaded")
}
func loadTrainerFixtures(ctx context.Context, application app.Application) error {
maxDate := time.Now().AddDate(0, 0, daysToSet)
localRand := rand.New(rand.NewSource(3))
for date := time.Now(); date.Before(maxDate); date = date.AddDate(0, 0, 1) {
for hour := 12; hour <= 20; hour++ {
trainingTime := time.Date(date.Year(), date.Month(), date.Day(), hour, 0, 0, 0, time.UTC)
if trainingTime.Add(time.Hour).Before(time.Now()) {
// this hour is already "in progress"
continue
}
if localRand.NormFloat64() > 0 {
err := application.Commands.MakeHoursAvailable.Handle(
ctx,
command.MakeHoursAvailable{Hours: []time.Time{trainingTime}},
)
if err != nil {
return errors.Wrap(err, "unable to update hour")
}
}
}
}
return nil
}
func canLoadFixtures(app app.Application, ctx context.Context) bool {
for {
dates, err := app.Queries.TrainerAvailableHours.Handle(ctx, query.AvailableHours{
From: time.Now(),
To: time.Now().AddDate(0, 0, daysToSet),
})
if err == nil {
for _, date := range dates {
for _, hour := range date.Hours {
if hour.Available {
// we don't need fixtures if any hour is already available for training
return false
}
}
}
return true
}
logrus.WithError(err).Error("Cannot check if fixtures can be loaded")
time.Sleep(10 * time.Second)
}
}