From 0fe3606484ec985b8c06e924f92ebacc94dae582 Mon Sep 17 00:00:00 2001 From: Louis FRADIN Date: Fri, 12 Jun 2026 17:48:42 +0200 Subject: [PATCH] feat(v3): auto-fill channel parameters from message location (#139) Channel parameters that declare a `location` runtime expression were parsed but ignored. The generated send functions now derive such a parameter from the outgoing message (payload or header) when the caller leaves it empty, while keeping it overridable. Reuses the same location-tree machinery as correlation IDs / reply addresses, and adds a Follow() method to Parameter. Fixes #139 Co-Authored-By: Claude Opus 4.8 (1M context) --- README.md | 24 + pkg/asyncapi/v3/operation.go | 36 ++ pkg/asyncapi/v3/parameter.go | 13 + .../generators/v3/templates/controller.tmpl | 1 + .../generators/v3/templates/message.tmpl | 23 + test/v3/issues/139/asyncapi.gen.go | 534 ++++++++++++++++++ test/v3/issues/139/asyncapi.yaml | 31 + test/v3/issues/139/suite_test.go | 75 +++ 8 files changed, 737 insertions(+) create mode 100644 test/v3/issues/139/asyncapi.gen.go create mode 100644 test/v3/issues/139/asyncapi.yaml create mode 100644 test/v3/issues/139/suite_test.go diff --git a/README.md b/README.md index 0409cc40..4cb6a046 100644 --- a/README.md +++ b/README.md @@ -866,6 +866,30 @@ func (t *Settings) SetDefaults() { Defaults are supported for scalar properties (string, boolean, integer, number). +### Channel parameters from message location (AsyncAPI v3) + +When a channel parameter declares a `location` runtime expression, the generated +send functions auto-fill that parameter from the outgoing message when the +caller leaves it empty. The parameter stays overridable: if you set it +explicitly, your value is used as-is. + +```yaml +channels: + user: + address: app.user.{userId} + parameters: + userId: + location: $message.payload#/userId + messages: + userSignedUp: + $ref: '#/components/messages/userSignedUp' +``` + +With the spec above, `SendAs...` derives `userId` from `msg.Payload.UserId`, so +the message is published on `app.user.` without passing the parameter +manually. Supported locations are `$message.payload#/...` and +`$message.header#/...`, and the targeted field must be a string. + ### ErrorHandler You can use an error handler that will be executed when processing for messages diff --git a/pkg/asyncapi/v3/operation.go b/pkg/asyncapi/v3/operation.go index 385cc5b9..cf4b55aa 100644 --- a/pkg/asyncapi/v3/operation.go +++ b/pkg/asyncapi/v3/operation.go @@ -1,5 +1,7 @@ package asyncapiv3 +import "strings" + // OperationAction represents an OperationAction. type OperationAction string @@ -157,9 +159,43 @@ func (op *Operation) setDependencies(spec Specification) error { // Generate reply op.generateReply() + // Resolve channel parameter locations against the operation message + op.setParametersLocationDependencies() + return nil } +// setParametersLocationDependencies resolves, for each channel parameter that +// defines a `location` runtime expression, the field of the operation message +// it points to. It ensures the field exists on the message (creating the schema +// tree if needed, like correlation IDs do) and records whether that field is +// required so the generated code knows if it is a pointer. This lets the +// generated send functions auto-fill the parameter from the message. +func (op *Operation) setParametersLocationDependencies() { + ch := op.Channel.Follow() + if ch == nil || len(ch.Parameters) == 0 { + return + } + + // The location refers to the operation message; if there is none, there is + // nothing to resolve. + msg, err := op.GetMessage() + if err != nil { + return + } + + for _, p := range ch.Parameters { + pf := p.Follow() + if pf.Location == "" { + continue + } + + locationParent := msg.createTreeUntilLocation(pf.Location) + path := strings.Split(pf.Location, "/") + pf.LocationRequired = locationParent.IsFieldRequired(path[len(path)-1]) + } +} + func (op *Operation) setReference(spec Specification) error { if op.Reference == "" { return nil diff --git a/pkg/asyncapi/v3/parameter.go b/pkg/asyncapi/v3/parameter.go index bc873974..2ee2f9fd 100644 --- a/pkg/asyncapi/v3/parameter.go +++ b/pkg/asyncapi/v3/parameter.go @@ -14,6 +14,19 @@ type Parameter struct { // Non AsyncAPI fields Name string `json:"-"` ReferenceTo *Parameter `json:"-"` + + // LocationRequired indicates whether the field targeted by Location is a + // required field of the message (and thus generated as a non-pointer field). + LocationRequired bool `json:"-"` +} + +// Follow returns the referenced parameter if there is one, otherwise the +// parameter itself. +func (p *Parameter) Follow() *Parameter { + if p.ReferenceTo != nil { + return p.ReferenceTo + } + return p } // generateMetadata generates metadata for the Parameter. diff --git a/pkg/codegen/generators/v3/templates/controller.tmpl b/pkg/codegen/generators/v3/templates/controller.tmpl index acc048a2..775d334c 100644 --- a/pkg/codegen/generators/v3/templates/controller.tmpl +++ b/pkg/codegen/generators/v3/templates/controller.tmpl @@ -330,6 +330,7 @@ func (c *{{ $.Prefix }}Controller) {{ sendFuncName $value $.Prefix }}( {{- end}} msg {{opToMsgTypeName $value}}, ) error { + {{- template "fill-parameters-from-location" $value }} // Set channel address {{- if eq .Channel.Follow.Address "" }} addr := chanAddr diff --git a/pkg/codegen/generators/v3/templates/message.tmpl b/pkg/codegen/generators/v3/templates/message.tmpl index cffca495..47bfe173 100644 --- a/pkg/codegen/generators/v3/templates/message.tmpl +++ b/pkg/codegen/generators/v3/templates/message.tmpl @@ -307,3 +307,26 @@ func (msg *{{namify .Name}}) SetAsResponseFrom(req MessageWithCorrelationID) { {{- end -}} {{- end }} + +{{- /* ---------------------------------------------------------------------- */ -}} +{{- /* fill-parameters-from-location auto-fills channel parameters that define */ -}} +{{- /* a `location` runtime expression from the outgoing message, unless the */ -}} +{{- /* caller already set them. The dot is the operation. (issue #139) */ -}} +{{- define "fill-parameters-from-location" -}} +{{- if .Channel.Follow.Parameters}} +{{- range $pkey, $pvalue := .Channel.Follow.Parameters}} +{{- if $pvalue.Follow.Location}} + // Fill {{namify $pkey}} from the message ({{$pvalue.Follow.Location}}) if not set + if params.{{namify $pkey}} == "" { + {{- if $pvalue.Follow.LocationRequired}} + params.{{namify $pkey}} = msg.{{referenceToStructAttributePath $pvalue.Follow.Location}} + {{- else}} + if v := msg.{{referenceToStructAttributePath $pvalue.Follow.Location}}; v != nil { + params.{{namify $pkey}} = *v + } + {{- end}} + } +{{- end}} +{{- end}} +{{- end}} +{{- end -}} diff --git a/test/v3/issues/139/asyncapi.gen.go b/test/v3/issues/139/asyncapi.gen.go new file mode 100644 index 00000000..8b7ac834 --- /dev/null +++ b/test/v3/issues/139/asyncapi.gen.go @@ -0,0 +1,534 @@ +// Package "issue139" provides primitives to interact with the AsyncAPI specification. +// +// Code generated by github.com/lerenn/asyncapi-codegen version (devel) DO NOT EDIT. +package issue139 + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/lerenn/asyncapi-codegen/pkg/extensions" +) + +// 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 + // 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 + } +} + +// 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), + 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 +} + +// SendAsSendUserOperation will send a UserSignedUp message on User channel. +// +// 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 *AppController) SendAsSendUserOperation( + ctx context.Context, + params UserChannelParameters, + msg UserSignedUpMessage, +) error { + // Fill UserId from the message ($message.payload#/userId) if not set + if params.UserId == "" { + if v := msg.Payload.UserId; v != nil { + params.UserId = *v + } + } + // Set channel address + addr := fmt.Sprintf("v3.issue139.user.%s", params.UserId) + + // Set context + ctx = addAppContextValues(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) + }) +} + +// UserSubscriber contains all handlers that are listening messages for User +type UserSubscriber interface { + // SendUserOperationReceived receive all UserSignedUp messages from User channel. + SendUserOperationReceived(ctx context.Context, msg UserSignedUpMessage) error +} + +// 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 + c.UnsubscribeFromAllChannels(ctx) + + c.logger.Info(ctx, "Closed user controller") +} + +// 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 *UserController) SubscribeToAllChannels(ctx context.Context, as UserSubscriber) error { + if as == nil { + return extensions.ErrNilUserSubscriber + } + + return nil +} + +// UnsubscribeFromAllChannels will stop the subscription of all remaining subscribed channels +func (c *UserController) UnsubscribeFromAllChannels(ctx context.Context) { +} + +// SubscribeToSendUserOperation will receive UserSignedUp messages from User 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. +// +// 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) SubscribeToSendUserOperation( + ctx context.Context, + params UserChannelParameters, + fn func(ctx context.Context, msg UserSignedUpMessage) error, +) error { + // Get channel address + addr := fmt.Sprintf("v3.issue139.user.%s", params.UserId) + + // Set context + 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()) + return err + } + + // Subscribe to broker channel + sub, err := c.broker.Subscribe(ctx, addr) + if err != nil { + c.logger.Error(ctx, err.Error()) + return err + } + c.logger.Info(ctx, "Subscribed to channel") + + // Asynchronously listen to new messages and pass them to app receiver + go func() { + for { + // Listen to next message + stop, err := c.listenToSendUserOperationNextMessage(addr, sub, fn) + if err != nil { + c.logger.Error(ctx, err.Error()) + } + + // Stop if required + if stop { + return + } + } + }() + + // Add the cancel channel to the inside map + c.subscriptions[addr] = sub + + return nil +} + +func (c *UserController) listenToSendUserOperationNextMessage( + addr string, + sub extensions.BrokerChannelSubscription, + fn func(ctx context.Context, msg UserSignedUpMessage) error, +) (stop bool, err error) { + // Create a context for the received response + msgCtx, cancel := context.WithCancel(context.Background()) + msgCtx = addUserContextValues(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 { + // Process message + msg, err := brokerMessageToUserSignedUpMessage(acknowledgeableBrokerMessage.BrokerMessage) + if err != nil { + return err + } + + // Execute the subscription function + if err := fn(middlewareCtx, msg); err != nil { + return err + } + + acknowledgeableBrokerMessage.Ack() + + return nil + }); 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 +} + +// UnsubscribeFromSendUserOperation will stop the reception of UserSignedUp messages from User channel. +// A timeout can be set in context to avoid blocking operation, if needed. +func (c *UserController) UnsubscribeFromSendUserOperation( + ctx context.Context, + params UserChannelParameters, +) { + // Get channel address + addr := fmt.Sprintf("v3.issue139.user.%s", params.UserId) + + // Check if there receivers for this channel + sub, exists := c.subscriptions[addr] + if !exists { + return + } + + // Set context + ctx = addUserContextValues(ctx, addr) + + // Stop the subscription + sub.Cancel(ctx) + + // Remove if from the receivers + delete(c.subscriptions, addr) + + c.logger.Info(ctx, "Unsubscribed from channel") +} + +// AsyncAPIVersion is the version of the used AsyncAPI document +const AsyncAPIVersion = "1.0.0" + +type MessageWithCorrelationID interface { + CorrelationID() string + SetCorrelationID(id string) +} + +type Error struct { + Channel string + Err error +} + +func (e *Error) Error() string { + return fmt.Sprintf("channel %q: err %v", e.Channel, e.Err) +} + +// UserChannelParameters represents UserChannel channel parameters +type UserChannelParameters struct { + // UserId is a channel parameter. + UserId string +} + +// Message 'UserSignedUpMessageFromUserChannel' 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. + +// UserSignedUpMessagePayload is a schema from the AsyncAPI specification required in messages +type UserSignedUpMessagePayload struct { + Name *string `json:"name,omitempty"` + UserId *string `json:"userId,omitempty"` +} + +// UserSignedUpMessage is the message expected for 'UserSignedUpMessage' channel. +type UserSignedUpMessage struct { + // Payload will be inserted in the message payload + Payload UserSignedUpMessagePayload +} + +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 ( + // UserChannelPath is the constant representing the 'UserChannel' channel path. + UserChannelPath = "v3.issue139.user.{userId}" +) + +// ChannelsPaths is an array of all channels paths +var ChannelsPaths = []string{ + UserChannelPath, +} diff --git a/test/v3/issues/139/asyncapi.yaml b/test/v3/issues/139/asyncapi.yaml new file mode 100644 index 00000000..b9763174 --- /dev/null +++ b/test/v3/issues/139/asyncapi.yaml @@ -0,0 +1,31 @@ +asyncapi: 3.0.0 +info: + title: Issue 139 - dynamic parameter location + version: 1.0.0 + +channels: + user: + address: v3.issue139.user.{userId} + parameters: + userId: + location: $message.payload#/userId + messages: + userSignedUp: + $ref: '#/components/messages/userSignedUp' + +operations: + sendUser: + action: send + channel: + $ref: '#/channels/user' + +components: + messages: + userSignedUp: + payload: + type: object + properties: + userId: + type: string + name: + type: string diff --git a/test/v3/issues/139/suite_test.go b/test/v3/issues/139/suite_test.go new file mode 100644 index 00000000..5a553cde --- /dev/null +++ b/test/v3/issues/139/suite_test.go @@ -0,0 +1,75 @@ +//go:generate go run ../../../../cmd/asyncapi-codegen -p issue139 -i ./asyncapi.yaml -o ./asyncapi.gen.go + +package issue139 + +import ( + "context" + "testing" + + "github.com/lerenn/asyncapi-codegen/pkg/extensions" + "github.com/lerenn/asyncapi-codegen/pkg/utils" + "github.com/stretchr/testify/suite" +) + +func TestSuite(t *testing.T) { + suite.Run(t, NewSuite()) +} + +// capturingBroker records the channel address of the last published message. +type capturingBroker struct { + publishedChannel string +} + +func (b *capturingBroker) Publish(_ context.Context, channel string, _ extensions.BrokerMessage) error { + b.publishedChannel = channel + return nil +} + +func (b *capturingBroker) Subscribe( + _ context.Context, + _ string, +) (extensions.BrokerChannelSubscription, error) { + return extensions.NewBrokerChannelSubscription(make(chan extensions.AcknowledgeableBrokerMessage), make(chan any)), nil +} + +type Suite struct { + suite.Suite +} + +func NewSuite() *Suite { + return &Suite{} +} + +// TestParameterFilledFromMessageLocation ensures a channel parameter that +// declares a `location` is auto-filled from the outgoing message when the +// caller leaves it empty (issue #139). +func (suite *Suite) TestParameterFilledFromMessageLocation() { + broker := &capturingBroker{} + ctrl, err := NewAppController(broker) + suite.Require().NoError(err) + defer ctrl.Close(context.Background()) + + msg := NewUserSignedUpMessage() + msg.Payload.UserId = utils.ToPointer("abc") + + // userId left empty in params: it must be filled from the message payload. + err = ctrl.SendAsSendUserOperation(context.Background(), UserChannelParameters{}, msg) + suite.Require().NoError(err) + suite.Require().Equal("v3.issue139.user.abc", broker.publishedChannel) +} + +// TestParameterOverridesMessageLocation ensures an explicitly provided +// parameter is not overwritten by the message location value. +func (suite *Suite) TestParameterOverridesMessageLocation() { + broker := &capturingBroker{} + ctrl, err := NewAppController(broker) + suite.Require().NoError(err) + defer ctrl.Close(context.Background()) + + msg := NewUserSignedUpMessage() + msg.Payload.UserId = utils.ToPointer("abc") + + err = ctrl.SendAsSendUserOperation(context.Background(), UserChannelParameters{UserId: "override"}, msg) + suite.Require().NoError(err) + suite.Require().Equal("v3.issue139.user.override", broker.publishedChannel) +}