cwtch/event/eventQueue.go

66 lines
1.2 KiB
Go
Raw Permalink Normal View History

package event
import (
"sync"
)
2019-11-12 20:39:55 +00:00
type queue struct {
infChan infiniteChannel
2019-11-12 20:39:55 +00:00
lock sync.Mutex
closed bool
}
// Queue is a wrapper around a channel for handling Events in a consistent way across subsystems.
// The expectation is that each subsystem in Cwtch will manage a given an event.Queue fed from
// the event.Manager.
type Queue interface {
2019-11-12 20:39:55 +00:00
Publish(event Event)
Next() Event
Shutdown()
2019-11-12 20:39:55 +00:00
OutChan() <-chan Event
Len() int
}
// NewQueue initializes an event.Queue
func NewQueue() Queue {
queue := &queue{infChan: *newInfiniteChannel()}
return queue
}
2019-11-12 20:39:55 +00:00
func (iq *queue) inChan() chan<- Event {
return iq.infChan.In()
}
func (iq *queue) OutChan() <-chan Event {
return iq.infChan.Out()
}
2023-04-17 19:05:02 +00:00
// Next returns the next available event from the front of the queue
func (iq *queue) Next() Event {
event := <-iq.infChan.Out()
return event
}
func (iq *queue) Len() int {
return iq.infChan.Len()
}
// Shutdown closes our eventChannel
func (iq *queue) Shutdown() {
2019-11-12 20:39:55 +00:00
iq.lock.Lock()
if !iq.closed {
iq.closed = true
iq.infChan.Close()
}
2019-11-12 20:39:55 +00:00
iq.lock.Unlock()
}
func (iq *queue) Publish(event Event) {
iq.lock.Lock()
if !iq.closed {
iq.inChan() <- event
}
iq.lock.Unlock()
}