Skip to content

Events ​

craftgo generates event code the way protoc generates message code: payload types, their validation, one descriptor per contract, and nothing else. Which events a deployable listens to, on which group, behind which middleware, is that deployable's own Go.

The model ​

One producer publishes a contract declared in the design; each listener group receives its own copy, and replicas inside a group share the work.

The contract sits in the design, between one producer and any number of listeners.

One producer publishes an event, and the design does not know how many listeners exist or where they run. Each listener joins under a group; every group receives every message once, and replicas inside a group divide that work. The runtime half is the bus - events.Bus is server.Server for the listener side, the one thing every subscription passes through.

Declaring events ​

An event is a file-level declaration, like type; a service holds HTTP methods only. Files group into packages by their package declaration, so the usual layout is one folder per version and one event per file, a new version published beside the old one until every listener has moved.

design/orders/
├── v1/
│   ├── placed.craftgo         package ordersv1
│   └── shipped.craftgo        package ordersv1
└── v2/
    └── placed.craftgo         package ordersv2
craftgo
package orders

type OrderPlaced {
    orderId string @minLength(1)
    total   int64  @gte(0)
}

@doc("An order was accepted.")
event Placed {
    payload OrderPlaced
}

payload must name a type, so every contract has named fields and its own Validate(). The payload is one JSON message, so a field it reaches may not carry @path, @query, @header, @cookie or @form, nor hold a file. Events have their own namespace, so type OrderPlaced and event OrderPlaced coexist. A payload may also be an array of a declared type - a JSON array on the wire, typed on the slice and validated element by element:

craftgo
event BatchPlaced {
    payload OrderPlaced[]
}

The wire identity defaults to <package>.<Event> - orders.Placed above - and @contract("payments.settled.v1") overrides it to match a name another system already publishes. Two events resolving to one identity are rejected at design time. The only event decorators are @contract, @doc and @deprecated.

What is generated ​

One file per design package that declares an event, and nothing beside it: <events out>/<pkg>/events.go.

go
// Code generated by craftgo. DO NOT EDIT.

package orders

import (
	craftevents "github.com/craftgodotdev/craftgo/pkg/events"

	types "example.com/app/internal/types/orders"
)

// PlacedContract is the wire identity of Placed.
const PlacedContract = "orders.Placed"

// An order was accepted.
//
// Placed is the orders.Placed event contract.
var Placed = craftevents.NewEvent[types.OrderPlaced](PlacedContract, (*types.OrderPlaced).Validate)

@doc, or the comment above the event when it has none, heads the descriptor's comment, an empty // line above the line craftgo writes. The validator is the payload's Validate, or for an array payload a generated function that validates each element. A descriptor holds no bus - the bus is a parameter at the call - so one contract package serves every deployable that imports it.

There is no handler interface, no registration function, no publisher type and no transport adapter. Where the file lands is events.targets[].out; see Configuration.

Publishing ​

A publish runs validate, then encode with the bus's codec, then the bus, then a Publisher - JetStream, core NATS, Kafka, memory, or your own outbox.

The descriptor validates and encodes; the transport under the bus decides where the bytes go.

go
err := orders.Placed.Publish(ctx, bus, &types.OrderPlaced{OrderID: order.ID, Total: order.Total},
	craftevents.WithKey(string(order.ID)))

