diff --git a/internal/client/asyncapi_messages.go b/internal/client/asyncapi_messages.go new file mode 100644 index 000000000..a353ade85 --- /dev/null +++ b/internal/client/asyncapi_messages.go @@ -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..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) (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 + } +} diff --git a/internal/client/generators/typescript/opsmanifest.go b/internal/client/generators/typescript/opsmanifest.go index 3d575e47b..907ae5d49 100644 --- a/internal/client/generators/typescript/opsmanifest.go +++ b/internal/client/generators/typescript/opsmanifest.go @@ -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 := "", "" diff --git a/internal/client/introspector.go b/internal/client/introspector.go index e833a63f1..2a7b1d182 100644 --- a/internal/client/introspector.go +++ b/internal/client/introspector.go @@ -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. @@ -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"} @@ -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) diff --git a/internal/client/introspector_client_meta_test.go b/internal/client/introspector_client_meta_test.go index 2f9b33eb1..b702cf029 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" @@ -1067,3 +1068,89 @@ func TestIntrospectRecordsEachMessagePerDirection(t *testing.T) { t.Errorf("ReceiveMessages = %v, want [said]", got) } } + +// 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) +} + +// 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 4cd0bae5f..e2d8f1f93 100644 --- a/internal/client/spec_parser.go +++ b/internal/client/spec_parser.go @@ -379,24 +379,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] - named := operationMessageSchemas(channel, operation, convertSchema) - - switch operation.Action { - case "send": - if existing.SendSchema == nil { - existing.SendSchema = convertSchemaFromChannel(channel, operation) - } - - existing.SendMessages = mergeMessageSchemas(existing.SendMessages, named) - case "receive": - if existing.ReceiveSchema == nil { - existing.ReceiveSchema = convertSchemaFromChannel(channel, operation) - } - - existing.ReceiveMessages = mergeMessageSchemas(existing.ReceiveMessages, named) - } + // A later operation on the same channel folds its direction in. + applyOperationMessages(spec, opID, wsEndpoints[channelName], channel, operation, convertSchema) } } else { // Use channel name as key to merge operations on same channel @@ -436,20 +420,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, @@ -851,34 +821,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 - } - } - - switch operation.Action { - case "send": - ws.SendMessages = operationMessageSchemas(channel, operation, convertSchema) - case "receive": - ws.ReceiveMessages = operationMessageSchemas(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 ab265a53e..0df6d58f8 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" ) @@ -376,3 +377,223 @@ 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) + } +} + +// 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) + } +} + +// 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) + } +} diff --git a/packages/client-core/__tests__/duplex-binding.test.ts b/packages/client-core/__tests__/duplex-binding.test.ts index c11ac0dc9..619ffeaee 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,41 @@ 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 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(); + }); + // 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 489e56094..a4b41ee94 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 { FrameHandler, 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,21 @@ 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. + * + * `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: FrameHandler, options?: SubscribeOptions): () => void; } /**