File size: 1,626 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package engine

import (
	"context"
	"sync"

	"github.com/google/uuid"
	"github.com/target/goalert/validation"
)

const cycleHist = 10

type cycleMonitor struct {
	mx sync.Mutex

	cycles  map[uuid.UUID]chan struct{}
	history [cycleHist]uuid.UUID
}

func newCycleMonitor() *cycleMonitor {
	m := &cycleMonitor{
		cycles: make(map[uuid.UUID]chan struct{}, cycleHist),
	}
	m._newID()
	return m
}

func (c *cycleMonitor) _newID() {
	// remove oldest cycle
	delete(c.cycles, c.history[cycleHist-1])

	// shift history
	copy(c.history[:], c.history[1:])

	// add new cycle
	c.history[0] = uuid.New()
	c.cycles[c.history[0]] = make(chan struct{})
}

// startNextCycle marks the beginning of the next engine cycle.
// It returns a func that should be called when the cycle is finished.
func (c *cycleMonitor) startNextCycle() func() {
	c.mx.Lock()
	defer c.mx.Unlock()

	ch := c.cycles[c.history[0]]
	c._newID()

	return func() { close(ch) }
}

// WaitCycleID waits for the engine cycle with the given UUID to finish.
func (c *cycleMonitor) WaitCycleID(ctx context.Context, cycleID uuid.UUID) error {
	if c == nil {
		// engine is disabled
		return validation.NewGenericError("engine is disabled")
	}

	c.mx.Lock()
	ch, ok := c.cycles[cycleID]
	c.mx.Unlock()
	if !ok {
		return validation.NewGenericError("unknown cycle ID")
	}

	select {
	case <-ch:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

// NextCycleID returns the UUID of the next engine cycle.
func (c *cycleMonitor) NextCycleID() uuid.UUID {
	if c == nil {
		// engine is disabled
		return uuid.Nil
	}

	c.mx.Lock()
	defer c.mx.Unlock()

	return c.history[0]
}