2021-02-23 14:13:04 +00:00
|
|
|
package v1
|
2020-12-18 15:47:45 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
|
2022-04-26 23:01:45 +00:00
|
|
|
"github.com/zitadel/zitadel/internal/eventstore/v1/models"
|
2020-12-18 15:47:45 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
subscriptions map[models.AggregateType][]*Subscription = map[models.AggregateType][]*Subscription{}
|
|
|
|
subsMutext sync.Mutex
|
|
|
|
)
|
|
|
|
|
|
|
|
type Subscription struct {
|
|
|
|
Events chan *models.Event
|
|
|
|
aggregates []models.AggregateType
|
|
|
|
}
|
|
|
|
|
|
|
|
func (es *eventstore) Subscribe(aggregates ...models.AggregateType) *Subscription {
|
|
|
|
events := make(chan *models.Event, 100)
|
|
|
|
sub := &Subscription{
|
|
|
|
Events: events,
|
|
|
|
aggregates: aggregates,
|
|
|
|
}
|
|
|
|
|
|
|
|
subsMutext.Lock()
|
|
|
|
defer subsMutext.Unlock()
|
|
|
|
|
|
|
|
for _, aggregate := range aggregates {
|
|
|
|
_, ok := subscriptions[aggregate]
|
|
|
|
if !ok {
|
|
|
|
subscriptions[aggregate] = make([]*Subscription, 0, 1)
|
|
|
|
}
|
|
|
|
subscriptions[aggregate] = append(subscriptions[aggregate], sub)
|
|
|
|
}
|
|
|
|
|
|
|
|
return sub
|
|
|
|
}
|
|
|
|
|
2021-02-24 12:24:33 +00:00
|
|
|
func Notify(events []*models.Event) {
|
2020-12-18 15:47:45 +00:00
|
|
|
subsMutext.Lock()
|
|
|
|
defer subsMutext.Unlock()
|
2021-02-24 12:24:33 +00:00
|
|
|
for _, event := range events {
|
|
|
|
subs, ok := subscriptions[event.AggregateType]
|
2020-12-18 15:47:45 +00:00
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
for _, sub := range subs {
|
2021-02-24 12:24:33 +00:00
|
|
|
sub.Events <- event
|
2020-12-18 15:47:45 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Subscription) Unsubscribe() {
|
|
|
|
subsMutext.Lock()
|
|
|
|
defer subsMutext.Unlock()
|
|
|
|
for _, aggregate := range s.aggregates {
|
|
|
|
subs, ok := subscriptions[aggregate]
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
for i := len(subs) - 1; i >= 0; i-- {
|
|
|
|
if subs[i] == s {
|
|
|
|
subs[i] = subs[len(subs)-1]
|
|
|
|
subs[len(subs)-1] = nil
|
|
|
|
subs = subs[:len(subs)-1]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-07-09 09:33:43 +00:00
|
|
|
_, ok := <-s.Events
|
|
|
|
if ok {
|
|
|
|
close(s.Events)
|
|
|
|
}
|
2020-12-18 15:47:45 +00:00
|
|
|
}
|