-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpublisher.go
77 lines (68 loc) · 1.91 KB
/
publisher.go
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package vnats
import (
"fmt"
"log/slog"
"strings"
"time"
"github.com/nats-io/nats.go"
)
// NewPublisher creates a new Publisher that publishes to a NATS stream.
func (c *Connection) NewPublisher(args PublisherArgs) (*Publisher, error) {
if err := validateStreamName(args.StreamName); err != nil {
return nil, err
}
if err := c.nats.EnsureStreamExists(&nats.StreamConfig{
Name: args.StreamName,
Subjects: []string{args.StreamName + ".>"},
Storage: defaultStorageType,
Replicas: len(c.nats.Servers()),
Duplicates: defaultDuplicationWindow,
MaxAge: time.Hour * 24 * 30,
}); err != nil {
return nil, fmt.Errorf("publisher could not be created: %w", err)
}
p := &Publisher{
conn: c,
logger: c.logger,
streamName: args.StreamName,
}
return p, nil
}
// Publisher is a NATS publisher that publishes to a NATS stream.
type Publisher struct {
conn *Connection
streamName string
logger *slog.Logger
}
// Publish publishes the message (data) to the given subject.
func (p *Publisher) Publish(msg *Msg) error {
if err := validateSubject(msg.Subject, p.streamName); err != nil {
return err
}
err := p.conn.nats.PublishMsg(msg.toNATS(), msg.MsgID)
if err != nil {
return fmt.Errorf("message with msgID: %s @ %s could not be published: %w", msg.MsgID, msg.Subject, err)
}
return nil
}
func validateSubject(subject, streamName string) error {
if err := validateStreamName(streamName); err != nil {
return err
}
if subject == "" {
return fmt.Errorf("subject cannot be empty")
}
if !strings.HasPrefix(subject, streamName+".") {
return fmt.Errorf("subject needs to begin with `STREAM_NAME.`")
}
return nil
}
func validateStreamName(streamName string) error {
if streamName == "" {
return fmt.Errorf("streamName cannot be empty")
}
if strings.ContainsAny(streamName, "*.>") {
return fmt.Errorf("streamName cannot contain any of chars: *.>")
}
return nil
}