github.com/kyma-project/kyma-environment-broker@v0.0.1/internal/event/pubsub.go (about)

     1  package event
     2  
     3  import (
     4  	"context"
     5  	"reflect"
     6  	"sync"
     7  
     8  	"github.com/sirupsen/logrus"
     9  )
    10  
    11  type Handler = func(ctx context.Context, ev interface{}) error
    12  
    13  type Publisher interface {
    14  	Publish(ctx context.Context, event interface{})
    15  }
    16  
    17  type Subscriber interface {
    18  	Subscribe(evType interface{}, evHandler Handler)
    19  }
    20  
    21  // PubSub implements a simple event broker which allows to send event across the application.
    22  type PubSub struct {
    23  	mu  sync.Mutex
    24  	log logrus.FieldLogger
    25  
    26  	handlers map[reflect.Type][]Handler
    27  }
    28  
    29  func NewPubSub(log logrus.FieldLogger) *PubSub {
    30  	return &PubSub{
    31  		log:      log,
    32  		handlers: make(map[reflect.Type][]Handler),
    33  	}
    34  }
    35  
    36  func (b *PubSub) Publish(ctx context.Context, ev interface{}) {
    37  	tt := reflect.TypeOf(ev)
    38  	hList, found := b.handlers[tt]
    39  	if found {
    40  		for _, handler := range hList {
    41  			go func(h Handler) {
    42  				err := h(ctx, ev)
    43  				if err != nil {
    44  					b.log.Errorf("error while calling pubsub event handler: %s", err.Error())
    45  				}
    46  			}(handler)
    47  		}
    48  	}
    49  }
    50  
    51  func (b *PubSub) Subscribe(evType interface{}, evHandler Handler) {
    52  	tt := reflect.TypeOf(evType)
    53  	b.mu.Lock()
    54  	defer b.mu.Unlock()
    55  
    56  	if _, found := b.handlers[tt]; !found {
    57  		b.handlers[tt] = []Handler{}
    58  	}
    59  
    60  	b.handlers[tt] = append(b.handlers[tt], evHandler)
    61  }