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
177 changes: 177 additions & 0 deletions internal/client/asyncapi_messages.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
package client

import (
"fmt"
"strings"

"github.com/xraph/forge/internal/shared"
)

// componentMessagesPrefix is where a document that does not follow AsyncAPI 3
// to the letter keeps the messages its operations reference.
const componentMessagesPrefix = "#/components/messages/"

// spokenMessage is one channel message an operation sends or receives.
type spokenMessage struct {
// key is the message's key under channels.<name>.messages.
key string
// name is what the generated binding calls it: the message's own `name`
// when it carries one, the key otherwise.
name string
msg *shared.AsyncAPIMessage
}

// operationMessages returns the channel messages an operation speaks, in
// sorted key order.
//
// AsyncAPI 3 lets an operation list the subset of the channel's messages it
// carries, as `#/channels/<channel>/messages/<key>` references. When it does,
// only those count: a duplex channel declares one message per direction and
// one operation per direction, and stamping every message with every
// operation's action is what left the send direction unnamed and the receive
// schema holding the send payload. An operation that lists no messages, or
// whose references all point outside the channel, speaks the whole channel,
// which is what every document generated before operations carried
// `messages` relied on.
func operationMessages(channel *shared.AsyncAPIChannel, operation *shared.AsyncAPIOperation) (spoken []spokenMessage, unresolved bool) {
wanted := make(map[string]struct{})
listed := operation != nil && len(operation.Messages) > 0

if operation != nil && operation.Channel != nil {
prefix := operation.Channel.Ref + "/messages/"

for _, ref := range operation.Messages {
if key, ok := strings.CutPrefix(ref.Ref, prefix); ok {
if _, declared := channel.Messages[key]; declared {
wanted[key] = struct{}{}
}
}
}
}

// Nothing resolved under this channel, so try the trailing segment of each
// reference as a channel message key. AsyncAPI 3 says an operation's
// `messages` point at the channel's own, and forge's router obeys that;
// other generators write `#/components/messages/send` and leave the
// channel to carry the definition. Under the strict read alone that
// document resolves nothing, both operations fall back to the whole
// channel, and the fold labels the two directions with whichever action
// came last -- the unnamed direction this whole path exists to prevent.
// The segment has to be a key the channel actually declares, so this can
// only ever narrow the fallback, never invent a message.
//
// Only a components reference qualifies. A reference into another
// channel's messages shares the key vocabulary with this one, and reading
// its last segment here would bind a direction to the wrong message.
if listed && len(wanted) == 0 {
for _, ref := range operation.Messages {
key, ok := strings.CutPrefix(ref.Ref, componentMessagesPrefix)
if !ok {
continue
}

if _, declared := channel.Messages[key]; declared {
wanted[key] = struct{}{}
}
}
}

out := make([]spokenMessage, 0, len(channel.Messages))

for _, key := range sortedStringKeys(channel.Messages) {
if _, ok := wanted[key]; len(wanted) > 0 && !ok {
continue
}

msg := channel.Messages[key]

name := msg.Name
if name == "" {
name = key
}

out = append(out, spokenMessage{key: key, name: name, msg: msg})
}

return out, listed && len(wanted) == 0
}