Publish validates first: a payload that does not validate is a *PayloadError and nothing goes on the wire. The options fill in everything beside the payload - WithKey (the entity the message is about, used by a transport that orders per entity), WithDedupID (JetStream drops a repeat within its stream's duplicate window; Kafka, core NATS and memory carry the ID to the consumer and act on nothing), WithHeader, WithAdapterOption. bus.PublishAll(ctx, envs) publishes a batch and reports a partial failure as a *PartialPublishError naming the indices that did not go out; an envelope it cannot encode refuses the whole batch, before any of it is sent, with an *EnvelopeError naming its index.

Every shipped transport delivers the key, the dedup ID and the metadata as written. NATS carries them in headers, which cannot hold everything, so on core NATS and JetStream a value NATS would change - padded with spaces or tabs, or holding a line break - or a metadata key that is no NATS header name (printable ASCII without spaces or any of "(),/:;<=>?@[\]{}) fails the publish with nats.ErrNotCarried before anything is sent.

A transport adapter is anything implementing one method:

go
type Publisher interface {
	Publish(ctx context.Context, msg *Message) error
}

An outbox is that method writing the encoded message to a table in the same transaction as the business write. A drainer then reads the table and calls bus.PublishAll against a bus wired to the real broker, each stored payload a wire.Raw so the codec carries its bytes through without encoding them again. Nothing generated changes, because nothing generated names a broker.

Consuming ​

A delivery travels broker, transport, panic recovery, the bus chain installed with bus.Use, the subscription chain, decode and validate, then your method; the transport then acks, naks or terminates the delivery as the chain asked through the message, and acks it when nothing was asked.

Everything between the broker and your method is the same for every subscription on the bus.

A listener is one line: the descriptor, the group it joins, and the method that handles it.

go
// internal/handler/orders/handler.go
var (
	NotificationGroup = craftevents.Group("order-notifications")
	LedgerGroup       = craftevents.Group("order-ledger")
)

func Register(bus *craftevents.Bus) error {
	notifier, ledger := Notifier{}, Ledger{}
	return errors.Join(
		orders.Placed.Subscribe(bus, NotificationGroup, notifier.SendReceipt),
		orders.Shipped.Subscribe(bus, NotificationGroup, notifier.SendDispatchNote),
		orders.Placed.Subscribe(bus, LedgerGroup, ledger.BookOrder),
	)
}

Subscribe(bus, group, fn) is typed against the contract: fn takes (ctx, *types.OrderPlaced) error with the payload already decoded and validated, so a method with the wrong signature does not compile at the call. errors.Join offers every line to the bus, so a refusal in the middle neither hides the refusals beside it nor cancels the registrations after it; each is a *RegisterError naming its contract and group.

main.go is where the bus, its chain and the modules meet:

go
bus := craftevents.New(craftevents.WithTransport(tr), craftevents.WithCodec(codecjson.Codec{}))
bus.Use(logging.AccessLog(craftlog.Slog()))

if err := handler.Register(bus); err != nil {
	return err
}
return bus.Start(ctx)

There is no default codec, and WithPublisher or WithSubscriber alone is enough for a binary that only publishes or only listens. Start hands the whole batch to the transport in one call, every handler wrapped; a second Start, or a Register after one, is ErrStarted.

Groups ​

A group is the broker identity a subscription joins: the Kafka consumer group, the NATS queue group, the JetStream durable. Subscriptions sharing one divide the stream between them, so a group is the unit of scaling and of failure isolation - not of ordering. events.Group is a named type so an application declares its groups once, as values beside the registrations that use them, rather than as loose strings. Register refuses an empty group. On a transport that remembers a position per group - Kafka, JetStream - the name is where those consumers resume: if it has an offset, write the name down.

A group with no position yet starts where its transport puts it:

transporta new group startsto start it elsewhere
JetStreamat the first message the stream holds (DeliverAll)nats.WithGroupConfig(group, nats.DeliverPolicy(jetstream.DeliverNewPolicy)), or create the durable beforehand with the policy you want, which Start adopts
Kafka, classic groupat the earliest record, replaying the whole topic - franz-go's defaultkafka.WithClientOptions(kgo.ConsumeResetOffset(kgo.NewOffset().AtEnd())) reads only what is published after the group first joins
Kafka, share groupat the end of the topicthe broker's group config share.auto.offset.reset, earliest to read the topic from its start
core NATS, memoryat the next message publishednothing to set: neither keeps a position

Each setting counts only while the group has no position: DeliverPolicy when the durable is created, the reset offset for a partition the classic group has committed nothing on.

Middleware ​

A consumer middleware is ordinary Go, never a declaration:

go
type Middleware func(sub craftevents.Subscription, next craftevents.Handler) craftevents.Handler

sub carries the contract, the consumer and the group being wrapped, so one chain can behave differently per group. Chains compose outermost first: Use(A, B, C) wraps a handler as A(B(C(h))). The chain belongs to the bus, the only thing every subscription passes through - WithMiddleware installs it at construction, bus.Use appends afterwards, and Use after Start panics. One subscription that needs its own wrap is built with the descriptor's Subscription(bus, group, fn), given a Chain, applied inside the bus chain, and handed to bus.Register. A failed decode or validation reaches the chain as *PayloadError, a message stamped with another codec as ErrCodecMismatch, a panicking handler as *PanicError.

Dispositions ​

A middleware asks for something other than "done" through the message: msg.Settle() takes the delivery, msg.Redeliver() hands it back, msg.Reject() gives it up. Asking for nothing settles.

A frame that panicked did not finish deciding, so what it asked for is dropped. A panicking handler leaves the message undecided and the chain above it decides, as it does for any other error. A panic in a middleware unwinds past the whole chain, leaving nothing above to decide - so the bus asks for redelivery on a transport that can honour one, and the delivery is retried rather than acked away.

Only some transports can honour this

JetStream and a Kafka share group track each record; a classic Kafka consumer group, core NATS and the in-process transport do not, and there Redeliver settles instead. Name what you need with WithDispositionRequired and Register refuses a transport that cannot honour it.

The plan ​

No generated file states what a deployable listens to, so bus.Plan() reports it instead, before or after Start. It sorts groups by name and consumers by contract, and renders that order however the plan was built, which makes it a golden file:

go
bus := craftevents.New(craftevents.WithTransport(memory.New()), craftevents.WithCodec(codecjson.Codec{}))
if err := handler.Register(bus); err != nil {
	t.Fatal(err)
}
got, err := json.MarshalIndent(bus.Plan(), "", "  ")
// compare got against testdata/plan.json

A rename, a lost listener or a group that drifted between two deployables then fails a test rather than a deploy.

Consuming in batches ​

A subscription can take its messages in batches, for work that is cheaper in bulk - one insert of a hundred rows, one call to a bulk API:

go
var BulkLedgerGroup = craftevents.Group("order-ledger-bulk")

func RegisterBulk(bus *craftevents.Bus, store *Store) error {
	return orders.Placed.SubscribeBatch(bus, BulkLedgerGroup,
		craftevents.BatchSize{Max: 100, Wait: time.Second},
		func(ctx context.Context, batch []craftevents.Item[types.OrderPlaced]) error {
			rows := make([]types.OrderPlaced, 0, len(batch))
			for _, it := range batch {
				if it.Payload.Total == 0 {
					it.Msg.Reject() // this message alone
					continue
				}
				rows = append(rows, *it.Payload)
			}
			return store.InsertOrders(ctx, rows)
		})
}

A batch holds at most Max messages, and no message waits longer than Wait for its batch to fill; a transport may hand a batch over sooner. Each message is decoded and validated as for Subscribe, and one that fails is left out of batch. The transport answers every message only once the function has returned, holding them open meanwhile. A broker's transport starts the next batch after that, so its batches keep the order their messages arrived in.

What each message becomes is decided per message:

  • asking for nothing settles it, as for one message;
  • it.Msg.Redeliver() or it.Msg.Reject() answers for that message alone;
  • it.Fail(err) gives that item an error of its own;
  • the function's error goes to every item without one - unless it is craftevents.ItemErrors, keyed by index into the batch the function was handed, which fails only the items it names.

The handler returns the failures as craftevents.ItemErrors, keyed by index into the whole batch: a payload that did not decode or validate as its *PayloadError, a message stamped with another codec as ErrCodecMismatch, the others as their own error or the function's. The transport reports that error once, with no message. An error redelivers nothing by itself, here as for one message: the chain decides.

A batch subscription holds its group alone - Register refuses it beside a subscription of another contract in the group with ErrBatchGroupShared, and the same contract twice with ErrDuplicateSubscription - and needs a transport that consumes in batches, which every shipped one does (ErrBatchUnsupported otherwise). BatchSize with a Max below 1 or a Wait that is not positive is ErrInvalidBatch.

Batch middleware ​

The chain installed with Use wraps one message and does not run for a batch. Batches have a chain of their own:

go
type BatchMiddleware func(sub craftevents.Subscription, next craftevents.BatchHandler) craftevents.BatchHandler

WithBatchMiddleware installs it at construction and bus.UseBatch appends afterwards; a subscription built with the descriptor's BatchSubscription(bus, group, size, fn) takes its own in Batch.Chain. The wrap order and the panic rules are those of one message: a panic in a batch middleware asks for every message of the batch to be redelivered, on a transport that can. logging.BatchAccessLog writes one line per batch. A retry policy reads the ItemErrors, and takes an error naming no message - the *PanicError of a handler that panicked, say - as every message failing:

go
// redeliverFailures asks for each message the batch failed to come back, but one whose
// payload cannot decode, which fails the same way again.
func redeliverFailures(_ craftevents.Subscription, next craftevents.BatchHandler) craftevents.BatchHandler {
	return func(ctx context.Context, batch []*craftevents.Message) error {
		err := next(ctx, batch)
		if err == nil {
			return nil
		}
		var failed craftevents.ItemErrors
		if !errors.As(err, &failed) {
			// An error naming no message, a *PanicError among them, fails every one.
			failed = craftevents.ItemErrors{}
			for i := range batch {
				failed[i] = err
			}
		}
		for i, itemErr := range failed {
			var bad *craftevents.PayloadError
			switch {
			case batch[i].Disposition() != craftevents.DispositionUnset:
			case errors.As(itemErr, &bad):
				batch[i].Reject()
			default:
				batch[i].Redeliver()
			}
		}
		return err
	}
}

NATS JetStream ​

One durable per group carries that group's FilterSubjects; one process subscribes several groups, and an existing durable is adopted when its filter equals the plan, widened when it is a strict subset, and refused otherwise.

A group is a durable name, and the durable's filter set is the plan this process registered.

nats.NewJetStream(conn, opts...) reads from a stream, and is what makes Redeliver and Reject mean something on NATS. It creates no stream: Start refuses a subject no stream carries. A durable reads one stream, so a group whose subjects span two is refused at start-up. At Start an existing durable is verified, not reshaped:

carried filter vs planwhat happens
equaladopted as is
a strict subset of the planwidened and logged - this version added a listener
anything elserefused, naming both sets

"Anything else" is a plan that drops subjects, one that only partly overlaps, or a durable with no filter at all. Re-pointing any of those stops those subjects reaching anyone, so it is refused unless the group carries nats.AllowNarrow() - a deliberate removal.

Per-group settings ​

Delivery settings belong to the group, because the group is what the server keeps them on:

go
js, err := nats.NewJetStream(conn,
	nats.WithGroupConfig(LedgerGroup, nats.DeliverPolicy(jetstream.DeliverNewPolicy),
		nats.MaxInFlight(8), nats.AckWait(2*time.Minute)))

MaxInFlight, FetchSize, AckWait, DeliverPolicy, ConsumerConfig and AllowNarrow are the group options, and repeated calls for one group accumulate. AckWait, DeliverPolicy and ConsumerConfig apply when the durable is created, and AllowNarrow when Start checks an existing one; WithMaxInFlight, WithFetchSize and WithAckWait are the transport-wide defaults.

MaxInFlight is how many messages one durable's pull keeps buffered here, and the default is 1 deliberately: a buffered message waits for every handler ahead of it with the server's AckWait clock already running. Raise it only where n × the slowest handler stays under AckWait, or a message is redelivered while it still sits in the buffer. WithMaxDeliveries (default 5) caps a redelivery loop and WithRedeliverBackoff(fn) delays each redelivery by fn(deliveries).

A batch subscription's group pulls its durable one batch at a time: one pull waits for the batch's first message, then pulls of the group's FetchSize - 500 unless WithFetchSize or the group says otherwise - fill it until it holds Max or Wait has passed since that message, each within the durable's MaxRequestBatch and MaxRequestExpires. A pull holds room for its FetchSize messages in the client. Every message of it is kept from redelivery, from its arrival until it is answered, however long the handler takes. A Max above the durable's MaxAckPending never fills - the server hands out no more unanswered messages than that - so each batch waits out its Wait. MaxInFlight does not apply to a batch group.

Rolling deploys ​

During a rolling deploy two versions of a deployable share a durable. A subject no listener in this process handles is handed back - NAK'd with the group's AckWait as the delay - so the replica that does handle it gets it, and never terminated. Every hand-back is reported through WithJetStreamErrorHandler with only sub.Group set.

Kafka, core NATS and memory ​

  • pkg/events/kafka - one contract per topic, ordering key as the record key; WithShareGroup asks for a KIP-932 share group instead of a classic consumer group. A classic group commits a fetch's records once each has been handled, and gathers a batch over several fetches, committing it once the handler has returned. A share group keeps every record of a fetch locked until it is answered, those waiting behind the one being handled included. For a batch subscription it hands over one fetch's records, at most Max, and does not wait to fill the batch: the client accepts what one fetch left unanswered at the next.
  • pkg/events/nats (core) - contract to subject, group to queue group; at most once and no nack, so install nats.WithErrorHandler or a failed message is observed by nothing. A batch is gathered from the queue subscription, and is at most once too.
  • pkg/events/memory - in-process, for tests, single-binary deployments and the plan golden test; Drain() waits for in-flight deliveries, a batch still filling among them. Each batch runs on its own goroutine. Each group gets its own copy of a message, payload included, and a handler runs on its subscription's context, as on a broker: the publisher's context does not reach it.

Every option and error type is listed in Runtime API.

Shutting down ​

A deployable stops consuming by cancelling the context it gave Start, then closing the transport - example/brokers defers both, in that order. Once that context has ended, a transport hands no message to a handler, and a handler still running sees its context end.

A handler that fails after the context ended, with the chain asking for nothing or for redelivery, was most likely cut short by the shutdown, so a transport that can hand its message back does so instead of settling it, retry middleware or not. While the subscription runs, an error still redelivers nothing by itself.

transporta message whose handler the shutdown cut shorta message fetched and not yet handed over
JetStreamNAK'd, and delivered again at onceNAK'd; one still in the pull's buffer comes back once AckWait has passed
Kafka, share groupreleased for another deliveryreleased
Kafka, classic groupleft uncommitted, with every record after it in its partition, so the group reads them againleft uncommitted
core NATSgone - core NATS delivers at most oncegone, but a batch still filling is handed over at once, on a context that keeps the subscription's values and ends 30s later
memorygonethe batch still filling, and a delivery that raced the shutdown, run on such a context

A message handled to the end is answered as the chain asked, and a classic group commits it as its read loop stops.

What Close does differs. JetStream's waits up to WithDrainTimeout (30s) for the handlers still running, on their live context, so closing first lets them finish rather than cutting them short. Kafka's closes its clients at once: a record still in a handler, and in a classic group each one handled since the last commit, is delivered again. Cancelling first lets each read loop answer and commit what it handled, unless Close overtakes it - nothing is lost either way. Core NATS's unsubscribes.

Who owns what ​

The design owns the event declaration, the wire name, the payload types and one folder per version; the application owns which events it listens to, the group per subscription, the middleware and the folder layout.

The design is the contract two deployables share; everything operational is the application's.

The design holds the event declaration and its @contract name, the payload types and their validators, one folder per version, and the HTTP services beside them. The application holds which events this deployable listens to, the group per subscription, the middleware on bus.Use, and its own folder layout, retries and transport settings.

Nothing in between is declarable: no listener declaration, no group decorator, no middleware declaration for listeners, no projection. A group or a chain in the design would tie a shared contract to one deployable's operations.

Released under the MIT License.