/
live.go
289 lines (245 loc) · 7.48 KB
/
live.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package live
import (
"context"
"fmt"
"log/slog"
"math/rand"
"sync"
"time"
"github.com/mbobakov/khrushchevka/internal"
"golang.org/x/sync/errgroup"
)
type LightsController interface {
Set(addr internal.LightAddress, isON bool) error
Reset() error
}
const (
name = "live"
)
// 1. once in maxDelay we are selecting randow flat
// 2. then send signal to enable service lights in stack for Service TTL
// 3. Livetime of random flat is ttl +/- 40% randomly
// 4. if ttl is reached, then switch off all lights in flat
// 5. During live time each window of the flat performing a program generated for the live time
// 6. Program contains <maxchanges> changes of light state with random delay between 0 and <maxInternalDelay>
// max live time for the interval in program : <livetime>/<maxchanges> +/- 30%
type Options struct {
MaxDelay time.Duration `long:"max-delay" env:"MAX_DELAY" default:"30s" description:"max delay between flat selection"`
FlatTTL time.Duration `long:"flat-ttl" env:"FLAT_TTL" default:"5h" description:"flat live time"`
ServiceTTL time.Duration `long:"service-ttl" env:"SERVICE_TTL" default:"20s" description:"service live time"`
MaxChanges uint `long:"max-changes" env:"MAX_CHANGES" default:"25" description:"max changes in flat per window"`
}
type Live struct {
lights LightsController
mapping [][]internal.Light
opts Options
done chan struct{}
log *slog.Logger
rand *rand.Rand
mu sync.RWMutex
isActive bool
}
//go:generate ../../../bin/moq -out mocks_test.go . LightsController
func New(l LightsController, mapping [][]internal.Light, opts Options) *Live {
return &Live{
lights: l,
opts: opts,
mapping: mapping,
log: slog.With("flow", name),
rand: rand.New(rand.NewSource(time.Now().UnixNano())), //no-lint: gosec
done: make(chan struct{}),
}
}
func (l *Live) Name() string {
return name
}
func (l *Live) serviceOn(ctx context.Context, sig <-chan struct{}, ttl time.Duration) error {
allServiceLights := []internal.LightAddress{}
for _, l := range l.mapping {
for _, f := range l {
if f.Kind == internal.LightTypeServiceNoManLand {
allServiceLights = append(allServiceLights, f.Addr)
}
}
}
t := time.NewTimer(ttl)
for {
select {
case <-sig:
// switch on all service lights
for _, v := range allServiceLights {
err := l.lights.Set(v, true)
if err != nil {
return fmt.Errorf("couldn't switch on light '%v': %w", v, err)
}
}
t.Reset(ttl)
case <-ctx.Done():
return nil
case <-t.C:
// switch off all service lights
for _, v := range allServiceLights {
err := l.lights.Set(v, false)
if err != nil {
return fmt.Errorf("couldn't switch off light '%v': %w", v, err)
}
}
}
}
}
func (l *Live) Start(ctx context.Context) error {
l.log.Info("starting flow", slog.Any("opts", l.opts))
l.done = make(chan struct{})
l.mu.Lock()
l.isActive = true
l.mu.Unlock()
// switch on entrance light
l.log.Info("swithching off all lights but entrance")
entrance := internal.Light{}
LOOP:
for _, row := range l.mapping {
for _, light := range row {
if light.Kind == internal.LightTypeServiceEntrance {
entrance = light
break LOOP
}
}
}
err := l.lights.Reset()
if err != nil {
return fmt.Errorf("couldn't switch off lights: %w", err)
}
err = l.lights.Set(entrance.Addr, true)
if err != nil {
return fmt.Errorf("couldn't switch on entrance light '%v': %w", entrance.Addr, err)
}
return l.mainCycle(ctx)
}
func (l *Live) Stop() {
l.mu.Lock()
defer l.mu.Unlock()
if l.isActive {
l.log.Info("stopping flow")
l.isActive = false
close(l.done)
}
}
func (l *Live) mainCycle(ctx context.Context) error {
slog.Info("starting real life flow", slog.Any("opts", l.opts))
var (
serviceOnChan = make(chan struct{})
nextFlatSelectionIn = time.Duration(0)
timer = time.NewTimer(l.opts.MaxDelay)
onGoing = map[int]bool{}
flats = []int{}
)
// collect flats
for _, l := range l.mapping {
for _, w := range l {
if w.Number != 0 {
flats = append(flats, w.Number)
}
}
}
// make error group to wait for all goroutines
group, ctx := errgroup.WithContext(ctx)
// Start service lights
group.Go(func() error { return l.serviceOn(ctx, serviceOnChan, l.opts.ServiceTTL) })
for {
l.log.Info("next flat selection in", slog.Duration("duration", nextFlatSelectionIn))
timer.Reset(nextFlatSelectionIn)
select {
case <-ctx.Done():
return nil
case <-l.done:
return nil
case <-timer.C:
if len(onGoing) == len(flats) {
l.log.Info("all flats are busy, waiting for next flat selection")
continue
}
selectedFlat := 0
for {
nominant := flats[l.rand.Intn(len(flats))]
if onGoing[nominant] {
continue
}
selectedFlat = nominant
onGoing[selectedFlat] = true
break
}
l.log.Info("selected flat", slog.Int("flat", selectedFlat))
serviceOnChan <- struct{}{}
// start the flat routine
group.Go(func() error {
err := l.flatCycle(ctx, group, selectedFlat)
if err != nil {
l.log.Error("couldn't process flat cycle", slog.Int("flat", selectedFlat), slog.Any("err", err))
return fmt.Errorf("couldn't process flat cycle: %w", err)
}
delete(onGoing, selectedFlat)
return nil
})
nextFlatSelectionIn = randomizeDuration(l.rand, l.opts.MaxDelay, 0.4)
}
}
}
func (l *Live) flatCycle(ctx context.Context, group *errgroup.Group, flat int) error {
flatWindows := []internal.LightAddress{}
for _, l := range l.mapping {
for _, w := range l {
if w.Number == flat && w.Kind != internal.LightTypeWallStub {
flatWindows = append(flatWindows, w.Addr)
}
}
}
l.log.Info("flat cycle", slog.Int("flat", flat), slog.Duration("ttl", l.opts.FlatTTL))
// Start flat live
for _, fw := range flatWindows {
schedule := getWindowSchedule(l.rand, l.opts.FlatTTL, l.opts.MaxChanges)
l.log.Info("window schedule", slog.Int("flat", flat), slog.Any("addr", fw), slog.String("schedule", schedule.String()))
fw := fw
// Start window routine
group.Go(func() error { return l.executeScheduleFor(ctx, schedule, fw) })
}
for {
select {
case <-ctx.Done():
return nil
case <-l.done:
return nil
}
}
}
// executeScheduleFor executes the given schedule for a specific light address.
// It starts executing the program by setting the light on or off based on the schedule.
// It continues executing the program until the schedule is completed or the context is done.
// If the context is done or the execution is interrupted, it returns nil.
// If there is an error while switching the light, it returns an error with a formatted message.
func (l *Live) executeScheduleFor(ctx context.Context, schedule windowSchedule, addr internal.LightAddress) error {
// Start executing program
timer := time.NewTimer(l.opts.FlatTTL)
for _, p := range schedule {
timer.Reset(p.duration)
err := l.lights.Set(addr, p.isOn)
if err != nil {
return fmt.Errorf("couldn't switch light '%v': %w", addr, err)
}
select {
case <-ctx.Done():
return nil
case <-l.done:
return nil
case <-timer.C:
continue
}
}
return nil
}
// randomizeDuration randomize time <t> in the border of +/- <fluctuation * 100 > percent
func randomizeDuration(r *rand.Rand, t time.Duration, fluctuation float64) time.Duration {
// Generate a random percentage within the fluctuation range
randomPercentage := (r.Float64() * 2 * fluctuation) - fluctuation
// Apply the fluctuation to the original duration
return t + time.Duration(float64(t)*randomPercentage)
}