Put a bus on JetStream¶
By the end of this tutorial a bus will be carrying events over JetStream, and you will have seen a declined message come back with a higher attempt number. It needs no NATS install: the server runs inside your program. You should have worked through getting started first.
1. Start an embedded server¶
Create a module and add the packages you import with your usual tooling. Then start a server with JetStream on, storing its data in a temporary directory:
package main
import (
"context"
"fmt"
"log/slog"
"os"
"time"
"gitlab.com/phpboyscout/go/envelope"
gonats "gitlab.com/phpboyscout/go/nats"
"gitlab.com/phpboyscout/go/nats/client"
"gitlab.com/phpboyscout/go/nats/server"
"gitlab.com/phpboyscout/go/messaging"
nats "gitlab.com/phpboyscout/go/messaging-nats"
)
func main() {
if err := run(context.Background()); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run(ctx context.Context) error {
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
dir, err := os.MkdirTemp("", "js")
if err != nil {
return err
}
defer os.RemoveAll(dir)
srv, err := server.New(ctx, gonats.ServerSettings{InProcessOnly: true, JetStream: true, StoreDir: dir})
if err != nil {
return err
}
if err := server.Start(logger, srv)(ctx); err != nil {
return err
}
defer server.Stop(logger, srv)(context.Background())
InProcessOnly means the server has no network listener. Clients reach it with client.InProcess.
2. Create the stream¶
The adapter binds to a stream and never creates one, so play the operator and create it first:
op, err := client.Connect(ctx, gonats.ClientSettings{Name: "operator"}, nil, client.InProcess(srv))
if err != nil {
return err
}
if _, err := op.Stream(ctx, client.StreamSettings{
Name: "GREETINGS", Subjects: []string{"greeting.>"}, MaxMsgs: 1000,
}); err != nil {
return err
}
_ = op.Close(ctx)
go/nats refuses a stream with no bound, so MaxMsgs is required. The stream is file-backed unless you
set Memory, which the adapter would refuse.
3. Bind a bus to it¶
The bus has one subscription. Its handler declines the first attempt and accepts the second:
done := make(chan struct{})
bus, err := messaging.New(
nats.JetStream(nats.JetStreamSettings{
Settings: nats.Settings{Options: []client.Option{client.InProcess(srv)}, Logger: logger},
Stream: "GREETINGS",
}),
messaging.Settings{
Subscriptions: []messaging.SubscriptionSpec{{
Name: "greeter", Pattern: "greeting.>", Shape: messaging.Fanout,
Mode: messaging.AtLeastOnce, DurableName: "greeter", MaxDeliver: 3,
Handler: func(_ context.Context, d messaging.Delivery) error {
fmt.Println("attempt", d.Attempt, "of", d.Subject)
if d.Attempt == 1 {
return d.Nack()
}
close(done)
return d.Ack()
},
}},
},
)
if err != nil {
return err
}
Mode: AtLeastOnce needs a DurableName and a MaxDeliver. On this backend the durable name becomes a
consumer on the stream.
4. Start it and publish¶
if err := bus.Start(ctx); err != nil {
return err
}
defer bus.Stop(context.Background())
select {
case <-bus.Ready():
case <-time.After(10 * time.Second):
return fmt.Errorf("the bus did not become ready")
}
if err := bus.Publish(ctx, "greeting.en", envelope.Event{
SpecVersion: "1.0", ID: "1", Source: "urn:example:tutorial",
Type: "com.example.greeting.v1", Data: []byte(`{"text":"hello"}`),
}); err != nil {
return err
}
select {
case <-done:
case <-time.After(10 * time.Second):
return fmt.Errorf("no second attempt")
}
return nil
}
Run it. The handler prints two lines:
The Publish returned only once the stream had the message, because the JetStream backend waits for the
server's acknowledgement. The Nack made the server offer the message again, and the attempt number is
the server's own count.
What you have¶
A bus on a durable stream, with a message redelivered after a decline. To go further:
- Subscribe durably for
AckWait, sharing a name and reopening one. - Core NATS or JetStream for what the other backend gives up.
- Connect to a NATS server to point the bus at a real one.