77 lines
2.1 KiB
Go
77 lines
2.1 KiB
Go
package natsio
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/nats-io/nats.go"
|
|
)
|
|
|
|
func generateStreamConfig(stream string, subjects []string) *nats.StreamConfig {
|
|
cfg := nats.StreamConfig{
|
|
Name: stream,
|
|
Subjects: subjects,
|
|
Retention: nats.WorkQueuePolicy,
|
|
MaxConsumers: -1,
|
|
MaxMsgSize: -1,
|
|
MaxMsgs: -1,
|
|
NoAck: false,
|
|
}
|
|
return &cfg
|
|
}
|
|
|
|
// GetStreamInfo ...
|
|
func (js JetStream) GetStreamInfo() (*nats.StreamInfo, error) {
|
|
return js.instance.StreamInfo(js.streamName)
|
|
}
|
|
|
|
// AddStream add new stream, with default config
|
|
// Due to subject must have a unique name, subject name will be combined with stream name
|
|
// E.g: stream name is "DEMO", subject name is "Subject-1", so final name in NATS will be: DEMO.Subject-1
|
|
func (js JetStream) AddStream(subjects []string) error {
|
|
// Get info about the stream
|
|
stream, _ := js.GetStreamInfo()
|
|
|
|
// If stream not found, create new
|
|
if stream == nil {
|
|
subjectNames := generateSubjectNames(js.streamName, subjects)
|
|
_, err := js.instance.AddStream(generateStreamConfig(js.streamName, subjectNames))
|
|
if err != nil {
|
|
msg := fmt.Sprintf("[NATS JETSTREAM] - add stream error: %s", err.Error())
|
|
return errors.New(msg)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// DeleteStream ...
|
|
func (js JetStream) DeleteStream() error {
|
|
if err := js.instance.DeleteStream(js.streamName); err != nil {
|
|
msg := fmt.Sprintf("[NATS JETSTREAM] - delete stream error: %s", err.Error())
|
|
return errors.New(msg)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// AddStreamSubjects ...
|
|
func (js JetStream) AddStreamSubjects(subjects []string) error {
|
|
// Get info about the stream
|
|
stream, _ := js.GetStreamInfo()
|
|
if stream == nil {
|
|
msg := fmt.Sprintf("[NATS JETSTREAM] - error when adding stream %s subjects: stream not found", js.streamName)
|
|
return errors.New(msg)
|
|
}
|
|
|
|
// Merge current and new subjects
|
|
subjectNames := generateSubjectNames(js.streamName, subjects)
|
|
newSubjects := mergeAndUniqueArrayStrings(subjectNames, stream.Config.Subjects)
|
|
|
|
_, err := js.instance.UpdateStream(generateStreamConfig(js.streamName, newSubjects))
|
|
if err != nil {
|
|
msg := fmt.Sprintf("[NATS JETSTREAM] - add stream error: %s", err.Error())
|
|
return errors.New(msg)
|
|
}
|
|
return nil
|
|
}
|