|
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() { |
|
|
|
delete(c.cycles, c.history[cycleHist-1]) |
|
|
|
|
|
copy(c.history[:], c.history[1:]) |
|
|
|
|
|
c.history[0] = uuid.New() |
|
c.cycles[c.history[0]] = make(chan struct{}) |
|
} |
|
|
|
|
|
|
|
func (c *cycleMonitor) startNextCycle() func() { |
|
c.mx.Lock() |
|
defer c.mx.Unlock() |
|
|
|
ch := c.cycles[c.history[0]] |
|
c._newID() |
|
|
|
return func() { close(ch) } |
|
} |
|
|
|
|
|
func (c *cycleMonitor) WaitCycleID(ctx context.Context, cycleID uuid.UUID) error { |
|
if c == nil { |
|
|
|
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() |
|
} |
|
} |
|
|
|
|
|
func (c *cycleMonitor) NextCycleID() uuid.UUID { |
|
if c == nil { |
|
|
|
return uuid.Nil |
|
} |
|
|
|
c.mx.Lock() |
|
defer c.mx.Unlock() |
|
|
|
return c.history[0] |
|
} |
|
|