From 0504ba9e312b705d5947a55b635b31e4917d4d19 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Tue, 15 Sep 2026 09:51:47 -0500 Subject: [PATCH 1/5] fix(client): read a duplex channel's directions from the operations that speak them Both AsyncAPI readers stamped every message on a channel with each operation's action and took the last-sorted payload for the direction's schema. On forge's own live-query channel, where the receive operation sorts first, that named the send direction nothing, named receive by its key, and put the send payload in the receive schema. The URL reader also appended one endpoint per operation, so a duplex channel reached through a URL source never carried both schemas and never became a duplex binding. One fold now serves both readers: an operation contributes only the messages it references (all of them when it lists none), the first message per direction claims that direction's schema, and the messages metadata is keyed by message name so the generated binding says `send: 'SendMessage'`. --- internal/client/asyncapi_messages.go | 108 ++++++++++++++++++ internal/client/introspector.go | 42 +++---- .../client/introspector_client_meta_test.go | 24 ++++ internal/client/spec_parser.go | 45 +------- .../client/spec_parser_client_meta_test.go | 93 +++++++++++++++ 5 files changed, 244 insertions(+), 68 deletions(-) create mode 100644 internal/client/asyncapi_messages.go diff --git a/internal/client/asyncapi_messages.go b/internal/client/asyncapi_messages.go new file mode 100644 index 000000000..aeda475a7 --- /dev/null +++ b/internal/client/asyncapi_messages.go @@ -0,0 +1,108 @@ +package client + +import ( + "strings" + + "github.com/xraph/forge/internal/shared" +) + +// spokenMessage is one channel message an operation sends or receives. +type spokenMessage struct { + // key is the message's key under channels..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//messages/` 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) []spokenMessage { + wanted := make(map[string]struct{}) + + 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{}{} + } + } + } + } + + 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 +} + +// 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 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(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 + } + + for _, spoken := range operationMessages(channel, operation) { + 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 + } + case "receive": + if ws.ReceiveSchema == nil { + ws.ReceiveSchema = schema + } + } + + names[spoken.name] = operation.Action + } +} diff --git a/internal/client/introspector.go b/internal/client/introspector.go index 0f05d7a0d..a9815e419 100644 --- a/internal/client/introspector.go +++ b/internal/client/introspector.go @@ -250,6 +250,8 @@ func (i *Introspector) extractFromAsyncAPI(spec *APISpec, asyncAPI *shared.Async // Extract operations and map them to channels, in sorted operation-id // order -- this appends to spec.WebSockets/spec.SSEs, and the streaming // generators emit in that order. + wsByChannel := make(map[string]int) + for _, opID := range sortedStringKeys(asyncAPI.Operations) { operation := asyncAPI.Operations[opID] if operation == nil || operation.Channel == nil { @@ -278,7 +280,20 @@ func (i *Introspector) extractFromAsyncAPI(spec *APISpec, asyncAPI *shared.Async isWebSocket := i.isWebSocketChannel(asyncAPI, channel) if isWebSocket { + // 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 := wsByChannel[channelName]; ok { + applyOperationMessages(&spec.WebSockets[existing], channel, operation, i.convertSchema) + + continue + } + ws := i.channelToWebSocket(spec, opID, channel, operation) + wsByChannel[channelName] = len(spec.WebSockets) spec.WebSockets = append(spec.WebSockets, ws) } else { // Treat as SSE @@ -713,32 +728,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 - } - } + applyOperationMessages(&ws, channel, operation, i.convertSchema) ws.StreamBindings = streamBindings(channel.Extensions) registerStreamBindingEntities(spec, channel.Address, ws.StreamBindings) diff --git a/internal/client/introspector_client_meta_test.go b/internal/client/introspector_client_meta_test.go index 77ea21d3e..7a9a0c83a 100644 --- a/internal/client/introspector_client_meta_test.go +++ b/internal/client/introspector_client_meta_test.go @@ -2,6 +2,7 @@ package client import ( "context" + "encoding/json" "slices" "strings" "testing" @@ -802,3 +803,26 @@ func TestInvalidatesIsSilentForAValidList(t *testing.T) { t.Fatalf("Warnings = %v, want none for a valid list", spec.Warnings) } } + +// The URL path reads the same document through the introspector, which used +// to append one endpoint per operation: neither half carried both schemas, so +// a duplex channel reached through a URL source never became a duplex binding +// at all. Both readers must fold the operations the same way. +func TestIntrospectorDuplexChannelNamesEachDirectionFromItsOperation(t *testing.T) { + raw, err := json.Marshal(duplexAsyncAPIDocument()) + if err != nil { + t.Fatal(err) + } + + var asyncAPI shared.AsyncAPISpec + if err := json.Unmarshal(raw, &asyncAPI); err != nil { + t.Fatal(err) + } + + spec := &APISpec{Schemas: map[string]*Schema{}} + if err := (&Introspector{}).extractFromAsyncAPI(spec, &asyncAPI); err != nil { + t.Fatalf("extractFromAsyncAPI: %v", err) + } + + assertDuplexDirections(t, spec) +} diff --git a/internal/client/spec_parser.go b/internal/client/spec_parser.go index 2207e88f6..d712ad920 100644 --- a/internal/client/spec_parser.go +++ b/internal/client/spec_parser.go @@ -366,13 +366,8 @@ func (p *SpecParser) parseAsyncAPI(data []byte, isYAML bool) (*APISpec, error) { ws := convertWebSocketChannel(spec, opID, channel, operation) wsEndpoints[channelName] = &ws } else { - // Merge with existing endpoint - existing := wsEndpoints[channelName] - if operation.Action == "send" && existing.SendSchema == nil { - existing.SendSchema = convertSchemaFromChannel(channel, operation) - } else if operation.Action == "receive" && existing.ReceiveSchema == nil { - existing.ReceiveSchema = convertSchemaFromChannel(channel, operation) - } + // A later operation on the same channel folds its direction in. + applyOperationMessages(wsEndpoints[channelName], channel, operation, convertSchema) } } else { // Use channel name as key to merge operations on same channel @@ -408,20 +403,6 @@ func (p *SpecParser) parseAsyncAPI(data []byte, isYAML bool) (*APISpec, error) { // Helper conversion functions -func convertSchemaFromChannel(channel *shared.AsyncAPIChannel, operation *shared.AsyncAPIOperation) *Schema { - // Lowest message name wins rather than whichever the map happened to hand - // over first. A channel carrying several messages otherwise contributed a - // different send/receive schema on each run, and that schema is emitted as - // a named type in the generated client. - for _, name := range sortedStringKeys(channel.Messages) { - if msg := channel.Messages[name]; msg.Payload != nil { - return convertSchema(msg.Payload) - } - } - - return nil -} - func convertOperation(spec *APISpec, method, path string, op *shared.Operation) Endpoint { endpoint := Endpoint{ Method: method, @@ -823,27 +804,7 @@ func convertWebSocketChannel(spec *APISpec, opID string, channel *shared.AsyncAP Metadata: make(map[string]any), } - // Sorted, because the assignments below are last-write-wins: a channel - // declaring several messages otherwise left SendSchema holding whichever - // payload the map surrendered last, which changed run to run. - for _, msgName := range sortedStringKeys(channel.Messages) { - if msg := channel.Messages[msgName]; msg.Payload != nil { - schema := convertSchema(msg.Payload) - - switch operation.Action { - case "send": - ws.SendSchema = schema - case "receive": - ws.ReceiveSchema = schema - } - - if ws.Metadata["messages"] == nil { - ws.Metadata["messages"] = make(map[string]string) - } - - ws.Metadata["messages"].(map[string]string)[msgName] = operation.Action - } - } + applyOperationMessages(&ws, channel, operation, convertSchema) ws.StreamBindings = streamBindings(channel.Extensions) registerStreamBindingEntities(spec, channel.Address, ws.StreamBindings) diff --git a/internal/client/spec_parser_client_meta_test.go b/internal/client/spec_parser_client_meta_test.go index ab265a53e..6a5ad0696 100644 --- a/internal/client/spec_parser_client_meta_test.go +++ b/internal/client/spec_parser_client_meta_test.go @@ -376,3 +376,96 @@ func TestSpecParserSSEStreamBindingsFromFile(t *testing.T) { t.Fatalf("StreamBindings[0].Invalidates = %v, want [User[]]", b.Invalidates) } } + +// A duplex channel names each direction from the operation that speaks it. +// The document below is the shape forge's own router publishes: one message +// per direction keyed `send` and `receive`, each carrying a `name`, and one +// operation per direction referencing its message. Before this test the +// parser stamped every message with the first operation's action, so the +// send direction went unnamed, and it took the last-sorted payload for both +// schemas, so the receive schema was the send payload. +func TestSpecParserDuplexChannelNamesEachDirectionFromItsOperation(t *testing.T) { + path := writeSpec(t, duplexAsyncAPIDocument()) + + spec, err := NewSpecParser().ParseFile(context.Background(), path) + if err != nil { + t.Fatalf("ParseFile: %v", err) + } + + assertDuplexDirections(t, spec) +} + +// duplexAsyncAPIDocument is the live-query channel as forge's router emits it: +// operation ids sort the receive operation first, which is the order that +// exposed the bug. +func duplexAsyncAPIDocument() map[string]any { + return map[string]any{ + "asyncapi": "3.0.0", + "info": map[string]any{"title": "Live", "version": "1.0.0"}, + "servers": map[string]any{ + "main": map[string]any{"host": "ws.example.com", "protocol": "wss"}, + }, + "channels": map[string]any{ + "liveQueryWS": map[string]any{ + "address": "/api/v1/query/live/ws", + "servers": []any{map[string]any{"$ref": "#/servers/main"}}, + "messages": map[string]any{ + "receive": map[string]any{ + "name": "ReceiveMessage", + "payload": map[string]any{ + "type": "object", + "properties": map[string]any{"type": map[string]any{"type": "string"}}, + }, + }, + "send": map[string]any{ + "name": "SendMessage", + "payload": map[string]any{ + "type": "object", + "properties": map[string]any{"action": map[string]any{"type": "string"}}, + }, + }, + }, + }, + }, + "operations": map[string]any{ + "query.live.wsReceive": map[string]any{ + "action": "receive", + "channel": map[string]any{"$ref": "#/channels/liveQueryWS"}, + "messages": []any{map[string]any{"$ref": "#/channels/liveQueryWS/messages/receive"}}, + }, + "query.live.wsSend": map[string]any{ + "action": "send", + "channel": map[string]any{"$ref": "#/channels/liveQueryWS"}, + "messages": []any{map[string]any{"$ref": "#/channels/liveQueryWS/messages/send"}}, + }, + }, + } +} + +// assertDuplexDirections checks the one endpoint both parsers should produce +// from duplexAsyncAPIDocument: one WebSocket, the send schema carrying the +// send payload, the receive schema the receive payload, and the messages +// metadata keyed by message NAME so the generated binding can say +// `send: 'SendMessage'` rather than an empty string. +func assertDuplexDirections(t *testing.T, spec *APISpec) { + t.Helper() + + if len(spec.WebSockets) != 1 { + t.Fatalf("WebSockets = %d, want the two operations folded into 1", len(spec.WebSockets)) + } + + ws := spec.WebSockets[0] + + if ws.SendSchema == nil || ws.SendSchema.Properties["action"] == nil { + t.Errorf("SendSchema = %+v, want the send message payload (has `action`)", ws.SendSchema) + } + + if ws.ReceiveSchema == nil || ws.ReceiveSchema.Properties["type"] == nil { + t.Errorf("ReceiveSchema = %+v, want the receive message payload (has `type`)", ws.ReceiveSchema) + } + + names, _ := ws.Metadata["messages"].(map[string]string) + if names["SendMessage"] != "send" || names["ReceiveMessage"] != "receive" || len(names) != 2 { + t.Errorf("Metadata[messages] = %v, want {SendMessage: send, ReceiveMessage: receive}", names) + } +} From 2b7b3b1bc9390b765b5a6ab4890a6ebdd76aff1a Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Tue, 15 Sep 2026 10:07:02 -0500 Subject: [PATCH 2/5] fix(client-core): let a caller holding cache.live speak on a duplex channel `cache.live` is typed as the structural LiveBinding, and 1.11.0 declared it without `raw`, so an application's stream helper had to cast to the binder class to reach the one method the duplex work added. The interface now carries `raw` with the same signature as StreamBinder.raw; the type import is erased, so the REST-only bundle does not grow. --- .../__tests__/duplex-binding.test.ts | 22 ++++++++++++++++++- packages/client-core/src/cache.ts | 10 +++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/packages/client-core/__tests__/duplex-binding.test.ts b/packages/client-core/__tests__/duplex-binding.test.ts index c11ac0dc9..77fce17ff 100644 --- a/packages/client-core/__tests__/duplex-binding.test.ts +++ b/packages/client-core/__tests__/duplex-binding.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'; import { QueryCache } from '../src/cache'; import { manualScheduler } from '../src/invalidate'; +import type { LiveBinding } from '../src/cache'; import { binderSnapshot, StreamBinder } from '../src/live'; import { SubscriptionManager } from '../src/stream'; import type { StreamBinding } from '../src/stream'; @@ -25,7 +26,7 @@ function build() { }); const binder = new StreamBinder({ cache, streams, manager, scheduler: (flush) => flush(), sleep: clock.sleep }); - return { binder, sockets, manager }; + return { binder, cache, sockets, manager }; } describe('a duplex channel', () => { @@ -52,6 +53,25 @@ describe('a duplex channel', () => { ]); }); + // Guards that a caller holding only what the cache exposes can speak. + // `cache.live` is typed as the structural `LiveBinding`, not the binder + // class, and an application's stream helper reaches the socket through it; + // a `raw` that lives on the class alone forces every such caller to cast. + it('is reachable through the LiveBinding the cache exposes', () => { + const { cache, sockets } = build(); + const live: LiveBinding | undefined = cache.live; + + if (live === undefined) { + throw new Error('the binder did not attach itself to the cache'); + } + + const release = live.raw('/api/v1/query/live/ws', () => {}, { hello: { action: 'subscribe' } }); + sockets.last().open(); + + expect(sockets.last().sent).toEqual([{ action: 'subscribe' }]); + release(); + }); + // Guards the generated table as the single source of channel names. it('refuses a channel that is not a duplex binding', () => { const { binder } = build(); diff --git a/packages/client-core/src/cache.ts b/packages/client-core/src/cache.ts index a5d4d6979..fc0dcc3fe 100644 --- a/packages/client-core/src/cache.ts +++ b/packages/client-core/src/cache.ts @@ -6,6 +6,7 @@ import type { OptimisticSpec } from './overlay.js'; import { QueryRegistry } from './registry.js'; import type { QueryEntry, QuerySpec, Unmount } from './registry.js'; import { EntityStore } from './store.js'; +import type { SubscribeOptions } from './stream.js'; import type { StagedWrite } from './store.js'; import { queryKey, resolveTags } from './tags.js'; import type { TagContext } from './tags.js'; @@ -153,6 +154,15 @@ export interface LiveBinding { subscribe(meta: OperationMeta, args?: TagContext): () => void; /** Which channels this operation's entities are pushed on. */ channelsFor(meta: OperationMeta): readonly string[]; + /** + * Subscribe to a declared duplex channel and take its frames raw. See + * `StreamBinder.raw`. + * + * Declared here so a caller holding only `cache.live` can speak on a + * socket without importing the binder class, which is the whole reason + * this interface exists. + */ + raw(channel: string, handler: (message: unknown) => void, options?: SubscribeOptions): () => void; } /** From 951b9c6f39fe1f9a356b76350d511b4257003681 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Tue, 15 Sep 2026 10:41:07 -0500 Subject: [PATCH 3/5] fix(client): resolve component message refs before speaking a whole channel An operation that lists `messages` and resolves none of them to the channel fell back to speaking every message the channel declares, and then both operations did, and the fold labelled each name with whichever action came last. That is the empty send direction this PR exists to remove, arriving by a different road and without a word of warning. AsyncAPI 3 says those refs point at the channel's own messages and forge's router writes them that way, but other generators write #/components/messages/send and leave the channel to carry the definition. The trailing segment of the ref is the channel's key there, so try it when the strict read comes back with nothing. It has to be a key the channel actually declares, so this can only narrow the fallback, never invent a message. When the fallback still engages for an operation that did list refs, the spec now carries a warning naming the operation and the channel. applyOperationMessages takes the spec and the operation id to do it, which both readers already had in hand. And a name claimed by one direction is no longer relabelled by the other, so two operations that legitimately speak the whole channel stop taking the names back from each other and the result no longer depends on operation-id sort order. --- internal/client/asyncapi_messages.go | 52 +++++++++- internal/client/introspector.go | 4 +- .../client/introspector_client_meta_test.go | 63 ++++++++++++ internal/client/spec_parser.go | 4 +- .../client/spec_parser_client_meta_test.go | 95 +++++++++++++++++++ 5 files changed, 210 insertions(+), 8 deletions(-) diff --git a/internal/client/asyncapi_messages.go b/internal/client/asyncapi_messages.go index aeda475a7..05b7531a2 100644 --- a/internal/client/asyncapi_messages.go +++ b/internal/client/asyncapi_messages.go @@ -1,6 +1,7 @@ package client import ( + "fmt" "strings" "github.com/xraph/forge/internal/shared" @@ -28,8 +29,9 @@ type spokenMessage struct { // 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) []spokenMessage { +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/" @@ -43,6 +45,25 @@ func operationMessages(channel *shared.AsyncAPIChannel, operation *shared.AsyncA } } + // 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. + if listed && len(wanted) == 0 { + for _, ref := range operation.Messages { + key := ref.Ref[strings.LastIndex(ref.Ref, "/")+1:] + if _, declared := channel.Messages[key]; declared { + wanted[key] = struct{}{} + } + } + } + out := make([]spokenMessage, 0, len(channel.Messages)) for _, key := range sortedStringKeys(channel.Messages) { @@ -60,7 +81,7 @@ func operationMessages(channel *shared.AsyncAPIChannel, operation *shared.AsyncA out = append(out, spokenMessage{key: key, name: name, msg: msg}) } - return out + return out, listed && len(wanted) == 0 } // applyOperationMessages records one operation's direction on the endpoint: @@ -73,7 +94,7 @@ func operationMessages(channel *shared.AsyncAPIChannel, operation *shared.AsyncA // 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(ws *WebSocketEndpoint, channel *shared.AsyncAPIChannel, operation *shared.AsyncAPIOperation, convert func(*shared.Schema) *Schema) { +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) } @@ -84,7 +105,21 @@ func applyOperationMessages(ws *WebSocketEndpoint, channel *shared.AsyncAPIChann ws.Metadata["messages"] = names } - for _, spoken := range operationMessages(channel, operation) { + 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 } @@ -103,6 +138,15 @@ func applyOperationMessages(ws *WebSocketEndpoint, channel *shared.AsyncAPIChann } } + // 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 } } diff --git a/internal/client/introspector.go b/internal/client/introspector.go index a9815e419..90abcebe7 100644 --- a/internal/client/introspector.go +++ b/internal/client/introspector.go @@ -287,7 +287,7 @@ func (i *Introspector) extractFromAsyncAPI(spec *APISpec, asyncAPI *shared.Async // left neither half carrying both schemas, so a duplex channel // reached through a URL source never became a duplex binding. if existing, ok := wsByChannel[channelName]; ok { - applyOperationMessages(&spec.WebSockets[existing], channel, operation, i.convertSchema) + applyOperationMessages(spec, opID, &spec.WebSockets[existing], channel, operation, i.convertSchema) continue } @@ -728,7 +728,7 @@ func (i *Introspector) channelToWebSocket(spec *APISpec, opID string, channel *s Metadata: make(map[string]any), } - applyOperationMessages(&ws, channel, operation, i.convertSchema) + applyOperationMessages(spec, opID, &ws, channel, operation, i.convertSchema) ws.StreamBindings = streamBindings(channel.Extensions) registerStreamBindingEntities(spec, channel.Address, ws.StreamBindings) diff --git a/internal/client/introspector_client_meta_test.go b/internal/client/introspector_client_meta_test.go index 7a9a0c83a..8b938de0b 100644 --- a/internal/client/introspector_client_meta_test.go +++ b/internal/client/introspector_client_meta_test.go @@ -826,3 +826,66 @@ func TestIntrospectorDuplexChannelNamesEachDirectionFromItsOperation(t *testing. assertDuplexDirections(t, spec) } + +// The same hardening through the URL reader. Both readers share the fold, but +// only this one passes its own spec and operation id into it, and a warning +// that names the wrong operation (or lands on no spec at all) is worth +// nothing. So the component-ref resolution and the warning are checked here +// as well as through the file parser. +func TestIntrospectorFoldResolvesComponentRefsAndWarnsWhenItCannot(t *testing.T) { + parse := func(t *testing.T, doc map[string]any) *APISpec { + t.Helper() + + raw, err := json.Marshal(doc) + if err != nil { + t.Fatal(err) + } + + var asyncAPI shared.AsyncAPISpec + if err := json.Unmarshal(raw, &asyncAPI); err != nil { + t.Fatal(err) + } + + spec := &APISpec{Schemas: map[string]*Schema{}} + if err := (&Introspector{}).extractFromAsyncAPI(spec, &asyncAPI); err != nil { + t.Fatalf("extractFromAsyncAPI: %v", err) + } + + return spec + } + + pointOperationsAt := func(doc map[string]any, ref func(action string) string) map[string]any { + operations, _ := doc["operations"].(map[string]any) + for id, action := range map[string]string{"query.live.wsReceive": "receive", "query.live.wsSend": "send"} { + operation, _ := operations[id].(map[string]any) + operation["messages"] = []any{map[string]any{"$ref": ref(action)}} + } + + return doc + } + + resolvable := parse(t, pointOperationsAt(duplexAsyncAPIDocument(), func(action string) string { + return "#/components/messages/" + action + })) + assertDuplexDirections(t, resolvable) + + if len(resolvable.Warnings) != 0 { + t.Errorf("Warnings = %v, want none for refs this fold could resolve", resolvable.Warnings) + } + + unresolvable := parse(t, pointOperationsAt(duplexAsyncAPIDocument(), func(string) string { + return "#/components/messages/nothingNamedThis" + })) + + var named bool + + for _, warning := range unresolvable.Warnings { + if strings.Contains(warning, "query.live.wsSend") && strings.Contains(warning, "/api/v1/query/live/ws") { + named = true + } + } + + if !named { + t.Errorf("Warnings = %v, want one naming the operation and the channel", unresolvable.Warnings) + } +} diff --git a/internal/client/spec_parser.go b/internal/client/spec_parser.go index d712ad920..e0ffcbf2e 100644 --- a/internal/client/spec_parser.go +++ b/internal/client/spec_parser.go @@ -367,7 +367,7 @@ func (p *SpecParser) parseAsyncAPI(data []byte, isYAML bool) (*APISpec, error) { wsEndpoints[channelName] = &ws } else { // A later operation on the same channel folds its direction in. - applyOperationMessages(wsEndpoints[channelName], channel, operation, convertSchema) + applyOperationMessages(spec, opID, wsEndpoints[channelName], channel, operation, convertSchema) } } else { // Use channel name as key to merge operations on same channel @@ -804,7 +804,7 @@ func convertWebSocketChannel(spec *APISpec, opID string, channel *shared.AsyncAP Metadata: make(map[string]any), } - applyOperationMessages(&ws, channel, operation, convertSchema) + applyOperationMessages(spec, opID, &ws, channel, operation, convertSchema) ws.StreamBindings = streamBindings(channel.Extensions) registerStreamBindingEntities(spec, channel.Address, ws.StreamBindings) diff --git a/internal/client/spec_parser_client_meta_test.go b/internal/client/spec_parser_client_meta_test.go index 6a5ad0696..133d81fb8 100644 --- a/internal/client/spec_parser_client_meta_test.go +++ b/internal/client/spec_parser_client_meta_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "os" "path/filepath" + "strings" "testing" ) @@ -469,3 +470,97 @@ func assertDuplexDirections(t *testing.T, spec *APISpec) { t.Errorf("Metadata[messages] = %v, want {SendMessage: send, ReceiveMessage: receive}", names) } } + +// AsyncAPI 3 says an operation's `messages` must reference the channel's own +// messages, and forge's router obeys that. Other generators do not: they point +// at `#/components/messages/` and leave the channel to carry the +// definition. That document used to resolve no reference at all, fall back to +// "this operation speaks the whole channel" for both operations, and stamp +// every message name with each action in turn, which is the unnamed send +// direction this fold exists to prevent. The trailing segment of the +// reference is the channel's key here, so resolve it. +func TestOperationMessagesResolveComponentRefsByTrailingSegment(t *testing.T) { + doc := duplexAsyncAPIDocument() + operations, _ := doc["operations"].(map[string]any) + + for id, action := range map[string]string{"query.live.wsReceive": "receive", "query.live.wsSend": "send"} { + operation, _ := operations[id].(map[string]any) + operation["messages"] = []any{map[string]any{"$ref": "#/components/messages/" + action}} + } + + spec, err := NewSpecParser().ParseFile(context.Background(), writeSpec(t, doc)) + if err != nil { + t.Fatalf("ParseFile: %v", err) + } + + assertDuplexDirections(t, spec) +} + +// When the references resolve to nothing at all the fold still has to produce +// something, and speaking the whole channel is the only answer available. It +// is also the answer that silently mislabels both directions, so it says so: +// a client generated from that document is wrong in a way nothing about it +// looks wrong, and the warning is the only place a reader finds out. +func TestOperationMessagesWarnWhenListedRefsResolveToNothing(t *testing.T) { + doc := duplexAsyncAPIDocument() + operations, _ := doc["operations"].(map[string]any) + + for _, id := range []string{"query.live.wsReceive", "query.live.wsSend"} { + operation, _ := operations[id].(map[string]any) + operation["messages"] = []any{map[string]any{"$ref": "#/components/messages/nothingNamedThis"}} + } + + spec, err := NewSpecParser().ParseFile(context.Background(), writeSpec(t, doc)) + if err != nil { + t.Fatalf("ParseFile: %v", err) + } + + var found string + + for _, warning := range spec.Warnings { + if strings.Contains(warning, "query.live.wsSend") { + found = warning + } + } + + if found == "" { + t.Fatalf("Warnings = %v, want one naming the operation whose message refs resolved to nothing", spec.Warnings) + } + + if !strings.Contains(found, "/api/v1/query/live/ws") { + t.Errorf("warning = %q, want it to name the channel as well as the operation", found) + } +} + +// An operation that lists no messages legitimately speaks the whole channel, +// and that is how every document written before operations carried `messages` +// reads. Two such operations both claim every message, and the fold used to +// let the later one relabel what the earlier had already claimed: whichever +// operation sorted last owned every name, so one direction ended up empty in +// the generated binding. A claim by the opposite direction stands. +func TestWholeChannelFallbackDoesNotRelabelAClaimedDirection(t *testing.T) { + doc := duplexAsyncAPIDocument() + operations, _ := doc["operations"].(map[string]any) + + for _, id := range []string{"query.live.wsReceive", "query.live.wsSend"} { + operation, _ := operations[id].(map[string]any) + delete(operation, "messages") + } + + spec, err := NewSpecParser().ParseFile(context.Background(), writeSpec(t, doc)) + if err != nil { + t.Fatalf("ParseFile: %v", err) + } + + if len(spec.WebSockets) != 1 { + t.Fatalf("WebSockets = %d, want 1", len(spec.WebSockets)) + } + + names, _ := spec.WebSockets[0].Metadata["messages"].(map[string]string) + + // query.live.wsReceive sorts first and claims both names; the send + // operation must not take them back. + if names["ReceiveMessage"] != "receive" { + t.Errorf("Metadata[messages] = %v, want ReceiveMessage still claimed by the receive operation", names) + } +} From 661ac17fc6c9b73c9742806fdf7e86fec6cbdde7 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Tue, 15 Sep 2026 10:41:07 -0500 Subject: [PATCH 4/5] fix(client-core): give LiveBinding.raw the handler type StreamBinder.raw takes The interface typed the handler as (message: unknown) => void while the class takes a FrameHandler, which is (message, channel). Method bivariance means the narrow spelling compiles and the runtime is unaffected: the channel arrives either way. The caller is what breaks. Anyone reaching the socket through cache.live, which is the reason this interface exists at all, receives the channel a frame came on and cannot see it in the type, so on a socket multiplexing more than one channel they either cast or guess. --- .../__tests__/duplex-binding.test.ts | 18 +++++++++++++++++- packages/client-core/src/cache.ts | 10 ++++++++-- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/packages/client-core/__tests__/duplex-binding.test.ts b/packages/client-core/__tests__/duplex-binding.test.ts index 77fce17ff..619ffeaee 100644 --- a/packages/client-core/__tests__/duplex-binding.test.ts +++ b/packages/client-core/__tests__/duplex-binding.test.ts @@ -65,10 +65,26 @@ describe('a duplex channel', () => { throw new Error('the binder did not attach itself to the cache'); } - const release = live.raw('/api/v1/query/live/ws', () => {}, { hello: { action: 'subscribe' } }); + const seen: [unknown, string][] = []; + const release = live.raw( + '/api/v1/query/live/ws', + // Typed by the interface, not annotated here: `channel` exists at + // runtime whichever way the handler is declared, so the only thing that + // can go wrong is the TYPE losing it and a caller through `cache.live` + // silently not knowing which of a socket's channels a frame came on. + // `npm run typecheck` is the other half of this assertion. + (message, channel) => { + seen.push([message, channel]); + }, + { hello: { action: 'subscribe' } }, + ); sockets.last().open(); expect(sockets.last().sent).toEqual([{ action: 'subscribe' }]); + + sockets.last().deliver({ type: 'update', id: 'q1' }); + + expect(seen).toEqual([[{ type: 'update', id: 'q1' }, '/api/v1/query/live/ws']]); release(); }); diff --git a/packages/client-core/src/cache.ts b/packages/client-core/src/cache.ts index fc0dcc3fe..05306406a 100644 --- a/packages/client-core/src/cache.ts +++ b/packages/client-core/src/cache.ts @@ -6,7 +6,7 @@ import type { OptimisticSpec } from './overlay.js'; import { QueryRegistry } from './registry.js'; import type { QueryEntry, QuerySpec, Unmount } from './registry.js'; import { EntityStore } from './store.js'; -import type { SubscribeOptions } from './stream.js'; +import type { FrameHandler, SubscribeOptions } from './stream.js'; import type { StagedWrite } from './store.js'; import { queryKey, resolveTags } from './tags.js'; import type { TagContext } from './tags.js'; @@ -161,8 +161,14 @@ export interface LiveBinding { * Declared here so a caller holding only `cache.live` can speak on a * socket without importing the binder class, which is the whole reason * this interface exists. + * + * `FrameHandler` rather than a one-argument handler spelled out here, and + * the same type `StreamBinder.raw` takes. Method bivariance makes the + * narrower spelling compile either way, so nothing breaks at runtime: what + * breaks is the caller, who receives the channel a frame arrived on and + * cannot see it in the type. */ - raw(channel: string, handler: (message: unknown) => void, options?: SubscribeOptions): () => void; + raw(channel: string, handler: FrameHandler, options?: SubscribeOptions): () => void; } /** From df13a23659a759f2e2859a2c8ac391e3b435790c Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Tue, 15 Sep 2026 10:55:54 -0500 Subject: [PATCH 5/5] fix(client): only a components reference resolves by its trailing segment The second resolution pass took the last path segment of any operation message reference as a key on this channel. A reference into another channel's messages shares the key vocabulary, so it bound a direction to the wrong message with no warning. The pass now applies to #/components/messages/ references only; anything else that resolves nothing takes the whole-channel fallback and its warning. --- internal/client/asyncapi_messages.go | 14 +++++++- .../client/spec_parser_client_meta_test.go | 32 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/internal/client/asyncapi_messages.go b/internal/client/asyncapi_messages.go index 05b7531a2..064a87527 100644 --- a/internal/client/asyncapi_messages.go +++ b/internal/client/asyncapi_messages.go @@ -7,6 +7,10 @@ import ( "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..messages. @@ -55,9 +59,17 @@ func operationMessages(channel *shared.AsyncAPIChannel, operation *shared.AsyncA // 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 := ref.Ref[strings.LastIndex(ref.Ref, "/")+1:] + key, ok := strings.CutPrefix(ref.Ref, componentMessagesPrefix) + if !ok { + continue + } + if _, declared := channel.Messages[key]; declared { wanted[key] = struct{}{} } diff --git a/internal/client/spec_parser_client_meta_test.go b/internal/client/spec_parser_client_meta_test.go index 133d81fb8..4eb4c5d00 100644 --- a/internal/client/spec_parser_client_meta_test.go +++ b/internal/client/spec_parser_client_meta_test.go @@ -564,3 +564,35 @@ func TestWholeChannelFallbackDoesNotRelabelAClaimedDirection(t *testing.T) { t.Errorf("Metadata[messages] = %v, want ReceiveMessage still claimed by the receive operation", names) } } + +// The trailing-segment pass is for `#/components/messages/` and nothing +// else. A reference into ANOTHER channel's messages shares the key vocabulary +// (`send`, `receive`) with this one, and reading its last segment as this +// channel's key would bind a direction to the wrong message with no warning. +// Such a reference resolves nothing here, the whole-channel fallback engages, +// and the warning says so. +func TestOperationMessagesDoNotResolveAnotherChannelsMessageByName(t *testing.T) { + doc := duplexAsyncAPIDocument() + operations, _ := doc["operations"].(map[string]any) + + for id, action := range map[string]string{"query.live.wsReceive": "receive", "query.live.wsSend": "send"} { + operation, _ := operations[id].(map[string]any) + operation["messages"] = []any{map[string]any{"$ref": "#/channels/otherChannel/messages/" + action}} + } + + spec, err := NewSpecParser().ParseFile(context.Background(), writeSpec(t, doc)) + if err != nil { + t.Fatalf("ParseFile: %v", err) + } + + warned := false + for _, w := range spec.Warnings { + if strings.Contains(w, "query.live.wsSend") { + warned = true + } + } + + if !warned { + t.Fatalf("a reference into another channel resolved as this channel's message; warnings = %v", spec.Warnings) + } +}