From d3d947e7b5545489e1b7e27b948d9a6e55ff4f6a Mon Sep 17 00:00:00 2001 From: Louis FRADIN Date: Sun, 14 Jun 2026 16:38:53 +0200 Subject: [PATCH] feat(v3): support receiving multiple messages per operation (#333) Follow-up to #140/#332, which shipped the send side. When a receive operation (or its channel) declares more than one message, generate one subscribe function per message instead of silently handling only the first one: - SubscribeToXForUserCreated / SubscribeToXForUserDeleted, with one callback per message type, plus matching UnsubscribeFromXFor... and per-message methods on the subscriber interface. Single-message operations are unchanged (byte-identical output). - A single broker subscription is opened per channel and multiplexed to the registered per-message handlers, so several per-message subscriptions on one channel no longer collide. - Received messages are discriminated with a try-each-until-valid strategy (unmarshal + validate against each candidate schema using go-playground/validator) and dispatched to the first match. - A message matching none of the expected types is nacked and surfaced through the error handler as the new extensions.ErrNoMatchingMessage. Adds a broker-backed regression test (test/v3/issues/333) covering dispatch of two distinct message types on one channel, the no-match path, and per-message unsubscribe. Documents the behavior and the validator dependency in the README. Co-Authored-By: Claude Opus 4.8 (1M context) --- README.md | 29 +- pkg/codegen/generators/v3/common.go | 13 + pkg/codegen/generators/v3/controller_base.go | 11 +- pkg/codegen/generators/v3/generator.go | 24 +- .../generators/v3/templates/controller.tmpl | 258 ++++++ .../v3/templates/controller_base.tmpl | 27 + .../generators/v3/templates/helpers.go | 41 + .../generators/v3/templates/subscriber.tmpl | 7 + pkg/extensions/errors.go | 5 + .../issues/130/requestreply/asyncapi.gen.go | 5 +- test/v3/issues/140/asyncapi.gen.go | 269 +++++- test/v3/issues/186/asyncapi.gen.go | 5 +- test/v3/issues/333/asyncapi.gen.go | 789 ++++++++++++++++++ test/v3/issues/333/asyncapi.yaml | 48 ++ test/v3/issues/333/gen.go | 3 + test/v3/issues/333/suite_test.go | 221 +++++ 16 files changed, 1702 insertions(+), 53 deletions(-) create mode 100644 test/v3/issues/333/asyncapi.gen.go create mode 100644 test/v3/issues/333/asyncapi.yaml create mode 100644 test/v3/issues/333/gen.go create mode 100644 test/v3/issues/333/suite_test.go diff --git a/README.md b/README.md index d8027377..4cba2bba 100644 --- a/README.md +++ b/README.md @@ -916,8 +916,33 @@ operations: generates `SendAsSendEventsOperationForUserCreated` and `...ForUserDeleted`, each sending its own message type. Operations with a single -message are unchanged. Reception of multiple message types on a single channel -is not covered yet (the subscribe side still handles the first message only). +message are unchanged. + +On the **receive** side, a subscribe function is likewise generated per message, +named after the operation and the message, with one callback per message type: + +```yaml +operations: + receiveEvents: + action: receive + channel: { $ref: '#/channels/events' } +``` + +generates `SubscribeToReceiveEventsOperationForUserCreated(ctx, fn)` and +`...ForUserDeleted(ctx, fn)` (plus the matching `UnsubscribeFrom...For...` +functions and per-message methods on the subscriber interface). A single broker +subscription is opened per channel and multiplexed to the registered handlers. + +Each received message is discriminated with a **try-each-until-valid** strategy: +it is unmarshalled and validated against every expected message schema (using +[`go-playground/validator`](https://github.com/go-playground/validator), so this +dependency must be available in your module) and dispatched to the first one +that matches. This is heuristic and can be ambiguous when several message +schemas overlap — it works best when the messages have distinguishing required +or `enum`/`const` fields. A message that matches none of the expected types is +nacked and surfaced to the [error handler](#errorhandler) as +`extensions.ErrNoMatchingMessage`. Operations with a single message are +unchanged. ### Channel parameters from message location (AsyncAPI v3) diff --git a/pkg/codegen/generators/v3/common.go b/pkg/codegen/generators/v3/common.go index 42878b2b..1a3966b9 100644 --- a/pkg/codegen/generators/v3/common.go +++ b/pkg/codegen/generators/v3/common.go @@ -13,6 +13,19 @@ type ActionOperations struct { Send map[string]*asyncapi.Operation } +// HasMultiMessageReceive reports whether at least one receive operation carries +// more than one message, and therefore needs the multiplexed dispatcher +// machinery (issue #333). +func (ao ActionOperations) HasMultiMessageReceive() bool { + for _, op := range ao.Receive { + o := op.Follow() + if len(o.GetMessages()) > 1 && o.Reply == nil && o.ReplyOf == nil { + return true + } + } + return false +} + // NewActionOperations will create a struct with operations based on their action. func NewActionOperations(side generators.Side, spec asyncapi.Specification) ActionOperations { var ao ActionOperations diff --git a/pkg/codegen/generators/v3/controller_base.go b/pkg/codegen/generators/v3/controller_base.go index 5d01f520..41d7c4d6 100644 --- a/pkg/codegen/generators/v3/controller_base.go +++ b/pkg/codegen/generators/v3/controller_base.go @@ -8,17 +8,22 @@ import ( // internal controller struct and its options) used by both the application and // user controllers. It is generated once, only when a controller side is // generated, so that the `types` output stays free of controller boilerplate. -type ControllerBaseGenerator struct{} +type ControllerBaseGenerator struct { + // MultiMessageReceive is true when at least one generated controller side has + // a receive operation carrying several messages, which requires the + // multiplexed dispatcher machinery (issue #333). + MultiMessageReceive bool +} // Generate will generate the shared controller base code. -func (ControllerBaseGenerator) Generate() (string, error) { +func (g ControllerBaseGenerator) Generate() (string, error) { tmplt, err := loadTemplate(controllerBaseTemplatePath) if err != nil { return "", err } buf := new(bytes.Buffer) - if err := tmplt.Execute(buf, nil); err != nil { + if err := tmplt.Execute(buf, g); err != nil { return "", err } diff --git a/pkg/codegen/generators/v3/generator.go b/pkg/codegen/generators/v3/generator.go index 46adf653..e8205ef6 100644 --- a/pkg/codegen/generators/v3/generator.go +++ b/pkg/codegen/generators/v3/generator.go @@ -83,7 +83,29 @@ func (g Generator) generateControllerBase() (string, error) { return "", nil } - return ControllerBaseGenerator{}.Generate() + return ControllerBaseGenerator{ + MultiMessageReceive: g.hasMultiMessageReceive(), + }.Generate() +} + +// hasMultiMessageReceive reports whether any of the controller sides that will +// be generated has a receive operation carrying several messages (issue #333). +func (g Generator) hasMultiMessageReceive() bool { + sides := make([]generators.Side, 0, 2) + if g.Options.Generate.Application { + sides = append(sides, generators.SideIsApplication) + } + if g.Options.Generate.User { + sides = append(sides, generators.SideIsUser) + } + + for _, side := range sides { + if NewActionOperations(side, g.Specification).HasMultiMessageReceive() { + return true + } + } + + return false } func (g Generator) generateApp() (string, error) { diff --git a/pkg/codegen/generators/v3/templates/controller.tmpl b/pkg/codegen/generators/v3/templates/controller.tmpl index 7e275f2d..cb68499d 100644 --- a/pkg/codegen/generators/v3/templates/controller.tmpl +++ b/pkg/codegen/generators/v3/templates/controller.tmpl @@ -15,6 +15,9 @@ func New{{ .Prefix }}Controller(bc extensions.BrokerController, options ...Contr controller := controller{ broker: bc, subscriptions: make(map[string]extensions.BrokerChannelSubscription), + {{- if .Operations.HasMultiMessageReceive}} + dispatcher: &messageDispatcher{handlers: make(map[string]map[string]messageDispatchHandler)}, + {{- end}} logger: extensions.DummyLogger{}, middlewares: make([]extensions.Middleware, 0), errorHandler: extensions.DefaultErrorHandler(), @@ -112,11 +115,19 @@ func (c *{{ .Prefix }}Controller) SubscribeToAllChannels(ctx context.Context, as {{range $key, $value := .Operations.Receive -}} {{- if not .Channel.Follow.Parameters }} + {{- if isMultiMessageReceive $value }} + {{- range $msg := $value.GetMessages}} + if err := c.{{ subscribeFuncNameForMessage $value $msg }}(ctx, as.{{ receivedFuncNameForMessage $value $msg }}); err != nil { + return err + } + {{- end}} + {{- else}} if err := c.{{ subscribeFuncName $value }}(ctx, as.{{ receivedFuncName $value }}); err != nil { return err } {{- end}} {{- end}} + {{- end}} return nil } @@ -125,13 +136,259 @@ func (c *{{ .Prefix }}Controller) SubscribeToAllChannels(ctx context.Context, as func (c *{{ .Prefix }}Controller) UnsubscribeFromAllChannels(ctx context.Context) { {{- range $key, $value := .Operations.Receive}} {{- if not .Channel.Follow.Parameters}} + {{- if isMultiMessageReceive $value }} + {{- range $msg := $value.GetMessages}} + c.{{ unsubscribeFuncNameForMessage $value $msg }}(ctx) + {{- end}} + {{- else}} c.UnsubscribeFrom{{ namify $value.Follow.Name }}(ctx) {{- end}} {{- end}} + {{- end}} } {{- end}} {{range $key, $value := .Operations.Receive -}} +{{- if isMultiMessageReceive $value }} +{{- /* MULTI-MESSAGE RECEIVE (#333): generate one subscribe function per message. + A single broker subscription per channel is opened and multiplexed to the + registered per-message handlers, using try-each-until-valid discrimination + (unmarshal + validate) to dispatch each received message. */}} +{{- range $msg := $value.GetMessages}} +// {{ subscribeFuncNameForMessage $value $msg }} will receive {{ cutSuffix (messageTypeName $msg) "Message" }} messages from {{ cutSuffix (opToChannelTypeName $value) "Channel" }} channel. +// +// Callback function 'fn' will be called each time a {{ cutSuffix (messageTypeName $msg) "Message" }} message is received. +// +// NOTE: this channel carries several message types; a received message is only +// dispatched to this callback when it matches the {{ messageTypeName $msg }} schema. +func (c *{{ $.Prefix }}Controller) {{ subscribeFuncNameForMessage $value $msg }}( + ctx context.Context, + {{- if $value.Channel.Follow.Parameters}} + params {{namifyWithoutParam $value.Channel.Follow.Name}}Parameters, + {{- end}} + fn func (ctx context.Context, msg {{messageTypeName $msg}}) error, +) error { + // Get channel address + addr := {{ generateChannelAddrFromOp $value }} + + // Set context + ctx = add{{ $.Prefix }}ContextValues(ctx, addr) + ctx = context.WithValue(ctx, extensions.ContextKeyIsDirection, "reception") + + // Build the handler that discriminates {{messageTypeName $msg}} messages and + // dispatches them to the callback. + handler := func(hdlrCtx context.Context, bMsg extensions.BrokerMessage) (bool, error) { + // Try to convert the broker message to the expected type + msg, err := brokerMessageTo{{messageTypeName $msg}}(bMsg) + if err != nil { + return false, nil + } + + // Validate it against the message schema to discriminate it from the + // other message types received on this channel. + if err := validate.Struct(msg); err != nil { + return false, nil + } + + {{if $msg.HaveCorrelationID -}} + // Add correlation ID to context if it exists + if id := msg.CorrelationID(); id != "" { + hdlrCtx = context.WithValue(hdlrCtx, extensions.ContextKeyIsCorrelationID, id) + } + {{- end}} + + // Execute the subscription function + if err := fn(hdlrCtx, msg); err != nil { + return true, err + } + + return true, nil + } + + // Register the handler and subscribe to the channel if not done already + return c.subscribeTo{{ namify $value.Follow.Name }}(ctx, addr, "{{messageTypeName $msg}}", handler) +} + +// {{ unsubscribeFuncNameForMessage $value $msg }} will stop the reception of {{ cutSuffix (messageTypeName $msg) "Message" }} messages from {{ cutSuffix (opToChannelTypeName $value) "Channel" }} channel. +// The underlying broker subscription is canceled once the last message type on +// the channel is unsubscribed. +// A timeout can be set in context to avoid blocking operation, if needed. +func (c *{{ $.Prefix }}Controller) {{ unsubscribeFuncNameForMessage $value $msg }}( + ctx context.Context, + {{- if $value.Channel.Follow.Parameters}} + params {{namifyWithoutParam $value.Channel.Follow.Name}}Parameters, + {{- end}} +) { + // Get channel address + addr := {{ generateChannelAddrFromOp $value }} + + c.unsubscribeFrom{{ namify $value.Follow.Name }}(ctx, addr, "{{messageTypeName $msg}}") +} +{{- end}} + +// subscribeTo{{ namify $value.Follow.Name }} registers a per-message handler on the +// {{ cutSuffix (opToChannelTypeName $value) "Channel" }} channel and, on the first +// registration, opens a single broker subscription multiplexed to every +// registered handler (issue #333). +func (c *{{ $.Prefix }}Controller) subscribeTo{{ namify $value.Follow.Name }}( + ctx context.Context, + addr string, + msgName string, + handler messageDispatchHandler, +) error { + c.dispatcher.mutex.Lock() + defer c.dispatcher.mutex.Unlock() + + // If there are already handlers on this channel, just register this one: the + // existing broker subscription will dispatch to it. + if handlers, exists := c.dispatcher.handlers[addr]; exists { + if _, exists := handlers[msgName]; exists { + err := fmt.Errorf("%w: controller is already subscribed for message %q on channel %q", extensions.ErrAlreadySubscribedChannel, msgName, addr) + c.logger.Error(ctx, err.Error(), extensions.LogInfosFromContext(ctx)...) + return err + } + + handlers[msgName] = handler + c.logger.Info(ctx, "Subscribed to channel", extensions.LogInfosFromContext(ctx)...) + return nil + } + + // First registration on this channel: register the handler... + c.dispatcher.handlers[addr] = map[string]messageDispatchHandler{msgName: handler} + + // ...and subscribe to the broker channel. + sub, err := c.broker.Subscribe(ctx, addr) + if err != nil { + delete(c.dispatcher.handlers, addr) + c.logger.Error(ctx, err.Error(), extensions.LogInfosFromContext(ctx)...) + return err + } + c.subscriptions[addr] = sub + c.logger.Info(ctx, "Subscribed to channel", extensions.LogInfosFromContext(ctx)...) + + // Asynchronously listen to new messages and dispatch them to the matching + // registered handler. + go func() { + for { + // Listen to next message + stop, err := c.listenTo{{ namify $value.Follow.Name }}NextMessage(addr, sub) + if err != nil { + c.logger.Error(ctx, err.Error(), extensions.LogInfosFromContext(ctx)...) + } + + // Stop if required + if stop { + return + } + } + } () + + return nil +} + +func (c *{{ $.Prefix }}Controller) listenTo{{ namify $value.Follow.Name }}NextMessage( + addr string, + sub extensions.BrokerChannelSubscription, +) (stop bool, err error) { + // Create a context for the received response + msgCtx, cancel := context.WithCancel(context.Background()) + msgCtx = add{{ $.Prefix }}ContextValues(msgCtx, addr) + msgCtx = context.WithValue(msgCtx, extensions.ContextKeyIsDirection, "reception") + defer cancel() + + // Wait for next message + acknowledgeableBrokerMessage, open := <-sub.MessagesChannel() + + // If subscription is closed and there is no more message + // (i.e. uninitialized message), then exit the function + if !open && acknowledgeableBrokerMessage.IsUninitialized() { + return true, nil + } + + // Set broker message to context + msgCtx = context.WithValue(msgCtx, extensions.ContextKeyIsBrokerMessage, acknowledgeableBrokerMessage.String()) + + // Execute middlewares before handling the message + if err := c.executeMiddlewares(msgCtx, &acknowledgeableBrokerMessage.BrokerMessage, func(middlewareCtx context.Context) error { + // Snapshot the registered message names in a deterministic order + c.dispatcher.mutex.Lock() + handlers := c.dispatcher.handlers[addr] + msgNames := make([]string, 0, len(handlers)) + for msgName := range handlers { + msgNames = append(msgNames, msgName) + } + c.dispatcher.mutex.Unlock() + sort.Strings(msgNames) + + // Try each registered handler until one matches the received message + for _, msgName := range msgNames { + c.dispatcher.mutex.Lock() + handler := c.dispatcher.handlers[addr][msgName] + c.dispatcher.mutex.Unlock() + if handler == nil { + continue + } + + handled, err := handler(middlewareCtx, acknowledgeableBrokerMessage.BrokerMessage) + if err != nil { + return err + } + if handled { + acknowledgeableBrokerMessage.Ack() + return nil + } + } + + // No registered handler matched the received message + return extensions.ErrNoMatchingMessage + }); err != nil { + c.errorHandler(msgCtx, addr, &acknowledgeableBrokerMessage, err) + // On error execute the acknowledgeableBrokerMessage nack() function and + // let the BrokerAcknowledgment decide what is the right nack behavior for the broker + acknowledgeableBrokerMessage.Nak() + } + + return false, nil +} + +func (c *{{ $.Prefix }}Controller) unsubscribeFrom{{ namify $value.Follow.Name }}( + ctx context.Context, + addr string, + msgName string, +) { + c.dispatcher.mutex.Lock() + defer c.dispatcher.mutex.Unlock() + + // Check if there are handlers for this channel + handlers, exists := c.dispatcher.handlers[addr] + if !exists { + return + } + + // Check if this message type is subscribed + if _, exists := handlers[msgName]; !exists { + return + } + + // Remove the handler for this message type + delete(handlers, msgName) + + // Set context + ctx = add{{ $.Prefix }}ContextValues(ctx, addr) + + // If there are no more handlers on this channel, cancel the broker subscription + if len(handlers) == 0 { + delete(c.dispatcher.handlers, addr) + + if sub, exists := c.subscriptions[addr]; exists { + sub.Cancel(ctx) + delete(c.subscriptions, addr) + } + } + + c.logger.Info(ctx, "Unsubscribed from channel", extensions.LogInfosFromContext(ctx)...) +} +{{- else}} // {{ subscribeFuncName $value }} will receive {{ cutSuffix (opToMsgTypeName $value) "Message" }} messages from {{ cutSuffix (opToChannelTypeName $value) "Channel" }} channel. // // Callback function 'fn' will be called each time a new message is received. @@ -310,6 +567,7 @@ func (c *{{ $.Prefix }}Controller) UnsubscribeFrom{{ namify $value.Follow.Name } c.logger.Info(ctx, "Unsubscribed from channel", extensions.LogInfosFromContext(ctx)...) } {{- end}} +{{- end}} {{- range $key, $value := .Operations.Send}} {{- if and (gt (operationMessageCount $value) 1) (not .Reply) (not .ReplyOf)}} diff --git a/pkg/codegen/generators/v3/templates/controller_base.tmpl b/pkg/codegen/generators/v3/templates/controller_base.tmpl index 475e607c..8010c3ef 100644 --- a/pkg/codegen/generators/v3/templates/controller_base.tmpl +++ b/pkg/codegen/generators/v3/templates/controller_base.tmpl @@ -1,3 +1,25 @@ +{{if .MultiMessageReceive -}} +// validate is the validator used to discriminate between the several message +// types that can be received on a single channel (issue #333). +var validate = validator.New() + +// messageDispatchHandler tries to convert and validate a raw broker message +// against a single expected message type and, when it matches, dispatches it to +// the registered callback. It returns true when the message matched the type. +type messageDispatchHandler func(ctx context.Context, bMsg extensions.BrokerMessage) (handled bool, err error) + +// messageDispatcher holds, per channel address, the per-message handlers +// registered by multi-message receive subscriptions and multiplexes a single +// broker subscription to them (issue #333). It is held by pointer on the +// controller so the controller stays safe to copy by value. +type messageDispatcher struct { + // mutex protects concurrent access to handlers. + mutex sync.Mutex + // handlers maps a channel address to the per-message handlers registered on it. + handlers map[string]map[string]messageDispatchHandler +} +{{end -}} + // controller is the controller that will be used to communicate with the broker // It will be used internally by AppController and UserController type controller struct { @@ -5,6 +27,11 @@ type controller struct { broker extensions.BrokerController // subscriptions is a map of all subscriptions subscriptions map[string]extensions.BrokerChannelSubscription + {{- if .MultiMessageReceive}} + // dispatcher multiplexes broker messages to the per-message handlers + // registered by multi-message receive subscriptions (issue #333). + dispatcher *messageDispatcher + {{- end}} // logger is the logger that will be used to log operations on controller logger extensions.Logger // middlewares are the middlewares that will be executed when sending or diff --git a/pkg/codegen/generators/v3/templates/helpers.go b/pkg/codegen/generators/v3/templates/helpers.go index 8c6f93c8..e5742aa3 100644 --- a/pkg/codegen/generators/v3/templates/helpers.go +++ b/pkg/codegen/generators/v3/templates/helpers.go @@ -209,6 +209,43 @@ func SendFuncNameForMessage(op *asyncapi.Operation, prefix string, msg *asyncapi return SendFuncName(op, prefix) + "For" + base } +// messageNameBase returns the message type name without its "Message" suffix, +// used to build per-message function names. +func messageNameBase(msg *asyncapi.Message) string { + return strings.TrimSuffix(MessageTypeName(msg), "Message") +} + +// SubscribeFuncNameForMessage returns the name of the per-message subscribe +// function generated when a receive operation carries more than one message +// (issue #333). It is the operation subscribe function name suffixed with "For" +// and the message name. +func SubscribeFuncNameForMessage(op *asyncapi.Operation, msg *asyncapi.Message) string { + return SubscribeFuncName(op) + "For" + messageNameBase(msg) +} + +// UnsubscribeFuncNameForMessage returns the name of the per-message unsubscribe +// function generated when a receive operation carries more than one message +// (issue #333). +func UnsubscribeFuncNameForMessage(op *asyncapi.Operation, msg *asyncapi.Message) string { + return "UnsubscribeFrom" + templateutil.Namify(op.Follow().Name) + "For" + messageNameBase(msg) +} + +// ReceivedFuncNameForMessage returns the name of the per-message subscriber +// callback generated when a receive operation carries more than one message +// (issue #333). +func ReceivedFuncNameForMessage(op *asyncapi.Operation, msg *asyncapi.Message) string { + return templateutil.Namify(op.Follow().Name) + "For" + messageNameBase(msg) + "Received" +} + +// IsMultiMessageReceive reports whether the given receive operation carries more +// than one message and therefore needs per-message subscribe functions and +// try-each-until-valid dispatch (issue #333). Reply and reply-target operations +// are excluded as the request/reply path is handled separately. +func IsMultiMessageReceive(op *asyncapi.Operation) bool { + o := op.Follow() + return len(o.GetMessages()) > 1 && o.Reply == nil && o.ReplyOf == nil +} + // HelpersFunctions returns the functions that can be used as helpers // in a golang template. func HelpersFunctions() template.FuncMap { @@ -234,5 +271,9 @@ func HelpersFunctions() template.FuncMap { "operationMessageCount": OperationMessageCount, "messageTypeName": MessageTypeName, "sendFuncNameForMessage": SendFuncNameForMessage, + "subscribeFuncNameForMessage": SubscribeFuncNameForMessage, + "unsubscribeFuncNameForMessage": UnsubscribeFuncNameForMessage, + "receivedFuncNameForMessage": ReceivedFuncNameForMessage, + "isMultiMessageReceive": IsMultiMessageReceive, } } diff --git a/pkg/codegen/generators/v3/templates/subscriber.tmpl b/pkg/codegen/generators/v3/templates/subscriber.tmpl index ca06f030..f35b6c8a 100644 --- a/pkg/codegen/generators/v3/templates/subscriber.tmpl +++ b/pkg/codegen/generators/v3/templates/subscriber.tmpl @@ -2,8 +2,15 @@ // {{ .Prefix }}Subscriber contains all handlers that are listening messages for {{ .Prefix }} type {{ .Prefix }}Subscriber interface { {{- range $key, $value := .Operations.Receive}} +{{- if isMultiMessageReceive $value }} +{{- range $msg := $value.GetMessages}} + // {{ receivedFuncNameForMessage $value $msg }} receive all {{ cutSuffix (messageTypeName $msg) "Message" }} messages from {{ cutSuffix (opToChannelTypeName $value) "Channel" }} channel. + {{ receivedFuncNameForMessage $value $msg }}(ctx context.Context, msg {{messageTypeName $msg}}) error +{{end}} +{{- else}} // {{ receivedFuncName $value }} receive all {{ cutSuffix (opToMsgTypeName $value) "Message" }} messages from {{ cutSuffix (opToChannelTypeName $value) "Channel" }} channel. {{ receivedFuncName $value }}(ctx context.Context, msg {{opToMsgTypeName $value}}) error {{end}} +{{- end}} } {{- end}} diff --git a/pkg/extensions/errors.go b/pkg/extensions/errors.go index af978109..6270e9c0 100644 --- a/pkg/extensions/errors.go +++ b/pkg/extensions/errors.go @@ -34,4 +34,9 @@ var ( // ErrChannelAddressEmpty is raised when a given channel address is empty, // when dynamically set from message. ErrChannelAddressEmpty = fmt.Errorf("%w: channel address empty", ErrAsyncAPI) + + // ErrNoMatchingMessage is raised when a message received on a channel that + // carries several message types does not match any of the expected types, + // i.e. it could not be unmarshalled and validated against any of them. + ErrNoMatchingMessage = fmt.Errorf("%w: no expected message type matched the received message", ErrAsyncAPI) ) diff --git a/test/v3/issues/130/requestreply/asyncapi.gen.go b/test/v3/issues/130/requestreply/asyncapi.gen.go index fc974565..c66de364 100644 --- a/test/v3/issues/130/requestreply/asyncapi.gen.go +++ b/test/v3/issues/130/requestreply/asyncapi.gen.go @@ -331,7 +331,10 @@ func (c *AppController) UnsubscribeFromPingOperation( delete(c.subscriptions, addr) c.logger.Info(ctx, "Unsubscribed from channel", extensions.LogInfosFromContext(ctx)...) -} // SubscribeToPingWithIDOperation will receive PingWithID messages from PingWithID channel. +} + +// SubscribeToPingWithIDOperation will receive PingWithID messages from PingWithID channel. +// // Callback function 'fn' will be called each time a new message is received. // // NOTE: for now, this only support the first message from AsyncAPI list. diff --git a/test/v3/issues/140/asyncapi.gen.go b/test/v3/issues/140/asyncapi.gen.go index 5aea878c..fda25c42 100644 --- a/test/v3/issues/140/asyncapi.gen.go +++ b/test/v3/issues/140/asyncapi.gen.go @@ -7,10 +7,33 @@ import ( "context" "encoding/json" "fmt" + "sort" + "sync" + "github.com/go-playground/validator/v10" "github.com/lerenn/asyncapi-codegen/pkg/extensions" ) +// validate is the validator used to discriminate between the several message +// types that can be received on a single channel (issue #333). +var validate = validator.New() + +// messageDispatchHandler tries to convert and validate a raw broker message +// against a single expected message type and, when it matches, dispatches it to +// the registered callback. It returns true when the message matched the type. +type messageDispatchHandler func(ctx context.Context, bMsg extensions.BrokerMessage) (handled bool, err error) + +// messageDispatcher holds, per channel address, the per-message handlers +// registered by multi-message receive subscriptions and multiplexes a single +// broker subscription to them (issue #333). It is held by pointer on the +// controller so the controller stays safe to copy by value. +type messageDispatcher struct { + // mutex protects concurrent access to handlers. + mutex sync.Mutex + // handlers maps a channel address to the per-message handlers registered on it. + handlers map[string]map[string]messageDispatchHandler +} + // controller is the controller that will be used to communicate with the broker // It will be used internally by AppController and UserController type controller struct { @@ -18,6 +41,9 @@ type controller struct { broker extensions.BrokerController // subscriptions is a map of all subscriptions subscriptions map[string]extensions.BrokerChannelSubscription + // dispatcher multiplexes broker messages to the per-message handlers + // registered by multi-message receive subscriptions (issue #333). + dispatcher *messageDispatcher // logger is the logger that will be used to log operations on controller logger extensions.Logger // middlewares are the middlewares that will be executed when sending or @@ -206,8 +232,11 @@ func (c *AppController) SendAsSendEventsOperationForUserDeleted( // UserSubscriber contains all handlers that are listening messages for User type UserSubscriber interface { - // SendEventsOperationReceived receive all UserCreated messages from Events channel. - SendEventsOperationReceived(ctx context.Context, msg UserCreatedMessage) error + // SendEventsOperationForUserCreatedReceived receive all UserCreated messages from Events channel. + SendEventsOperationForUserCreatedReceived(ctx context.Context, msg UserCreatedMessage) error + + // SendEventsOperationForUserDeletedReceived receive all UserDeleted messages from Events channel. + SendEventsOperationForUserDeletedReceived(ctx context.Context, msg UserDeletedMessage) error } // UserController is the structure that provides sending capabilities to the @@ -227,6 +256,7 @@ func NewUserController(bc extensions.BrokerController, options ...ControllerOpti controller := controller{ broker: bc, subscriptions: make(map[string]extensions.BrokerChannelSubscription), + dispatcher: &messageDispatcher{handlers: make(map[string]map[string]messageDispatchHandler)}, logger: extensions.DummyLogger{}, middlewares: make([]extensions.Middleware, 0), errorHandler: extensions.DefaultErrorHandler(), @@ -319,7 +349,10 @@ func (c *UserController) SubscribeToAllChannels(ctx context.Context, as UserSubs return extensions.ErrNilUserSubscriber } - if err := c.SubscribeToSendEventsOperation(ctx, as.SendEventsOperationReceived); err != nil { + if err := c.SubscribeToSendEventsOperationForUserCreated(ctx, as.SendEventsOperationForUserCreatedReceived); err != nil { + return err + } + if err := c.SubscribeToSendEventsOperationForUserDeleted(ctx, as.SendEventsOperationForUserDeletedReceived); err != nil { return err } @@ -328,18 +361,17 @@ func (c *UserController) SubscribeToAllChannels(ctx context.Context, as UserSubs // UnsubscribeFromAllChannels will stop the subscription of all remaining subscribed channels func (c *UserController) UnsubscribeFromAllChannels(ctx context.Context) { - c.UnsubscribeFromSendEventsOperation(ctx) + c.UnsubscribeFromSendEventsOperationForUserCreated(ctx) + c.UnsubscribeFromSendEventsOperationForUserDeleted(ctx) } -// SubscribeToSendEventsOperation will receive UserCreated messages from Events channel. -// -// Callback function 'fn' will be called each time a new message is received. +// SubscribeToSendEventsOperationForUserCreated will receive UserCreated messages from Events channel. // -// NOTE: for now, this only support the first message from AsyncAPI list. +// Callback function 'fn' will be called each time a UserCreated message is received. // -// NOTE: for now, this only support the first message from AsyncAPI list. -// If you need support for other messages, please raise an issue. -func (c *UserController) SubscribeToSendEventsOperation( +// NOTE: this channel carries several message types; a received message is only +// dispatched to this callback when it matches the UserCreatedMessage schema. +func (c *UserController) SubscribeToSendEventsOperationForUserCreated( ctx context.Context, fn func(ctx context.Context, msg UserCreatedMessage) error, ) error { @@ -350,27 +382,149 @@ func (c *UserController) SubscribeToSendEventsOperation( ctx = addUserContextValues(ctx, addr) ctx = context.WithValue(ctx, extensions.ContextKeyIsDirection, "reception") - // Check if the controller is already subscribed - _, exists := c.subscriptions[addr] - if exists { - err := fmt.Errorf("%w: controller is already subscribed on channel %q", extensions.ErrAlreadySubscribedChannel, addr) - c.logger.Error(ctx, err.Error(), extensions.LogInfosFromContext(ctx)...) - return err + // Build the handler that discriminates UserCreatedMessage messages and + // dispatches them to the callback. + handler := func(hdlrCtx context.Context, bMsg extensions.BrokerMessage) (bool, error) { + // Try to convert the broker message to the expected type + msg, err := brokerMessageToUserCreatedMessage(bMsg) + if err != nil { + return false, nil + } + + // Validate it against the message schema to discriminate it from the + // other message types received on this channel. + if err := validate.Struct(msg); err != nil { + return false, nil + } + + // Execute the subscription function + if err := fn(hdlrCtx, msg); err != nil { + return true, err + } + + return true, nil + } + + // Register the handler and subscribe to the channel if not done already + return c.subscribeToSendEventsOperation(ctx, addr, "UserCreatedMessage", handler) +} + +// UnsubscribeFromSendEventsOperationForUserCreated will stop the reception of UserCreated messages from Events channel. +// The underlying broker subscription is canceled once the last message type on +// the channel is unsubscribed. +// A timeout can be set in context to avoid blocking operation, if needed. +func (c *UserController) UnsubscribeFromSendEventsOperationForUserCreated( + ctx context.Context, +) { + // Get channel address + addr := "v3.issue140.events" + + c.unsubscribeFromSendEventsOperation(ctx, addr, "UserCreatedMessage") +} + +// SubscribeToSendEventsOperationForUserDeleted will receive UserDeleted messages from Events channel. +// +// Callback function 'fn' will be called each time a UserDeleted message is received. +// +// NOTE: this channel carries several message types; a received message is only +// dispatched to this callback when it matches the UserDeletedMessage schema. +func (c *UserController) SubscribeToSendEventsOperationForUserDeleted( + ctx context.Context, + fn func(ctx context.Context, msg UserDeletedMessage) error, +) error { + // Get channel address + addr := "v3.issue140.events" + + // Set context + ctx = addUserContextValues(ctx, addr) + ctx = context.WithValue(ctx, extensions.ContextKeyIsDirection, "reception") + + // Build the handler that discriminates UserDeletedMessage messages and + // dispatches them to the callback. + handler := func(hdlrCtx context.Context, bMsg extensions.BrokerMessage) (bool, error) { + // Try to convert the broker message to the expected type + msg, err := brokerMessageToUserDeletedMessage(bMsg) + if err != nil { + return false, nil + } + + // Validate it against the message schema to discriminate it from the + // other message types received on this channel. + if err := validate.Struct(msg); err != nil { + return false, nil + } + + // Execute the subscription function + if err := fn(hdlrCtx, msg); err != nil { + return true, err + } + + return true, nil + } + + // Register the handler and subscribe to the channel if not done already + return c.subscribeToSendEventsOperation(ctx, addr, "UserDeletedMessage", handler) +} + +// UnsubscribeFromSendEventsOperationForUserDeleted will stop the reception of UserDeleted messages from Events channel. +// The underlying broker subscription is canceled once the last message type on +// the channel is unsubscribed. +// A timeout can be set in context to avoid blocking operation, if needed. +func (c *UserController) UnsubscribeFromSendEventsOperationForUserDeleted( + ctx context.Context, +) { + // Get channel address + addr := "v3.issue140.events" + + c.unsubscribeFromSendEventsOperation(ctx, addr, "UserDeletedMessage") +} + +// subscribeToSendEventsOperation registers a per-message handler on the +// Events channel and, on the first +// registration, opens a single broker subscription multiplexed to every +// registered handler (issue #333). +func (c *UserController) subscribeToSendEventsOperation( + ctx context.Context, + addr string, + msgName string, + handler messageDispatchHandler, +) error { + c.dispatcher.mutex.Lock() + defer c.dispatcher.mutex.Unlock() + + // If there are already handlers on this channel, just register this one: the + // existing broker subscription will dispatch to it. + if handlers, exists := c.dispatcher.handlers[addr]; exists { + if _, exists := handlers[msgName]; exists { + err := fmt.Errorf("%w: controller is already subscribed for message %q on channel %q", extensions.ErrAlreadySubscribedChannel, msgName, addr) + c.logger.Error(ctx, err.Error(), extensions.LogInfosFromContext(ctx)...) + return err + } + + handlers[msgName] = handler + c.logger.Info(ctx, "Subscribed to channel", extensions.LogInfosFromContext(ctx)...) + return nil } - // Subscribe to broker channel + // First registration on this channel: register the handler... + c.dispatcher.handlers[addr] = map[string]messageDispatchHandler{msgName: handler} + + // ...and subscribe to the broker channel. sub, err := c.broker.Subscribe(ctx, addr) if err != nil { + delete(c.dispatcher.handlers, addr) c.logger.Error(ctx, err.Error(), extensions.LogInfosFromContext(ctx)...) return err } + c.subscriptions[addr] = sub c.logger.Info(ctx, "Subscribed to channel", extensions.LogInfosFromContext(ctx)...) - // Asynchronously listen to new messages and pass them to app receiver + // Asynchronously listen to new messages and dispatch them to the matching + // registered handler. go func() { for { // Listen to next message - stop, err := c.listenToSendEventsOperationNextMessage(addr, sub, fn) + stop, err := c.listenToSendEventsOperationNextMessage(addr, sub) if err != nil { c.logger.Error(ctx, err.Error(), extensions.LogInfosFromContext(ctx)...) } @@ -382,16 +536,12 @@ func (c *UserController) SubscribeToSendEventsOperation( } }() - // Add the cancel channel to the inside map - c.subscriptions[addr] = sub - return nil } func (c *UserController) listenToSendEventsOperationNextMessage( addr string, sub extensions.BrokerChannelSubscription, - fn func(ctx context.Context, msg UserCreatedMessage) error, ) (stop bool, err error) { // Create a context for the received response msgCtx, cancel := context.WithCancel(context.Background()) @@ -413,20 +563,37 @@ func (c *UserController) listenToSendEventsOperationNextMessage( // Execute middlewares before handling the message if err := c.executeMiddlewares(msgCtx, &acknowledgeableBrokerMessage.BrokerMessage, func(middlewareCtx context.Context) error { - // Process message - msg, err := brokerMessageToUserCreatedMessage(acknowledgeableBrokerMessage.BrokerMessage) - if err != nil { - return err + // Snapshot the registered message names in a deterministic order + c.dispatcher.mutex.Lock() + handlers := c.dispatcher.handlers[addr] + msgNames := make([]string, 0, len(handlers)) + for msgName := range handlers { + msgNames = append(msgNames, msgName) } + c.dispatcher.mutex.Unlock() + sort.Strings(msgNames) + + // Try each registered handler until one matches the received message + for _, msgName := range msgNames { + c.dispatcher.mutex.Lock() + handler := c.dispatcher.handlers[addr][msgName] + c.dispatcher.mutex.Unlock() + if handler == nil { + continue + } - // Execute the subscription function - if err := fn(middlewareCtx, msg); err != nil { - return err + handled, err := handler(middlewareCtx, acknowledgeableBrokerMessage.BrokerMessage) + if err != nil { + return err + } + if handled { + acknowledgeableBrokerMessage.Ack() + return nil + } } - acknowledgeableBrokerMessage.Ack() - - return nil + // No registered handler matched the received message + return extensions.ErrNoMatchingMessage }); err != nil { c.errorHandler(msgCtx, addr, &acknowledgeableBrokerMessage, err) // On error execute the acknowledgeableBrokerMessage nack() function and @@ -437,28 +604,40 @@ func (c *UserController) listenToSendEventsOperationNextMessage( return false, nil } -// UnsubscribeFromSendEventsOperation will stop the reception of UserCreated messages from Events channel. -// A timeout can be set in context to avoid blocking operation, if needed. -func (c *UserController) UnsubscribeFromSendEventsOperation( +func (c *UserController) unsubscribeFromSendEventsOperation( ctx context.Context, + addr string, + msgName string, ) { - // Get channel address - addr := "v3.issue140.events" + c.dispatcher.mutex.Lock() + defer c.dispatcher.mutex.Unlock() - // Check if there receivers for this channel - sub, exists := c.subscriptions[addr] + // Check if there are handlers for this channel + handlers, exists := c.dispatcher.handlers[addr] if !exists { return } + // Check if this message type is subscribed + if _, exists := handlers[msgName]; !exists { + return + } + + // Remove the handler for this message type + delete(handlers, msgName) + // Set context ctx = addUserContextValues(ctx, addr) - // Stop the subscription - sub.Cancel(ctx) + // If there are no more handlers on this channel, cancel the broker subscription + if len(handlers) == 0 { + delete(c.dispatcher.handlers, addr) - // Remove if from the receivers - delete(c.subscriptions, addr) + if sub, exists := c.subscriptions[addr]; exists { + sub.Cancel(ctx) + delete(c.subscriptions, addr) + } + } c.logger.Info(ctx, "Unsubscribed from channel", extensions.LogInfosFromContext(ctx)...) } diff --git a/test/v3/issues/186/asyncapi.gen.go b/test/v3/issues/186/asyncapi.gen.go index 3b97ea6a..b5a59169 100644 --- a/test/v3/issues/186/asyncapi.gen.go +++ b/test/v3/issues/186/asyncapi.gen.go @@ -315,7 +315,10 @@ func (c *AppController) UnsubscribeFromAngleRequestOperation( delete(c.subscriptions, addr) c.logger.Info(ctx, "Unsubscribed from channel", extensions.LogInfosFromContext(ctx)...) -} // SubscribeToStarRequestOperation will receive Star messages from Star channel. +} + +// SubscribeToStarRequestOperation will receive Star messages from Star channel. +// // Callback function 'fn' will be called each time a new message is received. // // NOTE: for now, this only support the first message from AsyncAPI list. diff --git a/test/v3/issues/333/asyncapi.gen.go b/test/v3/issues/333/asyncapi.gen.go new file mode 100644 index 00000000..66cb30bc --- /dev/null +++ b/test/v3/issues/333/asyncapi.gen.go @@ -0,0 +1,789 @@ +// Package "issue333" provides primitives to interact with the AsyncAPI specification. +// +// Code generated by github.com/lerenn/asyncapi-codegen version (devel) DO NOT EDIT. +package issue333 + +import ( + "context" + "encoding/json" + "fmt" + "sort" + "sync" + + "github.com/go-playground/validator/v10" + "github.com/lerenn/asyncapi-codegen/pkg/extensions" +) + +// validate is the validator used to discriminate between the several message +// types that can be received on a single channel (issue #333). +var validate = validator.New() + +// messageDispatchHandler tries to convert and validate a raw broker message +// against a single expected message type and, when it matches, dispatches it to +// the registered callback. It returns true when the message matched the type. +type messageDispatchHandler func(ctx context.Context, bMsg extensions.BrokerMessage) (handled bool, err error) + +// messageDispatcher holds, per channel address, the per-message handlers +// registered by multi-message receive subscriptions and multiplexes a single +// broker subscription to them (issue #333). It is held by pointer on the +// controller so the controller stays safe to copy by value. +type messageDispatcher struct { + // mutex protects concurrent access to handlers. + mutex sync.Mutex + // handlers maps a channel address to the per-message handlers registered on it. + handlers map[string]map[string]messageDispatchHandler +} + +// controller is the controller that will be used to communicate with the broker +// It will be used internally by AppController and UserController +type controller struct { + // broker is the broker controller that will be used to communicate + broker extensions.BrokerController + // subscriptions is a map of all subscriptions + subscriptions map[string]extensions.BrokerChannelSubscription + // dispatcher multiplexes broker messages to the per-message handlers + // registered by multi-message receive subscriptions (issue #333). + dispatcher *messageDispatcher + // logger is the logger that will be used to log operations on controller + logger extensions.Logger + // middlewares are the middlewares that will be executed when sending or + // receiving messages + middlewares []extensions.Middleware + // handler to handle errors from consumers and middlewares + errorHandler extensions.ErrorHandler +} + +// ControllerOption is the type of the options that can be passed +// when creating a new Controller +type ControllerOption func(controller *controller) + +// WithLogger attaches a logger to the controller +func WithLogger(logger extensions.Logger) ControllerOption { + return func(controller *controller) { + controller.logger = logger + } +} + +// WithMiddlewares attaches middlewares that will be executed when sending or receiving messages +func WithMiddlewares(middlewares ...extensions.Middleware) ControllerOption { + return func(controller *controller) { + controller.middlewares = middlewares + } +} + +// WithErrorHandler attaches a errorhandler to handle errors from subscriber functions +func WithErrorHandler(handler extensions.ErrorHandler) ControllerOption { + return func(controller *controller) { + controller.errorHandler = handler + } +} + +// AppSubscriber contains all handlers that are listening messages for App +type AppSubscriber interface { + // ReceiveEventsOperationForUserDeletedReceived receive all UserDeleted messages from Events channel. + ReceiveEventsOperationForUserDeletedReceived(ctx context.Context, msg UserDeletedMessage) error + + // ReceiveEventsOperationForUserSignedUpReceived receive all UserSignedUp messages from Events channel. + ReceiveEventsOperationForUserSignedUpReceived(ctx context.Context, msg UserSignedUpMessage) error +} + +// AppController is the structure that provides sending capabilities to the +// developer and and connect the broker with the App +type AppController struct { + controller +} + +// NewAppController links the App to the broker +func NewAppController(bc extensions.BrokerController, options ...ControllerOption) (*AppController, error) { + // Check if broker controller has been provided + if bc == nil { + return nil, extensions.ErrNilBrokerController + } + + // Create default controller + controller := controller{ + broker: bc, + subscriptions: make(map[string]extensions.BrokerChannelSubscription), + dispatcher: &messageDispatcher{handlers: make(map[string]map[string]messageDispatchHandler)}, + logger: extensions.DummyLogger{}, + middlewares: make([]extensions.Middleware, 0), + errorHandler: extensions.DefaultErrorHandler(), + } + + // Apply options + for _, option := range options { + option(&controller) + } + + return &AppController{controller: controller}, nil +} + +func (c AppController) wrapMiddlewares( + middlewares []extensions.Middleware, + callback extensions.NextMiddleware, +) func(ctx context.Context, msg *extensions.BrokerMessage) error { + var called bool + + // If there is no more middleware + if len(middlewares) == 0 { + return func(ctx context.Context, msg *extensions.BrokerMessage) error { + // Call the callback if it exists and it has not been called already + if callback != nil && !called { + called = true + return callback(ctx) + } + + // Nil can be returned, as the callback has already been called + return nil + } + } + + // Get the next function to call from next middlewares or callback + next := c.wrapMiddlewares(middlewares[1:], callback) + + // Wrap middleware into a check function that will call execute the middleware + // and call the next wrapped middleware if the returned function has not been + // called already + return func(ctx context.Context, msg *extensions.BrokerMessage) error { + // Call the middleware and the following if it has not been done already + if !called { + // Create the next call with the context and the message + nextWithArgs := func(ctx context.Context) error { + return next(ctx, msg) + } + + // Call the middleware and register it as already called + called = true + if err := middlewares[0](ctx, msg, nextWithArgs); err != nil { + return err + } + + // If next has already been called in middleware, it should not be executed again + return nextWithArgs(ctx) + } + + // Nil can be returned, as the next middleware has already been called + return nil + } +} + +func (c AppController) executeMiddlewares(ctx context.Context, msg *extensions.BrokerMessage, callback extensions.NextMiddleware) error { + // Wrap middleware to have 'next' function when calling them + wrapped := c.wrapMiddlewares(c.middlewares, callback) + + // Execute wrapped middlewares + return wrapped(ctx, msg) +} + +func addAppContextValues(ctx context.Context, addr string) context.Context { + ctx = context.WithValue(ctx, extensions.ContextKeyIsVersion, "1.0.0") + ctx = context.WithValue(ctx, extensions.ContextKeyIsProvider, "app") + return context.WithValue(ctx, extensions.ContextKeyIsChannel, addr) +} + +// Close will clean up any existing resources on the controller +func (c *AppController) Close(ctx context.Context) { + // Unsubscribing remaining channels + c.UnsubscribeFromAllChannels(ctx) + + c.logger.Info(ctx, "Closed app controller", extensions.LogInfosFromContext(ctx)...) +} + +// SubscribeToAllChannels will receive messages from channels where channel has +// no parameter on which the app is expecting messages. For channels with parameters, +// they should be subscribed independently. +func (c *AppController) SubscribeToAllChannels(ctx context.Context, as AppSubscriber) error { + if as == nil { + return extensions.ErrNilAppSubscriber + } + + if err := c.SubscribeToReceiveEventsOperationForUserDeleted(ctx, as.ReceiveEventsOperationForUserDeletedReceived); err != nil { + return err + } + if err := c.SubscribeToReceiveEventsOperationForUserSignedUp(ctx, as.ReceiveEventsOperationForUserSignedUpReceived); err != nil { + return err + } + + return nil +} + +// UnsubscribeFromAllChannels will stop the subscription of all remaining subscribed channels +func (c *AppController) UnsubscribeFromAllChannels(ctx context.Context) { + c.UnsubscribeFromReceiveEventsOperationForUserDeleted(ctx) + c.UnsubscribeFromReceiveEventsOperationForUserSignedUp(ctx) +} + +// SubscribeToReceiveEventsOperationForUserDeleted will receive UserDeleted messages from Events channel. +// +// Callback function 'fn' will be called each time a UserDeleted message is received. +// +// NOTE: this channel carries several message types; a received message is only +// dispatched to this callback when it matches the UserDeletedMessage schema. +func (c *AppController) SubscribeToReceiveEventsOperationForUserDeleted( + ctx context.Context, + fn func(ctx context.Context, msg UserDeletedMessage) error, +) error { + // Get channel address + addr := "v3.issue333.events" + + // Set context + ctx = addAppContextValues(ctx, addr) + ctx = context.WithValue(ctx, extensions.ContextKeyIsDirection, "reception") + + // Build the handler that discriminates UserDeletedMessage messages and + // dispatches them to the callback. + handler := func(hdlrCtx context.Context, bMsg extensions.BrokerMessage) (bool, error) { + // Try to convert the broker message to the expected type + msg, err := brokerMessageToUserDeletedMessage(bMsg) + if err != nil { + return false, nil + } + + // Validate it against the message schema to discriminate it from the + // other message types received on this channel. + if err := validate.Struct(msg); err != nil { + return false, nil + } + + // Execute the subscription function + if err := fn(hdlrCtx, msg); err != nil { + return true, err + } + + return true, nil + } + + // Register the handler and subscribe to the channel if not done already + return c.subscribeToReceiveEventsOperation(ctx, addr, "UserDeletedMessage", handler) +} + +// UnsubscribeFromReceiveEventsOperationForUserDeleted will stop the reception of UserDeleted messages from Events channel. +// The underlying broker subscription is canceled once the last message type on +// the channel is unsubscribed. +// A timeout can be set in context to avoid blocking operation, if needed. +func (c *AppController) UnsubscribeFromReceiveEventsOperationForUserDeleted( + ctx context.Context, +) { + // Get channel address + addr := "v3.issue333.events" + + c.unsubscribeFromReceiveEventsOperation(ctx, addr, "UserDeletedMessage") +} + +// SubscribeToReceiveEventsOperationForUserSignedUp will receive UserSignedUp messages from Events channel. +// +// Callback function 'fn' will be called each time a UserSignedUp message is received. +// +// NOTE: this channel carries several message types; a received message is only +// dispatched to this callback when it matches the UserSignedUpMessage schema. +func (c *AppController) SubscribeToReceiveEventsOperationForUserSignedUp( + ctx context.Context, + fn func(ctx context.Context, msg UserSignedUpMessage) error, +) error { + // Get channel address + addr := "v3.issue333.events" + + // Set context + ctx = addAppContextValues(ctx, addr) + ctx = context.WithValue(ctx, extensions.ContextKeyIsDirection, "reception") + + // Build the handler that discriminates UserSignedUpMessage messages and + // dispatches them to the callback. + handler := func(hdlrCtx context.Context, bMsg extensions.BrokerMessage) (bool, error) { + // Try to convert the broker message to the expected type + msg, err := brokerMessageToUserSignedUpMessage(bMsg) + if err != nil { + return false, nil + } + + // Validate it against the message schema to discriminate it from the + // other message types received on this channel. + if err := validate.Struct(msg); err != nil { + return false, nil + } + + // Execute the subscription function + if err := fn(hdlrCtx, msg); err != nil { + return true, err + } + + return true, nil + } + + // Register the handler and subscribe to the channel if not done already + return c.subscribeToReceiveEventsOperation(ctx, addr, "UserSignedUpMessage", handler) +} + +// UnsubscribeFromReceiveEventsOperationForUserSignedUp will stop the reception of UserSignedUp messages from Events channel. +// The underlying broker subscription is canceled once the last message type on +// the channel is unsubscribed. +// A timeout can be set in context to avoid blocking operation, if needed. +func (c *AppController) UnsubscribeFromReceiveEventsOperationForUserSignedUp( + ctx context.Context, +) { + // Get channel address + addr := "v3.issue333.events" + + c.unsubscribeFromReceiveEventsOperation(ctx, addr, "UserSignedUpMessage") +} + +// subscribeToReceiveEventsOperation registers a per-message handler on the +// Events channel and, on the first +// registration, opens a single broker subscription multiplexed to every +// registered handler (issue #333). +func (c *AppController) subscribeToReceiveEventsOperation( + ctx context.Context, + addr string, + msgName string, + handler messageDispatchHandler, +) error { + c.dispatcher.mutex.Lock() + defer c.dispatcher.mutex.Unlock() + + // If there are already handlers on this channel, just register this one: the + // existing broker subscription will dispatch to it. + if handlers, exists := c.dispatcher.handlers[addr]; exists { + if _, exists := handlers[msgName]; exists { + err := fmt.Errorf("%w: controller is already subscribed for message %q on channel %q", extensions.ErrAlreadySubscribedChannel, msgName, addr) + c.logger.Error(ctx, err.Error(), extensions.LogInfosFromContext(ctx)...) + return err + } + + handlers[msgName] = handler + c.logger.Info(ctx, "Subscribed to channel", extensions.LogInfosFromContext(ctx)...) + return nil + } + + // First registration on this channel: register the handler... + c.dispatcher.handlers[addr] = map[string]messageDispatchHandler{msgName: handler} + + // ...and subscribe to the broker channel. + sub, err := c.broker.Subscribe(ctx, addr) + if err != nil { + delete(c.dispatcher.handlers, addr) + c.logger.Error(ctx, err.Error(), extensions.LogInfosFromContext(ctx)...) + return err + } + c.subscriptions[addr] = sub + c.logger.Info(ctx, "Subscribed to channel", extensions.LogInfosFromContext(ctx)...) + + // Asynchronously listen to new messages and dispatch them to the matching + // registered handler. + go func() { + for { + // Listen to next message + stop, err := c.listenToReceiveEventsOperationNextMessage(addr, sub) + if err != nil { + c.logger.Error(ctx, err.Error(), extensions.LogInfosFromContext(ctx)...) + } + + // Stop if required + if stop { + return + } + } + }() + + return nil +} + +func (c *AppController) listenToReceiveEventsOperationNextMessage( + addr string, + sub extensions.BrokerChannelSubscription, +) (stop bool, err error) { + // Create a context for the received response + msgCtx, cancel := context.WithCancel(context.Background()) + msgCtx = addAppContextValues(msgCtx, addr) + msgCtx = context.WithValue(msgCtx, extensions.ContextKeyIsDirection, "reception") + defer cancel() + + // Wait for next message + acknowledgeableBrokerMessage, open := <-sub.MessagesChannel() + + // If subscription is closed and there is no more message + // (i.e. uninitialized message), then exit the function + if !open && acknowledgeableBrokerMessage.IsUninitialized() { + return true, nil + } + + // Set broker message to context + msgCtx = context.WithValue(msgCtx, extensions.ContextKeyIsBrokerMessage, acknowledgeableBrokerMessage.String()) + + // Execute middlewares before handling the message + if err := c.executeMiddlewares(msgCtx, &acknowledgeableBrokerMessage.BrokerMessage, func(middlewareCtx context.Context) error { + // Snapshot the registered message names in a deterministic order + c.dispatcher.mutex.Lock() + handlers := c.dispatcher.handlers[addr] + msgNames := make([]string, 0, len(handlers)) + for msgName := range handlers { + msgNames = append(msgNames, msgName) + } + c.dispatcher.mutex.Unlock() + sort.Strings(msgNames) + + // Try each registered handler until one matches the received message + for _, msgName := range msgNames { + c.dispatcher.mutex.Lock() + handler := c.dispatcher.handlers[addr][msgName] + c.dispatcher.mutex.Unlock() + if handler == nil { + continue + } + + handled, err := handler(middlewareCtx, acknowledgeableBrokerMessage.BrokerMessage) + if err != nil { + return err + } + if handled { + acknowledgeableBrokerMessage.Ack() + return nil + } + } + + // No registered handler matched the received message + return extensions.ErrNoMatchingMessage + }); err != nil { + c.errorHandler(msgCtx, addr, &acknowledgeableBrokerMessage, err) + // On error execute the acknowledgeableBrokerMessage nack() function and + // let the BrokerAcknowledgment decide what is the right nack behavior for the broker + acknowledgeableBrokerMessage.Nak() + } + + return false, nil +} + +func (c *AppController) unsubscribeFromReceiveEventsOperation( + ctx context.Context, + addr string, + msgName string, +) { + c.dispatcher.mutex.Lock() + defer c.dispatcher.mutex.Unlock() + + // Check if there are handlers for this channel + handlers, exists := c.dispatcher.handlers[addr] + if !exists { + return + } + + // Check if this message type is subscribed + if _, exists := handlers[msgName]; !exists { + return + } + + // Remove the handler for this message type + delete(handlers, msgName) + + // Set context + ctx = addAppContextValues(ctx, addr) + + // If there are no more handlers on this channel, cancel the broker subscription + if len(handlers) == 0 { + delete(c.dispatcher.handlers, addr) + + if sub, exists := c.subscriptions[addr]; exists { + sub.Cancel(ctx) + delete(c.subscriptions, addr) + } + } + + c.logger.Info(ctx, "Unsubscribed from channel", extensions.LogInfosFromContext(ctx)...) +} + +// UserController is the structure that provides sending capabilities to the +// developer and and connect the broker with the User +type UserController struct { + controller +} + +// NewUserController links the User to the broker +func NewUserController(bc extensions.BrokerController, options ...ControllerOption) (*UserController, error) { + // Check if broker controller has been provided + if bc == nil { + return nil, extensions.ErrNilBrokerController + } + + // Create default controller + controller := controller{ + broker: bc, + subscriptions: make(map[string]extensions.BrokerChannelSubscription), + logger: extensions.DummyLogger{}, + middlewares: make([]extensions.Middleware, 0), + errorHandler: extensions.DefaultErrorHandler(), + } + + // Apply options + for _, option := range options { + option(&controller) + } + + return &UserController{controller: controller}, nil +} + +func (c UserController) wrapMiddlewares( + middlewares []extensions.Middleware, + callback extensions.NextMiddleware, +) func(ctx context.Context, msg *extensions.BrokerMessage) error { + var called bool + + // If there is no more middleware + if len(middlewares) == 0 { + return func(ctx context.Context, msg *extensions.BrokerMessage) error { + // Call the callback if it exists and it has not been called already + if callback != nil && !called { + called = true + return callback(ctx) + } + + // Nil can be returned, as the callback has already been called + return nil + } + } + + // Get the next function to call from next middlewares or callback + next := c.wrapMiddlewares(middlewares[1:], callback) + + // Wrap middleware into a check function that will call execute the middleware + // and call the next wrapped middleware if the returned function has not been + // called already + return func(ctx context.Context, msg *extensions.BrokerMessage) error { + // Call the middleware and the following if it has not been done already + if !called { + // Create the next call with the context and the message + nextWithArgs := func(ctx context.Context) error { + return next(ctx, msg) + } + + // Call the middleware and register it as already called + called = true + if err := middlewares[0](ctx, msg, nextWithArgs); err != nil { + return err + } + + // If next has already been called in middleware, it should not be executed again + return nextWithArgs(ctx) + } + + // Nil can be returned, as the next middleware has already been called + return nil + } +} + +func (c UserController) executeMiddlewares(ctx context.Context, msg *extensions.BrokerMessage, callback extensions.NextMiddleware) error { + // Wrap middleware to have 'next' function when calling them + wrapped := c.wrapMiddlewares(c.middlewares, callback) + + // Execute wrapped middlewares + return wrapped(ctx, msg) +} + +func addUserContextValues(ctx context.Context, addr string) context.Context { + ctx = context.WithValue(ctx, extensions.ContextKeyIsVersion, "1.0.0") + ctx = context.WithValue(ctx, extensions.ContextKeyIsProvider, "user") + return context.WithValue(ctx, extensions.ContextKeyIsChannel, addr) +} + +// Close will clean up any existing resources on the controller +func (c *UserController) Close(ctx context.Context) { + // Unsubscribing remaining channels +} + +// SendToReceiveEventsOperationForUserDeleted will send a UserDeleted message on Events channel. +func (c *UserController) SendToReceiveEventsOperationForUserDeleted( + ctx context.Context, + msg UserDeletedMessage, +) error { + // Set channel address + addr := "v3.issue333.events" + + // Set context + ctx = addUserContextValues(ctx, addr) + ctx = context.WithValue(ctx, extensions.ContextKeyIsDirection, "publication") + + // Convert to BrokerMessage + brokerMsg, err := msg.toBrokerMessage() + if err != nil { + return err + } + + // Set broker message to context + ctx = context.WithValue(ctx, extensions.ContextKeyIsBrokerMessage, brokerMsg.String()) + + // Send the message on event-broker through middlewares + return c.executeMiddlewares(ctx, &brokerMsg, func(ctx context.Context) error { + return c.broker.Publish(ctx, addr, brokerMsg) + }) +} + +// SendToReceiveEventsOperationForUserSignedUp will send a UserSignedUp message on Events channel. +func (c *UserController) SendToReceiveEventsOperationForUserSignedUp( + ctx context.Context, + msg UserSignedUpMessage, +) error { + // Set channel address + addr := "v3.issue333.events" + + // Set context + ctx = addUserContextValues(ctx, addr) + ctx = context.WithValue(ctx, extensions.ContextKeyIsDirection, "publication") + + // Convert to BrokerMessage + brokerMsg, err := msg.toBrokerMessage() + if err != nil { + return err + } + + // Set broker message to context + ctx = context.WithValue(ctx, extensions.ContextKeyIsBrokerMessage, brokerMsg.String()) + + // Send the message on event-broker through middlewares + return c.executeMiddlewares(ctx, &brokerMsg, func(ctx context.Context) error { + return c.broker.Publish(ctx, addr, brokerMsg) + }) +} + +// AsyncAPIVersion is the version of the used AsyncAPI document +const AsyncAPIVersion = "1.0.0" + +// MessageWithCorrelationID is implemented by messages that carry a correlation ID. +type MessageWithCorrelationID interface { + CorrelationID() string + SetCorrelationID(id string) +} + +// Error is the error structure returned by the controller operations. +type Error struct { + Channel string + Err error +} + +// Error returns a string representation of the error. +func (e *Error) Error() string { + return fmt.Sprintf("channel %q: err %v", e.Channel, e.Err) +} + +// Message 'UserDeletedMessageFromEventsChannel' reference another one at '#/components/messages/userDeleted'. +// This should be fixed in a future version to allow message override. +// If you encounter this message, feel free to open an issue on this subject +// to let know that you need this functionnality. + +// Message 'UserSignedUpMessageFromEventsChannel' reference another one at '#/components/messages/userSignedUp'. +// This should be fixed in a future version to allow message override. +// If you encounter this message, feel free to open an issue on this subject +// to let know that you need this functionnality. + +// UserDeletedMessagePayload is a schema from the AsyncAPI specification required in messages +type UserDeletedMessagePayload struct { + Event string `json:"event" validate:"oneof='user_deleted'"` + Id string `json:"id"` +} + +// UserDeletedMessage is the message expected for 'UserDeletedMessage' channel. +type UserDeletedMessage struct { + // Payload will be inserted in the message payload + Payload UserDeletedMessagePayload +} + +// NewUserDeletedMessage creates a new UserDeletedMessage with default values if any. +func NewUserDeletedMessage() UserDeletedMessage { + var msg UserDeletedMessage + + return msg +} + +// brokerMessageToUserDeletedMessage will fill a new UserDeletedMessage with data from generic broker message +func brokerMessageToUserDeletedMessage(bMsg extensions.BrokerMessage) (UserDeletedMessage, error) { + var msg UserDeletedMessage + + // Unmarshal payload to expected message payload format + err := json.Unmarshal(bMsg.Payload, &msg.Payload) + if err != nil { + return msg, err + } + + // TODO: run checks on msg type + + return msg, nil +} + +// toBrokerMessage will generate a generic broker message from UserDeletedMessage data +func (msg UserDeletedMessage) toBrokerMessage() (extensions.BrokerMessage, error) { + // TODO: implement checks on message + + // Marshal payload to JSON + payload, err := json.Marshal(msg.Payload) + if err != nil { + return extensions.BrokerMessage{}, err + } + + // There is no headers here + headers := make(map[string][]byte, 0) + + return extensions.BrokerMessage{ + Headers: headers, + Payload: payload, + }, nil +} + +// UserSignedUpMessagePayload is a schema from the AsyncAPI specification required in messages +type UserSignedUpMessagePayload struct { + Event string `json:"event" validate:"oneof='user_signed_up'"` + Id string `json:"id"` +} + +// UserSignedUpMessage is the message expected for 'UserSignedUpMessage' channel. +type UserSignedUpMessage struct { + // Payload will be inserted in the message payload + Payload UserSignedUpMessagePayload +} + +// NewUserSignedUpMessage creates a new UserSignedUpMessage with default values if any. +func NewUserSignedUpMessage() UserSignedUpMessage { + var msg UserSignedUpMessage + + return msg +} + +// brokerMessageToUserSignedUpMessage will fill a new UserSignedUpMessage with data from generic broker message +func brokerMessageToUserSignedUpMessage(bMsg extensions.BrokerMessage) (UserSignedUpMessage, error) { + var msg UserSignedUpMessage + + // Unmarshal payload to expected message payload format + err := json.Unmarshal(bMsg.Payload, &msg.Payload) + if err != nil { + return msg, err + } + + // TODO: run checks on msg type + + return msg, nil +} + +// toBrokerMessage will generate a generic broker message from UserSignedUpMessage data +func (msg UserSignedUpMessage) toBrokerMessage() (extensions.BrokerMessage, error) { + // TODO: implement checks on message + + // Marshal payload to JSON + payload, err := json.Marshal(msg.Payload) + if err != nil { + return extensions.BrokerMessage{}, err + } + + // There is no headers here + headers := make(map[string][]byte, 0) + + return extensions.BrokerMessage{ + Headers: headers, + Payload: payload, + }, nil +} + +const ( + // EventsChannelPath is the constant representing the 'EventsChannel' channel path. + EventsChannelPath = "v3.issue333.events" +) + +// ChannelsPaths is an array of all channels paths +var ChannelsPaths = []string{ + EventsChannelPath, +} diff --git a/test/v3/issues/333/asyncapi.yaml b/test/v3/issues/333/asyncapi.yaml new file mode 100644 index 00000000..2fb4ca97 --- /dev/null +++ b/test/v3/issues/333/asyncapi.yaml @@ -0,0 +1,48 @@ +asyncapi: 3.0.0 +info: + title: Issue 333 - receive multiple messages per operation + version: 1.0.0 + +channels: + events: + address: v3.issue333.events + messages: + userSignedUp: + $ref: '#/components/messages/userSignedUp' + userDeleted: + $ref: '#/components/messages/userDeleted' + +operations: + receiveEvents: + action: receive + channel: + $ref: '#/channels/events' + +components: + messages: + userSignedUp: + payload: + type: object + required: + - event + - id + properties: + event: + type: string + enum: + - user_signed_up + id: + type: string + userDeleted: + payload: + type: object + required: + - event + - id + properties: + event: + type: string + enum: + - user_deleted + id: + type: string diff --git a/test/v3/issues/333/gen.go b/test/v3/issues/333/gen.go new file mode 100644 index 00000000..0ad6622b --- /dev/null +++ b/test/v3/issues/333/gen.go @@ -0,0 +1,3 @@ +//go:generate go run ../../../../cmd/asyncapi-codegen -p issue333 -i ./asyncapi.yaml -o ./asyncapi.gen.go + +package issue333 diff --git a/test/v3/issues/333/suite_test.go b/test/v3/issues/333/suite_test.go new file mode 100644 index 00000000..d264b48b --- /dev/null +++ b/test/v3/issues/333/suite_test.go @@ -0,0 +1,221 @@ +package issue333 + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/lerenn/asyncapi-codegen/pkg/extensions" + "github.com/stretchr/testify/suite" +) + +const eventsChannel = "v3.issue333.events" + +func TestSuite(t *testing.T) { + suite.Run(t, NewSuite()) +} + +type Suite struct { + suite.Suite +} + +func NewSuite() *Suite { + return &Suite{} +} + +// ackRecorder records whether a delivered message ended up acked or naked. +type ackRecorder struct { + acked chan struct{} + naked chan struct{} +} + +func newAckRecorder() *ackRecorder { + return &ackRecorder{ + acked: make(chan struct{}, 1), + naked: make(chan struct{}, 1), + } +} + +func (a *ackRecorder) AckMessage() { a.acked <- struct{}{} } +func (a *ackRecorder) NakMessage() { a.naked <- struct{}{} } + +// memBroker is a minimal in-memory broker that lets the test inject raw broker +// messages on a channel and observe how they are acknowledged. +type memBroker struct { + mu sync.Mutex + subs map[string]extensions.BrokerChannelSubscription +} + +func newMemBroker() *memBroker { + return &memBroker{subs: make(map[string]extensions.BrokerChannelSubscription)} +} + +func (b *memBroker) Publish(_ context.Context, _ string, _ extensions.BrokerMessage) error { + return nil +} + +func (b *memBroker) Subscribe(_ context.Context, channel string) (extensions.BrokerChannelSubscription, error) { + sub := extensions.NewBrokerChannelSubscription( + make(chan extensions.AcknowledgeableBrokerMessage, 8), + make(chan any, 1), + ) + sub.WaitForCancellationAsync(func() {}) + + b.mu.Lock() + b.subs[channel] = sub + b.mu.Unlock() + + return sub, nil +} + +// inject delivers a raw payload to the subscribers of the events channel and +// returns the recorder that observes its acknowledgement. +func (b *memBroker) inject(payload []byte) *ackRecorder { + b.mu.Lock() + sub := b.subs[eventsChannel] + b.mu.Unlock() + + rec := newAckRecorder() + sub.TransmitReceivedMessage(extensions.NewAcknowledgeableBrokerMessage( + extensions.BrokerMessage{Payload: payload}, + rec, + )) + + return rec +} + +// receiver captures the messages dispatched to each per-message callback. +type receiver struct { + signedUp chan UserSignedUpMessage + deleted chan UserDeletedMessage +} + +func newReceiver() *receiver { + return &receiver{ + signedUp: make(chan UserSignedUpMessage, 1), + deleted: make(chan UserDeletedMessage, 1), + } +} + +func (r *receiver) ReceiveEventsOperationForUserSignedUpReceived(_ context.Context, msg UserSignedUpMessage) error { + r.signedUp <- msg + return nil +} + +func (r *receiver) ReceiveEventsOperationForUserDeletedReceived(_ context.Context, msg UserDeletedMessage) error { + r.deleted <- msg + return nil +} + +// TestDispatchesEachMessageTypeToItsOwnCallback ensures that two distinct +// message types received on the same channel are each dispatched to their own +// per-message callback using try-each-until-valid discrimination (issue #333). +func (suite *Suite) TestDispatchesEachMessageTypeToItsOwnCallback() { + broker := newMemBroker() + ctrl, err := NewAppController(broker) + suite.Require().NoError(err) + defer ctrl.Close(context.Background()) + + rcv := newReceiver() + suite.Require().NoError(ctrl.SubscribeToAllChannels(context.Background(), rcv)) + + // A user_signed_up message must reach the UserSignedUp callback only. + rec := broker.inject([]byte(`{"event":"user_signed_up","id":"signed-1"}`)) + select { + case msg := <-rcv.signedUp: + suite.Require().Equal("signed-1", msg.Payload.Id) + case <-time.After(time.Second): + suite.Fail("UserSignedUp callback was not called") + } + suite.requireAcked(rec) + suite.Require().Empty(rcv.deleted, "UserDeleted callback must not be called for a user_signed_up message") + + // A user_deleted message must reach the UserDeleted callback only, even + // though UserDeleted is tried after UserSignedUp in alphabetical order. + rec = broker.inject([]byte(`{"event":"user_deleted","id":"deleted-1"}`)) + select { + case msg := <-rcv.deleted: + suite.Require().Equal("deleted-1", msg.Payload.Id) + case <-time.After(time.Second): + suite.Fail("UserDeleted callback was not called") + } + suite.requireAcked(rec) + suite.Require().Empty(rcv.signedUp, "UserSignedUp callback must not be called for a user_deleted message") +} + +// TestUnmatchedMessageIsNakedAndReported ensures a message that matches none of +// the expected types is naked and surfaced through the error handler with +// ErrNoMatchingMessage (issue #333). +func (suite *Suite) TestUnmatchedMessageIsNakedAndReported() { + handlerErr := make(chan error, 1) + broker := newMemBroker() + ctrl, err := NewAppController(broker, WithErrorHandler( + func(_ context.Context, _ string, _ *extensions.AcknowledgeableBrokerMessage, opErr error) { + handlerErr <- opErr + }, + )) + suite.Require().NoError(err) + defer ctrl.Close(context.Background()) + + rcv := newReceiver() + suite.Require().NoError(ctrl.SubscribeToAllChannels(context.Background(), rcv)) + + rec := broker.inject([]byte(`{"event":"unknown","id":"x"}`)) + + select { + case opErr := <-handlerErr: + suite.Require().ErrorIs(opErr, extensions.ErrNoMatchingMessage) + case <-time.After(time.Second): + suite.Fail("error handler was not called for an unmatched message") + } + + suite.requireNaked(rec) + suite.Require().Empty(rcv.signedUp) + suite.Require().Empty(rcv.deleted) +} + +// TestUnsubscribeStopsDispatch ensures that unsubscribing a single message type +// removes only its handler while the others keep receiving (issue #333). +func (suite *Suite) TestUnsubscribeStopsDispatch() { + broker := newMemBroker() + ctrl, err := NewAppController(broker) + suite.Require().NoError(err) + defer ctrl.Close(context.Background()) + + rcv := newReceiver() + suite.Require().NoError(ctrl.SubscribeToAllChannels(context.Background(), rcv)) + + // Unsubscribe only the UserSignedUp handler. + ctrl.UnsubscribeFromReceiveEventsOperationForUserSignedUp(context.Background()) + + // UserDeleted must still be dispatched. + rec := broker.inject([]byte(`{"event":"user_deleted","id":"deleted-2"}`)) + select { + case msg := <-rcv.deleted: + suite.Require().Equal("deleted-2", msg.Payload.Id) + case <-time.After(time.Second): + suite.Fail("UserDeleted callback was not called after unsubscribing UserSignedUp") + } + suite.requireAcked(rec) +} + +func (suite *Suite) requireAcked(rec *ackRecorder) { + select { + case <-rec.acked: + case <-rec.naked: + suite.Fail("message was naked but should have been acked") + case <-time.After(time.Second): + suite.Fail("message was neither acked nor naked") + } +} + +func (suite *Suite) requireNaked(rec *ackRecorder) { + select { + case <-rec.naked: + case <-rec.acked: + suite.Fail("message was acked but should have been naked") + case <-time.After(time.Second): + suite.Fail("message was neither acked nor naked") + } +}