github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/core/changestream/subscription.go (about)

     1  // Copyright 2023 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package changestream
     5  
     6  // Subscription is an interface that can be used to receive events from the
     7  // event queue and unsubscribe from the queue.
     8  type Subscription interface {
     9  	// Changes returns the channel that the subscription will receive events on.
    10  	Changes() <-chan ChangeEvent
    11  
    12  	// Unsubscribe removes the subscription from the event queue.
    13  	Unsubscribe()
    14  
    15  	// Done provides a way to know from the consumer side if the underlying
    16  	// subscription has been terminated. This is useful to know if the
    17  	// event queue has been killed.
    18  	Done() <-chan struct{}
    19  }
    20  
    21  // SubscriptionOption is an option that can be used to create a subscription.
    22  type SubscriptionOption struct {
    23  	namespace  string
    24  	changeMask ChangeType
    25  	filter     func(ChangeEvent) bool
    26  }
    27  
    28  // Namespace returns the name of the type that the subscription will tied to.
    29  func (o SubscriptionOption) Namespace() string {
    30  	return o.namespace
    31  }
    32  
    33  // ChangeMask returns the change mask that the subscription will be for.
    34  func (o SubscriptionOption) ChangeMask() ChangeType {
    35  	return o.changeMask
    36  }
    37  
    38  // Filter returns the filter function that the subscription will be for.
    39  func (o SubscriptionOption) Filter() func(ChangeEvent) bool {
    40  	return o.filter
    41  }
    42  
    43  // Namespace returns a SubscriptionOption that will subscribe to the given
    44  // namespace.
    45  func Namespace(namespace string, changeMask ChangeType) SubscriptionOption {
    46  	return SubscriptionOption{
    47  		namespace:  namespace,
    48  		changeMask: changeMask,
    49  		filter:     func(ce ChangeEvent) bool { return true },
    50  	}
    51  }
    52  
    53  // FilteredNamespace returns a SubscriptionOption that will subscribe to the given
    54  // topic and filter the events using the given function.
    55  func FilteredNamespace(namespace string, changeMask ChangeType, filter func(ChangeEvent) bool) SubscriptionOption {
    56  	opt := Namespace(namespace, changeMask)
    57  	opt.filter = filter
    58  	return opt
    59  }