// applyOperationMessages records one operation's direction on the endpoint:
// the payload of the first message it speaks becomes that direction's schema
// if nothing claimed it yet, every payload lands in MessageTypes and the
// direction's message map under its key, and Metadata["messages"] maps each
// message NAME to the direction, which is where the generated duplex binding
// reads `send` and `receive` from.
//
// Both readers of an AsyncAPI document call this: once when the first
// operation on a channel creates the endpoint, and again for every later
// operation folded into it. Keeping the fold in one place is the point; the
// two readers used to disagree, and the URL one never folded at all.
func applyOperationMessages(spec *APISpec, opID string, ws *WebSocketEndpoint, channel *shared.AsyncAPIChannel, operation *shared.AsyncAPIOperation, convert func(*shared.Schema) *Schema) {
if ws.MessageTypes == nil {
ws.MessageTypes = make(map[string]*Schema)
}

names, _ := ws.Metadata["messages"].(map[string]string)
if names == nil {
names = make(map[string]string)
ws.Metadata["messages"] = names
}

spokenMessages, unresolved := operationMessages(channel, operation)

// The fallback is a guess, and a wrong guess here produces a client that
// compiles and speaks the wrong message on one direction. Nothing about
// the output looks wrong, so this is the only place a reader finds out.
if unresolved && spec != nil {
spec.Warnings = append(spec.Warnings, fmt.Sprintf(
"operation %q lists messages, none of which resolve to a message of channel %q; "+
"it was folded as if it spoke the whole channel, so its direction may claim a message "+
"the other direction sends",
opID, channel.Address,
))
}

for _, spoken := range spokenMessages {
if spoken.msg.Payload == nil {
continue
}

schema := convert(spoken.msg.Payload)
ws.MessageTypes[spoken.key] = schema

switch operation.Action {
case "send":
if ws.SendSchema == nil {
ws.SendSchema = schema
}

if ws.SendMessages == nil {
ws.SendMessages = make(map[string]*Schema)
}

ws.SendMessages[spoken.key] = schema
case "receive":
if ws.ReceiveSchema == nil {
ws.ReceiveSchema = schema
}

if ws.ReceiveMessages == nil {
ws.ReceiveMessages = make(map[string]*Schema)
}

ws.ReceiveMessages[spoken.key] = schema
}

// A name the opposite direction already claimed stands. Two operations
// that both speak the whole channel otherwise relabel each other, and
// whichever sorted last owned every name -- which is how a duplex
// binding ended up with one direction empty. First claim wins, so the
// result no longer depends on operation-id sort order.
if claimed, ok := names[spoken.name]; ok && claimed != operation.Action {
continue
}

names[spoken.name] = operation.Action
}
}
4 changes: 2 additions & 2 deletions internal/client/generators/typescript/opsmanifest.go
Original file line number Diff line number Diff line change
Expand Up @@ -822,8 +822,8 @@ func (g *OpsManifestGenerator) writeStreams(buf *strings.Builder, spec *client.A
}

