Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -877,6 +877,30 @@ func (t *Settings) SetDefaults() {

Defaults are supported for scalar properties (string, boolean, integer, number).

### Multiple messages per operation (AsyncAPI v3)

When an operation (or its channel) declares more than one message, a dedicated
send function is generated for each one, named after the operation and the
message:

```yaml
channels:
events:
address: app.events
messages:
userCreated: { $ref: '#/components/messages/userCreated' }
userDeleted: { $ref: '#/components/messages/userDeleted' }
operations:
sendEvents:
action: send
channel: { $ref: '#/channels/events' }
```

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).

### Channel parameters from message location (AsyncAPI v3)

When a channel parameter declares a `location` runtime expression, the generated
Expand Down
19 changes: 15 additions & 4 deletions pkg/asyncapi/v3/channel.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package asyncapiv3

import (
"fmt"
"sort"

"github.com/lerenn/asyncapi-codegen/pkg/extensions"
)
Expand Down Expand Up @@ -154,10 +155,20 @@ func (ch *Channel) Follow() *Channel {
return ch
}

// GetMessage will return the channel message.
// GetMessage will return the channel message. When the channel has several
// messages, the one with the lowest name is returned deterministically (ranging
// a map directly would be non-deterministic, producing unstable generated code).
func (ch Channel) GetMessage() (*Message, error) {
for _, m := range ch.Follow().Messages {
return m.Follow(), nil // TODO: change
messages := ch.Follow().Messages
if len(messages) == 0 {
return nil, fmt.Errorf("%w: channel %q", ErrNoMessageInChannel, ch.Name)
}
return nil, fmt.Errorf("%w: channel %q", ErrNoMessageInChannel, ch.Name)

names := make([]string, 0, len(messages))
for name := range messages {
names = append(names, name)
}
sort.Strings(names)

return messages[names[0]].Follow(), nil
}
27 changes: 26 additions & 1 deletion pkg/asyncapi/v3/operation.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package asyncapiv3

import "strings"
import (
"sort"
"strings"
)

// OperationAction represents an OperationAction.
type OperationAction string
Expand Down Expand Up @@ -247,6 +250,28 @@ func (op Operation) GetMessage() (*Message, error) {
return op.Channel.GetMessage()
}

// GetMessages returns all the resolved messages of the operation, sorted by
// name for deterministic generation. It falls back to the channel messages when
// the operation itself does not list any.
func (op Operation) GetMessages() []*Message {
var msgs []*Message

switch {
case len(op.Messages) > 0:
for _, m := range op.Messages {
msgs = append(msgs, m.Follow())
}
case op.Channel != nil:
for _, m := range op.Channel.Follow().Messages {
msgs = append(msgs, m.Follow())
}
}

sort.Slice(msgs, func(i, j int) bool { return msgs[i].Name < msgs[j].Name })

return msgs
}

// ApplyTrait applies a trait to the operation.
func (op *Operation) ApplyTrait(ot *OperationTrait, spec Specification) {
// Check operation is not nil
Expand Down
53 changes: 53 additions & 0 deletions pkg/codegen/generators/v3/templates/controller.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,58 @@ func (c *{{ $.Prefix }}Controller) UnsubscribeFrom{{ namify $value.Follow.Name }
{{- end}}

{{- range $key, $value := .Operations.Send}}
{{- if and (gt (operationMessageCount $value) 1) (not .Reply) (not .ReplyOf)}}
{{- /* Multiple messages: generate one send function per message (#140) */}}
{{- range $msg := $value.GetMessages}}

// {{ sendFuncNameForMessage $value $.Prefix $msg }} will send a {{ cutSuffix (messageTypeName $msg) "Message" }} message on {{ cutSuffix (opToChannelTypeName $value) "Channel" }} channel.
func (c *{{ $.Prefix }}Controller) {{ sendFuncNameForMessage $value $.Prefix $msg }}(
ctx context.Context,
{{- if $value.Channel.Follow.Parameters }}
params {{namifyWithoutParam $value.Channel.Follow.Name}}Parameters,
{{- end}}
{{- if eq $value.Channel.Follow.Address "" }}
chanAddr string,
{{- end}}
msg {{messageTypeName $msg}},
) error {
// Set channel address
{{- if eq $value.Channel.Follow.Address "" }}
addr := chanAddr
{{- else }}
addr := {{ generateChannelAddrFromOp $value }}
{{- end }}

{{if $msg.HaveCorrelationID -}}
// Set correlation ID if it does not exist
if id := msg.CorrelationID(); id == "" {
msg.SetCorrelationID(uuid.New().String())
}
{{- end}}

// Set context
ctx = add{{ $.Prefix }}ContextValues(ctx, addr)
ctx = context.WithValue(ctx, extensions.ContextKeyIsDirection, "publication")
{{if $msg.HaveCorrelationID -}}
ctx = context.WithValue(ctx, extensions.ContextKeyIsCorrelationID, msg.CorrelationID())
{{- end}}

// 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)
})
}
{{- end}}
{{- else}}

// {{ sendFuncName $value $.Prefix }} will send a {{ cutSuffix (opToMsgTypeName $value) "Message" }} message on {{ cutSuffix (opToChannelTypeName $value) "Channel" }} channel.
//
Expand Down Expand Up @@ -371,6 +423,7 @@ func (c *{{ $.Prefix }}Controller) {{ sendFuncName $value $.Prefix }}(
return c.broker.Publish(ctx, addr, brokerMsg)
})
}
{{- end}}


{{if .Reply -}}
Expand Down
22 changes: 22 additions & 0 deletions pkg/codegen/generators/v3/templates/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"regexp"
"strconv"
"strings"
"text/template"

asyncapi "github.com/lerenn/asyncapi-codegen/pkg/asyncapi/v3"
Expand Down Expand Up @@ -190,6 +191,24 @@ func RequestFuncName(op *asyncapi.Operation, prefix string) string {
return verb + templateutil.Namify(op.Follow().Name)
}

// OperationMessageCount returns the number of messages of an operation.
func OperationMessageCount(op *asyncapi.Operation) int {
return len(op.Follow().GetMessages())
}

// MessageTypeName returns the generated Go type name of a message.
func MessageTypeName(msg *asyncapi.Message) string {
return templateutil.Namify(msg.Follow().Name)
}

// SendFuncNameForMessage returns the name of the per-message send function
// generated when an operation carries more than one message (issue #140). It is
// the operation send function name suffixed with "For" and the message name.
func SendFuncNameForMessage(op *asyncapi.Operation, prefix string, msg *asyncapi.Message) string {
base := strings.TrimSuffix(MessageTypeName(msg), "Message")
return SendFuncName(op, prefix) + "For" + base
}

// HelpersFunctions returns the functions that can be used as helpers
// in a golang template.
func HelpersFunctions() template.FuncMap {
Expand All @@ -212,5 +231,8 @@ func HelpersFunctions() template.FuncMap {
"replyFuncName": ReplyFuncName,
"sendFuncName": SendFuncName,
"requestFuncName": RequestFuncName,
"operationMessageCount": OperationMessageCount,
"messageTypeName": MessageTypeName,
"sendFuncNameForMessage": SendFuncNameForMessage,
}
}
Loading
Loading