-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpubsub.go
More file actions
52 lines (43 loc) · 2.3 KB
/
pubsub.go
File metadata and controls
52 lines (43 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package message
import (
"context"
"errors"
)
var (
ErrInvalidEvent = errors.New("invalid EventOrMessage")
ErrInvalidHandler = errors.New("invalid HandlerFunc func signature")
ErrParamConversionFailed = errors.New("invalid parameter types")
)
type (
// EventOrTopicName is used to give an Event or a Topic a name, so publishers and subscribers can use it.
EventOrTopicName string
// EventOrTopic returns the EventOrTopicName of an EventOrMessage. It is optional and does not have to be
// implemented by each EventOrMessage. If it's not implemented the struct type is used as EventOrTopicName instead.
EventOrTopic interface {
EventOrTopicName() EventOrTopicName
}
// EventOrMessage is an event or message passed between publishers and subscribers.
// The type of EventOrMessage has to be a named struct and will be automatically converted
// from the publisher's type to the subscriber's type, if they share a EventOrTopicName.
EventOrMessage interface{}
// HandlerFunc is the subscriber's handler and must have the signature:
// func(ctx context.Context, eom EventOrMessage) {}.
// HandlerFunc can not be more specific in this definition, so that each call to Subscribe() can give the most
// specific parameter list, it wants to use for its domain.
HandlerFunc interface{}
)
// PubSub is the interface providing a publish and subscribe messaging.
type PubSub interface {
// Publish sends the EventOrMessage to all active subscribers of the given topic.
// Publish will convert the message type to the message type of each subscriber and returns errors for all the
// subscribers where the conversion failed.
Publish(ctx context.Context, eom EventOrMessage) error
// Subscribe registers h as a handler function for the given EventOrTopicName.
// The returned Subscriber can `Unsubscribe()` from the EventOrTopicName.
// The handler func must accept context.Context and EventOrMessage argument, and it will be converted automatically.
// If EventOrMessage implements the EventOrTopic interface, it is called to determine the EventOrTopicName,
// otherwise the struct name is used.
Subscribe(eom EventOrMessage, h HandlerFunc) (*Subscriber, error)
// Shutdown will block and wait for all handlers to finish or for the context to time out, whichever happens first.
Shutdown(ctx context.Context)
}