// duplexMessageNames picks the lowest-sorted message name for each direction,
// the same tie-break convertSchemaFromChannel uses, so the output is stable
// across runs.
// the same first-message tie-break applyOperationMessages uses for directional
// schemas, so the output is stable across runs.
func duplexMessageNames(metadata map[string]any) (string, string) {
names, _ := metadata["messages"].(map[string]string)
send, receive := "", ""
Expand Down
135 changes: 11 additions & 124 deletions internal/client/introspector.go
Original file line number Diff line number Diff line change
Expand Up @@ -313,32 +313,21 @@ func (i *Introspector) extractFromAsyncAPI(spec *APISpec, asyncAPI *shared.Async
isWebSocket := i.isWebSocketChannel(asyncAPI, channel)

if isWebSocket {
if idx, seen := wsSeen[channelName]; seen {
// The other direction of a channel already converted: fill
// the half this operation describes, if the first left it.
existing := &spec.WebSockets[idx]
named := operationMessageSchemas(channel, operation, i.convertSchema)

switch operation.Action {
case "send":
if existing.SendSchema == nil {
existing.SendSchema = i.firstPayload(channel)
}

existing.SendMessages = mergeMessageSchemas(existing.SendMessages, named)
case "receive":
if existing.ReceiveSchema == nil {
existing.ReceiveSchema = i.firstPayload(channel)
}

existing.ReceiveMessages = mergeMessageSchemas(existing.ReceiveMessages, named)
}
// Operations on one channel fold into one endpoint, the first
// operation naming it: a duplex channel is one socket with a send
// and a receive operation, not two sockets. The file reader has
// always folded this way; appending one endpoint per operation
// left neither half carrying both schemas, so a duplex channel
// reached through a URL source never became a duplex binding.
if existing, ok := wsSeen[channelName]; ok {
applyOperationMessages(spec, opID, &spec.WebSockets[existing], channel, operation, i.convertSchema)

continue
}

ws := i.channelToWebSocket(spec, opID, channel, operation)
wsSeen[channelName] = len(spec.WebSockets)
spec.WebSockets = append(spec.WebSockets, i.channelToWebSocket(spec, opID, channel, operation))
spec.WebSockets = append(spec.WebSockets, ws)
} else {
// Treat as SSE. channelToSSE reads every message on the channel,
// so a second operation has nothing left to add.
Expand All @@ -356,76 +345,6 @@ func (i *Introspector) extractFromAsyncAPI(spec *APISpec, asyncAPI *shared.Async
return nil
}

// operationMessageSchemas returns the schemas of the messages one operation
// names on a channel, keyed by message name. An operation that lists none is
// read as carrying every message on the channel, which is what the router's
// generator means when it writes one; a reference to a message the channel
// does not declare is skipped.
func operationMessageSchemas(
channel *shared.AsyncAPIChannel, operation *shared.AsyncAPIOperation, convert func(*shared.Schema) *Schema,
) map[string]*Schema {
names := make([]string, 0, len(operation.Messages))

for _, ref := range operation.Messages {
if i := strings.LastIndex(ref.Ref, "/"); i >= 0 && i < len(ref.Ref)-1 {
names = append(names, ref.Ref[i+1:])
}
}

if len(names) == 0 {
names = sortedStringKeys(channel.Messages)
}

var out map[string]*Schema

for _, name := range names {
msg := channel.Messages[name]
if msg == nil || msg.Payload == nil {
continue
}

if out == nil {
out = make(map[string]*Schema)
}

out[name] = convert(msg.Payload)
}

return out
}

// mergeMessageSchemas adds the messages of a second operation in the same
// direction to those already recorded, keeping the first schema for a name.
func mergeMessageSchemas(into, add map[string]*Schema) map[string]*Schema {
if len(add) == 0 {
return into
}

if into == nil {
into = make(map[string]*Schema, len(add))
}

for name, schema := range add {
if _, ok := into[name]; !ok {
into[name] = schema
}
}

return into
}

// firstPayload is the schema of a channel's lowest-named message, which is
// the one channelToWebSocket's last-write-wins loop settles on as well.
func (i *Introspector) firstPayload(channel *shared.AsyncAPIChannel) *Schema {
for _, name := range sortedStringKeys(channel.Messages) {
if msg := channel.Messages[name]; msg != nil && msg.Payload != nil {
return i.convertSchema(msg.Payload)
}
}

return nil
}

// isStreamingFeatureChannel checks if a channel is a streaming extension feature channel.
func (i *Introspector) isStreamingFeatureChannel(channelName string) bool {
streamingChannels := []string{"rooms", "channels", "presence", "typing"}
Expand Down Expand Up @@ -849,39 +768,7 @@ func (i *Introspector) channelToWebSocket(spec *APISpec, opID string, channel *s
Metadata: make(map[string]any),
}

// Extract send/receive schemas from messages, in sorted message-name order.
// SendSchema/ReceiveSchema below are last-write-wins, so a channel with
// several messages otherwise emitted a different type on each run.
for _, msgName := range sortedStringKeys(channel.Messages) {
if msg := channel.Messages[msgName]; msg.Payload != nil {
schema := i.convertSchema(msg.Payload)

// Store all message types
ws.MessageTypes[msgName] = schema

// Determine direction based on operation action
switch operation.Action {
case "send":
ws.SendSchema = schema
case "receive":
ws.ReceiveSchema = schema
}

// Store message name in metadata
if ws.Metadata["messages"] == nil {
ws.Metadata["messages"] = make(map[string]string)
}

ws.Metadata["messages"].(map[string]string)[msgName] = operation.Action
}
}

switch operation.Action {
case "send":
ws.SendMessages = operationMessageSchemas(channel, operation, i.convertSchema)
case "receive":
ws.ReceiveMessages = operationMessageSchemas(channel, operation, i.convertSchema)
}
applyOperationMessages(spec, opID, &ws, channel, operation, i.convertSchema)

ws.StreamBindings = streamBindings(channel.Extensions)
registerStreamBindingEntities(spec, channel.Address, ws.StreamBindings)
Expand Down
Loading
Loading