diff --git a/internal/sidekick/swift/annotate_method.go b/internal/sidekick/swift/annotate_method.go index bda7ab7051..d1ad1fba65 100644 --- a/internal/sidekick/swift/annotate_method.go +++ b/internal/sidekick/swift/annotate_method.go @@ -279,20 +279,32 @@ func (c *codec) annotateMethod(method *api.Method, modelAnn *modelAnnotations) e // Extract routing parameters for gRPC per AIP-4222: // - Prefer explicit google.api.routing annotations if present. // - Fall back to extracting path parameters across all google.api.http bindings. - if method.HasRouting() { - routingParams = c.routingParamsFromRouting(method.Routing()) - } else if len(bindings) > 0 { - routingParams = c.routingParamsFromBindings(bindings) + if c.isGrpc() { + if method.HasRouting() { + routingParams, err = c.routingParamsFromRouting(method.InputType(), method.Routing()) + if err != nil { + return err + } + } else if len(bindings) > 0 { + routingParams, err = c.routingParamsFromBindings(method.InputType(), bindings) + if err != nil { + return err + } + } } // In Protobuf APIs (such as Storage Control or pure gRPC services), some RPC // methods do not define google.api.http annotations. // - HTTP/REST methods: Extract httpMethod, pathExpressionStr, bodyField, // queryParams, and pathVariables as before. - // - Pure gRPC methods (without HTTP annotations): Safely bypass the HTTP - // extraction without crashing, leaving those fields as their default zero values. + // - Pure gRPC methods (or gRPC clients): Safely bypass REST path binding + // extraction, while preserving primary HTTPMethod for idempotency checks. var pathBindings []*pathBindingAnnotations - if len(bindings) > 0 { + if len(bindings) > 0 && c.isGrpc() { + if bindings[0] != nil { + httpMethod = bindings[0].Verb() + } + } else if len(bindings) > 0 { hasBody = method.PathInfo().BodyFieldPath() != "" isBodyWildcard = method.PathInfo().BodyFieldPath() == "*" if hasBody && !isBodyWildcard { diff --git a/internal/sidekick/swift/annotate_method_routing_test.go b/internal/sidekick/swift/annotate_method_routing_test.go new file mode 100644 index 0000000000..b4ee42d874 --- /dev/null +++ b/internal/sidekick/swift/annotate_method_routing_test.go @@ -0,0 +1,258 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package swift + +import ( + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/googleapis/librarian/internal/config" + "github.com/googleapis/librarian/internal/sidekick/api" +) + +func TestAnnotateMethod_RoutingFieldTypes(t *testing.T) { + extEnum := api.NewTestEnum("ExtMode"). + WithPackage("google.type"). + WithValues( + api.NewTestEnumValue("EXT_MODE_UNSPECIFIED", 0), + api.NewTestEnumValue("EXT_MODE_FAST", 1), + ) + inputType := api.NewTestMessage("RouteRequest"). + WithPackage("google.cloud.test.v1"). + WithFields( + api.NewTestField("name").WithType(api.TypezString), + api.NewTestField("page_size").WithType(api.TypezInt32), + api.NewTestField("ext_mode").WithEnumType(extEnum), + ) + outputType := api.NewTestMessage("RouteResponse"). + WithPackage("google.cloud.test.v1") + + httpScalarMethod := api.NewTestMethod("GetTarget"). + WithInput(inputType). + WithOutput(outputType). + WithVerb("GET"). + WithPathTemplate( + api.NewPathTemplateBuilder(). + WithLiteral("v1"). + WithVariableNamed("name"). + WithVariableNamed("page_size"). + Build(), + ) + + explicitExtMethod := api.NewTestMethod("RouteExternal"). + WithInput(inputType). + WithOutput(outputType). + WithVerb("POST"). + WithPathTemplate(api.NewPathTemplateBuilder().WithLiteral("v1").WithLiteral("route").Build()). + WithRouting( + api.NewTestRoutingInfo("mode", api.NewTestRoutingInfoVariant("ext_mode")), + api.NewTestRoutingInfo("count", api.NewTestRoutingInfoVariant("page_size")), + ) + + service := api.NewTestService("TestService"). + WithPackage("google.cloud.test.v1"). + WithMethods(httpScalarMethod, explicitExtMethod) + model := api.NewTestAPI([]*api.Message{inputType, outputType}, []*api.Enum{extEnum}, []*api.Service{service}). + WithPackageName("google.cloud.test.v1") + if err := api.CrossReference(model); err != nil { + t.Fatal(err) + } + + library := &config.Library{ + Name: "google-cloud-test-v1", + Swift: swiftConfig(t, []config.SwiftDependency{ + {Name: "GoogleType", ApiPackage: "google.type"}, + }), + } + module := &config.SwiftModule{ + ModuleType: "grpc-client", + ModulePath: "TestProtos", + } + c, err := newCodec(model, library, module, t.TempDir()) + if err != nil { + t.Fatal(err) + } + if err := c.annotateModel(); err != nil { + t.Fatal(err) + } + + gotHTTP := httpScalarMethod.Codec().(*methodAnnotations) + if len(gotHTTP.PathBindings) != 0 { + t.Errorf("grpc-client PathBindings = %d, want 0", len(gotHTTP.PathBindings)) + } + if gotHTTP.HTTPMethod != "GET" || !gotHTTP.Idempotent() { + t.Errorf("got HTTPMethod=%q Idempotent()=%v, want GET / true", gotHTTP.HTTPMethod, gotHTTP.Idempotent()) + } + wantHTTPParams := []*routingParam{ + { + RoutingKey: "name", + Variants: []*routingParamVariant{ + { + FieldSteps: []*routingFieldStep{{PropertyName: "name"}}, + MatchingSegments: []string{".multiWildcard"}, + Last: true, + }, + }, + }, + { + RoutingKey: "page_size", + Variants: []*routingParamVariant{ + { + FieldSteps: []*routingFieldStep{{PropertyName: "pageSize"}}, + ConvertToString: true, + MatchingSegments: []string{".multiWildcard"}, + Last: true, + }, + }, + }, + } + if diff := cmp.Diff(wantHTTPParams, gotHTTP.RoutingParams); diff != "" { + t.Errorf("httpScalarMethod.RoutingParams mismatch (-want +got):\n%s", diff) + } + + svcAnn := service.Codec().(*serviceAnnotations) + if diff := cmp.Diff([]string{"GoogleType"}, svcAnn.ServiceImports()); diff != "" { + t.Errorf("service.ServiceImports() mismatch (-want +got):\n%s", diff) + } + + gotExplicit := explicitExtMethod.Codec().(*methodAnnotations) + wantExplicitParams := []*routingParam{ + { + RoutingKey: "mode", + Variants: []*routingParamVariant{ + { + FieldSteps: []*routingFieldStep{{PropertyName: "extMode"}}, + IsEnum: true, + RequiredPackages: []string{"google.type"}, + Last: true, + }, + }, + }, + { + RoutingKey: "count", + Variants: []*routingParamVariant{ + { + FieldSteps: []*routingFieldStep{{PropertyName: "pageSize"}}, + ConvertToString: true, + Last: true, + }, + }, + }, + } + if diff := cmp.Diff(wantExplicitParams, gotExplicit.RoutingParams); diff != "" { + t.Errorf("explicitExtMethod.RoutingParams mismatch (-want +got):\n%s", diff) + } +} + +func TestAnnotateMethod_HTTPClientSkipsRoutingParams(t *testing.T) { + extEnum := api.NewTestEnum("ExtMode"). + WithPackage("google.type"). + WithValues(api.NewTestEnumValue("EXT_MODE_UNSPECIFIED", 0)) + inputType := api.NewTestMessage("HTTPRequest"). + WithPackage("google.cloud.test.v1"). + WithFields( + api.NewTestField("name").WithType(api.TypezString), + api.NewTestField("payload").WithType(api.TypezBytes), + api.NewTestField("ext_mode").WithEnumType(extEnum), + ) + outputType := api.NewTestMessage("HTTPResponse").WithPackage("google.cloud.test.v1") + method := api.NewTestMethod("GetResource"). + WithInput(inputType). + WithOutput(outputType). + WithVerb("GET"). + WithPathTemplate(api.NewPathTemplateBuilder().WithLiteral("v1").WithVariableNamed("name").Build()). + WithRouting( + api.NewTestRoutingInfo("payload", api.NewTestRoutingInfoVariant("payload")), + api.NewTestRoutingInfo("mode", api.NewTestRoutingInfoVariant("ext_mode")), + ) + service := api.NewTestService("HTTPService"). + WithPackage("google.cloud.test.v1"). + WithMethods(method) + model := api.NewTestAPI([]*api.Message{inputType, outputType}, []*api.Enum{extEnum}, []*api.Service{service}). + WithPackageName("google.cloud.test.v1") + if err := api.CrossReference(model); err != nil { + t.Fatal(err) + } + + c := newTestCodec(t, model, &config.Library{ + Name: "google-cloud-test-v1", + Swift: swiftConfig(t, []config.SwiftDependency{ + {Name: "GoogleType", ApiPackage: "google.type"}, + }), + }) + if err := c.annotateModel(); err != nil { + t.Fatal(err) + } + gotMethod := method.Codec().(*methodAnnotations) + if len(gotMethod.RoutingParams) != 0 { + t.Errorf("HTTP client RoutingParams = %v, want empty", gotMethod.RoutingParams) + } + svcAnn := service.Codec().(*serviceAnnotations) + if len(svcAnn.ServiceImports()) != 0 { + t.Errorf("HTTP client ServiceImports() = %v, want empty", svcAnn.ServiceImports()) + } +} + +func TestAnnotateMethod_RoutingError(t *testing.T) { + inputType := api.NewTestMessage("BadRouteRequest"). + WithPackage("google.cloud.test.v1"). + WithFields( + api.NewTestField("payload").WithType(api.TypezBytes), + ) + outputType := api.NewTestMessage("BadRouteResponse"). + WithPackage("google.cloud.test.v1") + + for _, test := range []struct { + name string + method *api.Method + }{ + { + name: "explicit routing references missing field", + method: api.NewTestMethod("MissingExplicit"). + WithInput(inputType). + WithOutput(outputType). + WithRouting(api.NewTestRoutingInfo("missing", api.NewTestRoutingInfoVariant("does_not_exist"))), + }, + { + name: "implicit HTTP binding references bytes field", + method: api.NewTestMethod("BytesHTTP"). + WithInput(inputType). + WithOutput(outputType). + WithVerb("GET"). + WithPathTemplate(api.NewPathTemplateBuilder().WithLiteral("v1").WithVariableNamed("payload").Build()), + }, + } { + t.Run(test.name, func(t *testing.T) { + service := api.NewTestService("TestService"). + WithPackage("google.cloud.test.v1"). + WithMethods(test.method) + model := api.NewTestAPI([]*api.Message{inputType, outputType}, nil, []*api.Service{service}). + WithPackageName("google.cloud.test.v1") + if err := api.CrossReference(model); err != nil { + t.Fatal(err) + } + c, err := newCodec(model, &config.Library{Swift: swiftConfig(t, nil)}, &config.SwiftModule{ + ModuleType: "grpc-client", + ModulePath: "TestProtos", + }, t.TempDir()) + if err != nil { + t.Fatal(err) + } + if gotErr := c.annotateModel(); gotErr == nil { + t.Errorf("annotateModel() succeeded for %s, want error", test.name) + } + }) + } +} diff --git a/internal/sidekick/swift/annotate_method_test.go b/internal/sidekick/swift/annotate_method_test.go index 0091ba4634..47959c67a5 100644 --- a/internal/sidekick/swift/annotate_method_test.go +++ b/internal/sidekick/swift/annotate_method_test.go @@ -1206,7 +1206,15 @@ func TestAnnotateMethod_ExplicitEmptyRoutingSuppressesHTTPFallback(t *testing.T) if err := api.CrossReference(model); err != nil { t.Fatal(err) } - codec := newTestCodec(t, model, nil) + codec, err := newCodec( + model, + &config.Library{Swift: swiftConfig(t, nil)}, + &config.SwiftModule{ModuleType: "grpc-client", ModulePath: "TestProtos"}, + t.TempDir(), + ) + if err != nil { + t.Fatal(err) + } if err := codec.annotateModel(); err != nil { t.Fatal(err) } @@ -1281,7 +1289,15 @@ func TestAnnotateMethod_RoutingAdditionalBindings(t *testing.T) { if err := api.CrossReference(model); err != nil { t.Fatal(err) } - codec := newTestCodec(t, model, nil) + codec, err := newCodec( + model, + &config.Library{Swift: swiftConfig(t, nil)}, + &config.SwiftModule{ModuleType: "grpc-client", ModulePath: "TestProtos"}, + t.TempDir(), + ) + if err != nil { + t.Fatal(err) + } if err := codec.annotateModel(); err != nil { t.Fatal(err) } @@ -1294,14 +1310,14 @@ func TestAnnotateMethod_RoutingAdditionalBindings(t *testing.T) { { name: "literal primary with additional binding variable", method: listAccounts, - want: []*routingParam{newTestMultiWildcardRoutingParam("parent", "request.parent")}, + want: []*routingParam{newTestMultiWildcardRoutingParam("parent", []*routingFieldStep{{PropertyName: "parent"}}, false)}, }, { name: "overlapping and secondary variables preserve order", method: moveAccount, want: []*routingParam{ - newTestMultiWildcardRoutingParam("name", "request.name"), - newTestMultiWildcardRoutingParam("destination_parent", "request.destinationParent"), + newTestMultiWildcardRoutingParam("name", []*routingFieldStep{{PropertyName: "name"}}, false), + newTestMultiWildcardRoutingParam("destination_parent", []*routingFieldStep{{PropertyName: "destinationParent"}}, false), }, }, { @@ -1312,8 +1328,8 @@ func TestAnnotateMethod_RoutingAdditionalBindings(t *testing.T) { RoutingKey: "bucket", Variants: []*routingParamVariant{ { - FieldAccessor: "request.destinationParent", - Last: true, + FieldSteps: []*routingFieldStep{{PropertyName: "destinationParent"}}, + Last: true, }, }, }, diff --git a/internal/sidekick/swift/annotate_service.go b/internal/sidekick/swift/annotate_service.go index e7825e9a19..efab186422 100644 --- a/internal/sidekick/swift/annotate_service.go +++ b/internal/sidekick/swift/annotate_service.go @@ -283,6 +283,23 @@ func (c *codec) annotateService(service *api.Service, model *modelAnnotations) ( annotations.DependsOn[dep.Name] = dep } } + if c.isGrpc() { + if ma, ok := method.Codec().(*methodAnnotations); ok { + for _, rp := range ma.RoutingParams { + for _, v := range rp.Variants { + for _, pkg := range v.RequiredPackages { + dep, err := c.addApiPackageDependency(pkg) + if err != nil { + return nil, err + } + if dep != nil { + annotations.DependsOn[dep.Name] = dep + } + } + } + } + } + } for _, signature := range method.Signatures() { if err := c.addSignatureDependencies(annotations, signature); err != nil { return nil, err diff --git a/internal/sidekick/swift/format_path.go b/internal/sidekick/swift/format_path.go index 09c07be292..42a76d5e6c 100644 --- a/internal/sidekick/swift/format_path.go +++ b/internal/sidekick/swift/format_path.go @@ -16,6 +16,7 @@ package swift import ( "fmt" + "slices" "strings" "github.com/googleapis/librarian/internal/sidekick/api" @@ -153,30 +154,187 @@ type routingParam struct { Variants []*routingParamVariant } +// routingFieldStep describes a single hop along a routing parameter field path +// starting from `request`. +type routingFieldStep struct { + PropertyName string + ChainOptional bool +} + // Represents a single candidate field path and pattern rule for extracting a routing // parameter value. type routingParamVariant struct { - FieldAccessor string + FieldSteps []*routingFieldStep + ConvertToString bool + IsEnum bool + IsStringEnum bool + IsOptional bool + NeedsParens bool + RequiredPackages []string PrefixSegments []string MatchingSegments []string SuffixSegments []string Last bool } -// Builds a Swift field access expression with optional chaining from a field path slice -// (e.g., ["table", "parent"] -> "request.table?.parent"). -// -// Returns an empty string if fieldPath is empty; callers are expected to filter out -// empty field paths as AIP-4222 routing parameters must extract from a specific field. -func formatFieldAccessor(fieldPath []string) string { +func isScalarWrapperWKT(typezID string) bool { + switch typezID { + case api.WktStringValueID, + api.WktInt64ValueID, + api.WktUInt64ValueID, + api.WktInt32ValueID, + api.WktUInt32ValueID, + api.WktFloatValueID, + api.WktDoubleValueID, + api.WktBoolValueID: + return true + default: + return false + } +} + +// resolveRoutingFieldPath resolves a routing parameter field path against message +// and describes how to extract and convert the leaf value into a Swift String?. +func (c *codec) resolveRoutingFieldPath(message *api.Message, fieldPath []string) (*routingParamVariant, error) { if len(fieldPath) == 0 { - return "" + return nil, nil + } + if message == nil { + return nil, fmt.Errorf("missing input message for routing field path %q", strings.Join(fieldPath, ".")) + } + var modelAnn *modelAnnotations + if c.Model != nil { + modelAnn, _ = c.Model.Codec.(*modelAnnotations) + } + current := message + var steps []*routingFieldStep + var requiredPackages []string + addRequiredPackage := func(pkg string) { + if pkg == "" || (c.Model != nil && pkg == c.Model.PackageName) { + return + } + if !slices.Contains(requiredPackages, pkg) { + requiredPackages = append(requiredPackages, pkg) + } + } + isOptional := false + tailOptional := false + inOptionalChain := false + convertToString := false + isEnum := false + isStringEnum := false + + for i, part := range fieldPath { + field, err := lookupField(current, part) + if err != nil { + return nil, err + } + if !field.Singular() { + return nil, fmt.Errorf("unsupported non-singular routing field %q in message %q", field.Name(), current.ID()) + } + if field.IsOneOf() { + return nil, fmt.Errorf("unsupported oneof routing field %q in message %q", field.Name(), current.ID()) + } + if field.Typez() == api.TypezBytes || field.TypezID() == api.WktBytesValueID || field.TypezID() == api.WktNullValueID || isScalarWrapperWKT(field.TypezID()) { + return nil, fmt.Errorf("unsupported routing parameter type %q, message=%q, path=%q", unsupportedRoutingTypeName(field), message.ID(), strings.Join(fieldPath, ".")) + } + fieldAnn, err := c.ensureRoutingFieldAnnotated(field, modelAnn) + if err != nil { + return nil, err + } + if fieldAnn.Recursive { + return nil, fmt.Errorf("unsupported recursive routing field %q in message %q", field.Name(), current.ID()) + } + addRequiredPackage(fieldAnn.PackageName) + + chainOptional := tailOptional + if chainOptional { + inOptionalChain = true + } + steps = append(steps, &routingFieldStep{ + PropertyName: fieldAnn.Name, + ChainOptional: chainOptional, + }) + tailOptional = field.Optional() + isOptional = isOptional || field.Optional() + + if i < len(fieldPath)-1 { + if field.Typez() != api.TypezMessage { + return nil, fmt.Errorf("intermediate routing field %q in message %q is not a message", field.Name(), current.ID()) + } + nextMsg, err := c.lookupRoutingNextMessage(field) + if err != nil { + return nil, err + } + current = nextMsg + continue + } + + convertToString, isEnum, isStringEnum, err = c.classifyRoutingLeaf(field, message, fieldPath) + if err != nil { + return nil, err + } } - var parts []string - for _, p := range fieldPath { - parts = append(parts, camelCase(p)) + + return &routingParamVariant{ + FieldSteps: steps, + ConvertToString: convertToString, + IsEnum: isEnum, + IsStringEnum: isStringEnum, + IsOptional: isOptional, + NeedsParens: inOptionalChain, + RequiredPackages: requiredPackages, + }, nil +} + +// ensureRoutingFieldAnnotated ensures only the traversed field has Swift +// annotations, without annotating unrelated sibling fields on external +// intermediate messages. +func (c *codec) ensureRoutingFieldAnnotated(field *api.Field, modelAnn *modelAnnotations) (*fieldAnnotations, error) { + fieldAnn, ok := field.Codec().(*fieldAnnotations) + if !ok { + if c.Model == nil { + return nil, fmt.Errorf("internal error: field %s does not have swift fieldAnnotations", field.ID()) + } + var err error + fieldAnn, err = c.annotateField(field, modelAnn) + if err != nil { + return nil, err + } + } + return fieldAnn, nil +} + +func (c *codec) lookupRoutingNextMessage(field *api.Field) (*api.Message, error) { + if field.MessageType() != nil { + return field.MessageType(), nil } - return "request." + strings.Join(parts, "?.") + if c.Model != nil { + return lookupMessage(c.Model, field.TypezID()) + } + return nil, fmt.Errorf("unable to lookup message %q", field.TypezID()) +} + +func (c *codec) classifyRoutingLeaf(field *api.Field, message *api.Message, fieldPath []string) (convertToString, isEnum, isStringEnum bool, err error) { + switch field.Typez() { + case api.TypezString: + return false, false, false, nil + case api.TypezEnum: + return false, true, c.UseStringEnums, nil + case api.TypezInt32, api.TypezInt64, api.TypezUint32, api.TypezUint64, + api.TypezSint32, api.TypezSint64, api.TypezFixed32, api.TypezFixed64, + api.TypezSfixed32, api.TypezSfixed64, api.TypezFloat, api.TypezDouble, api.TypezBool: + return true, false, false, nil + default: + return false, false, false, fmt.Errorf("unsupported routing parameter type %q, message=%q, path=%q", unsupportedRoutingTypeName(field), message.ID(), strings.Join(fieldPath, ".")) + } +} + +func unsupportedRoutingTypeName(field *api.Field) string { + if field.TypezID() == api.WktBytesValueID || field.TypezID() == api.WktNullValueID || isScalarWrapperWKT(field.TypezID()) { + return field.TypezID() + } + return field.Typez().String() } // Converts a list of path segments into Swift _RoutingMatcher token expressions @@ -228,7 +386,7 @@ func annotateSegments(segments []string, isPrefix bool, isSuffix bool) []string } // Extracts routing parameters from explicit google.api.routing annotations per AIP-4222. -func (c *codec) routingParamsFromRouting(routingInfos []*api.RoutingInfo) []*routingParam { +func (c *codec) routingParamsFromRouting(message *api.Message, routingInfos []*api.RoutingInfo) ([]*routingParam, error) { var params []*routingParam for _, info := range routingInfos { routingKey := info.Name() @@ -242,12 +400,14 @@ func (c *codec) routingParamsFromRouting(routingInfos []*api.RoutingInfo) []*rou if routingKey == "" { routingKey = strings.Join(fieldPath, ".") } - variants = append(variants, &routingParamVariant{ - FieldAccessor: formatFieldAccessor(fieldPath), - PrefixSegments: annotateSegments(variant.Prefix().Segments(), true, false), - MatchingSegments: annotateSegments(variant.Matching().Segments(), false, false), - SuffixSegments: annotateSegments(variant.Suffix().Segments(), false, true), - }) + v, err := c.resolveRoutingFieldPath(message, fieldPath) + if err != nil { + return nil, err + } + v.PrefixSegments = annotateSegments(variant.Prefix().Segments(), true, false) + v.MatchingSegments = annotateSegments(variant.Matching().Segments(), false, false) + v.SuffixSegments = annotateSegments(variant.Suffix().Segments(), false, true) + variants = append(variants, v) } if len(variants) > 0 { @@ -260,14 +420,14 @@ func (c *codec) routingParamsFromRouting(routingInfos []*api.RoutingInfo) []*rou }) } } - return params + return params, nil } // Extracts fallback routing parameters from a google.api.http path template when explicit // google.api.routing annotations are absent per AIP-4222. -func (c *codec) routingParamsFromPathTemplate(t *api.PathTemplate) []*routingParam { +func (c *codec) routingParamsFromPathTemplate(message *api.Message, t *api.PathTemplate) ([]*routingParam, error) { if t == nil { - return nil + return nil, nil } var params []*routingParam for _, segment := range t.Segments() { @@ -276,34 +436,36 @@ func (c *codec) routingParamsFromPathTemplate(t *api.PathTemplate) []*routingPar if len(fieldPath) == 0 { continue } + v, err := c.resolveRoutingFieldPath(message, fieldPath) + if err != nil { + return nil, err + } + v.MatchingSegments = []string{".multiWildcard"} + v.Last = true params = append(params, &routingParam{ RoutingKey: strings.Join(fieldPath, "."), - Variants: []*routingParamVariant{ - { - FieldAccessor: formatFieldAccessor(fieldPath), - PrefixSegments: nil, - MatchingSegments: []string{".multiWildcard"}, - SuffixSegments: nil, - Last: true, - }, - }, + Variants: []*routingParamVariant{v}, }) } } - return params + return params, nil } // routingParamsFromBindings extracts fallback routing parameters across all // google.api.http bindings in declaration order, deduplicating repeated routing // keys per AIP-4222. -func (c *codec) routingParamsFromBindings(bindings []*api.PathBinding) []*routingParam { +func (c *codec) routingParamsFromBindings(message *api.Message, bindings []*api.PathBinding) ([]*routingParam, error) { var params []*routingParam seen := make(map[string]bool) for _, binding := range bindings { if binding == nil { continue } - for _, param := range c.routingParamsFromPathTemplate(binding.PathTemplate()) { + bindingParams, err := c.routingParamsFromPathTemplate(message, binding.PathTemplate()) + if err != nil { + return nil, err + } + for _, param := range bindingParams { if seen[param.RoutingKey] { continue } @@ -311,5 +473,5 @@ func (c *codec) routingParamsFromBindings(bindings []*api.PathBinding) []*routin params = append(params, param) } } - return params + return params, nil } diff --git a/internal/sidekick/swift/format_path_routing_test.go b/internal/sidekick/swift/format_path_routing_test.go new file mode 100644 index 0000000000..a9ba92c6a2 --- /dev/null +++ b/internal/sidekick/swift/format_path_routing_test.go @@ -0,0 +1,422 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package swift + +import ( + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/googleapis/librarian/internal/config" + "github.com/googleapis/librarian/internal/sidekick/api" +) + +func TestResolveRoutingFieldPath(t *testing.T) { + makeFixture := func(specFormat string) (*codec, *api.Message) { + statusEnum := api.NewTestEnum("Status"). + WithPackage("google.cloud.test.v1"). + WithValues( + api.NewTestEnumValue("STATUS_UNSPECIFIED", 0), + api.NewTestEnumValue("STATUS_ACTIVE", 1), + ) + extEnum := api.NewTestEnum("ExtMode"). + WithPackage("google.type"). + WithValues( + api.NewTestEnumValue("EXT_MODE_UNSPECIFIED", 0), + api.NewTestEnumValue("EXT_MODE_ON", 1), + ) + unconfiguredEnum := api.NewTestEnum("UnconfiguredEnum"). + WithPackage("google.unconfigured"). + WithValues( + api.NewTestEnumValue("UNCONFIGURED_UNSPECIFIED", 0), + ) + + extContainerMsg := api.NewTestMessage("ExtContainer"). + WithPackage("google.type"). + WithFields( + api.NewTestField("rank").WithType(api.TypezInt32), + api.NewTestField("unconfigured_sibling").WithEnumType(unconfiguredEnum), + ) + + innerMsg := api.NewTestMessage("Inner"). + WithPackage("google.cloud.test.v1"). + WithFields( + api.NewTestField("count").WithType(api.TypezInt32), + api.NewTestField("opt_count").WithType(api.TypezInt32).WithOptional(), + api.NewTestField("status").WithEnumType(statusEnum), + api.NewTestField("opt_status").WithEnumType(statusEnum).WithOptional(), + ) + + requestMsg := api.NewTestMessage("Request"). + WithPackage("google.cloud.test.v1"). + WithFields( + api.NewTestField("name").WithType(api.TypezString), + api.NewTestField("opt_name").WithType(api.TypezString).WithOptional(), + api.NewTestField("page_size").WithType(api.TypezInt32), + api.NewTestField("opt_page_size").WithType(api.TypezInt32).WithOptional(), + api.NewTestField("ratio").WithType(api.TypezDouble), + api.NewTestField("enabled").WithType(api.TypezBool), + api.NewTestField("status").WithEnumType(statusEnum), + api.NewTestField("opt_status").WithEnumType(statusEnum).WithOptional(), + api.NewTestField("ext_mode").WithEnumType(extEnum), + api.NewTestField("ext_container").WithMessageType(extContainerMsg).WithOptional(), + api.NewTestField("req_inner").WithMessageType(innerMsg), + api.NewTestField("info").WithMessageType(innerMsg).WithOptional(), + ) + + model := api.NewTestAPI( + []*api.Message{innerMsg, requestMsg}, + []*api.Enum{statusEnum, extEnum}, + nil, + ).WithPackageName("google.cloud.test.v1") + model.AddMessage(extContainerMsg) + model.AddEnum(unconfiguredEnum) + if err := api.CrossReference(model); err != nil { + t.Fatal(err) + } + lib := &config.Library{ + SpecificationFormat: specFormat, + Swift: swiftConfig(t, []config.SwiftDependency{ + {Name: "GoogleType", ApiPackage: "google.type"}, + }), + } + c := newTestCodec(t, model, lib) + if err := c.annotateModel(); err != nil { + t.Fatal(err) + } + return c, requestMsg + } + + for _, test := range []struct { + name string + specFormat string + fieldPath []string + want *routingParamVariant + }{ + { + name: "empty field path", + specFormat: config.SpecProtobuf, + fieldPath: nil, + want: nil, + }, + { + name: "non-optional string", + specFormat: config.SpecProtobuf, + fieldPath: []string{"name"}, + want: &routingParamVariant{ + FieldSteps: []*routingFieldStep{{PropertyName: "name"}}, + }, + }, + { + name: "optional string", + specFormat: config.SpecProtobuf, + fieldPath: []string{"opt_name"}, + want: &routingParamVariant{ + FieldSteps: []*routingFieldStep{{PropertyName: "optName"}}, + IsOptional: true, + }, + }, + { + name: "non-optional int32 scalar", + specFormat: config.SpecProtobuf, + fieldPath: []string{"page_size"}, + want: &routingParamVariant{ + FieldSteps: []*routingFieldStep{{PropertyName: "pageSize"}}, + ConvertToString: true, + }, + }, + { + name: "optional int32 scalar", + specFormat: config.SpecProtobuf, + fieldPath: []string{"opt_page_size"}, + want: &routingParamVariant{ + FieldSteps: []*routingFieldStep{{PropertyName: "optPageSize"}}, + ConvertToString: true, + IsOptional: true, + }, + }, + { + name: "double scalar", + specFormat: config.SpecProtobuf, + fieldPath: []string{"ratio"}, + want: &routingParamVariant{ + FieldSteps: []*routingFieldStep{{PropertyName: "ratio"}}, + ConvertToString: true, + }, + }, + { + name: "bool scalar", + specFormat: config.SpecProtobuf, + fieldPath: []string{"enabled"}, + want: &routingParamVariant{ + FieldSteps: []*routingFieldStep{{PropertyName: "enabled"}}, + ConvertToString: true, + }, + }, + { + name: "non-optional protobuf enum", + specFormat: config.SpecProtobuf, + fieldPath: []string{"status"}, + want: &routingParamVariant{ + FieldSteps: []*routingFieldStep{{PropertyName: "status"}}, + IsEnum: true, + }, + }, + { + name: "optional protobuf enum", + specFormat: config.SpecProtobuf, + fieldPath: []string{"opt_status"}, + want: &routingParamVariant{ + FieldSteps: []*routingFieldStep{{PropertyName: "optStatus"}}, + IsEnum: true, + IsOptional: true, + }, + }, + { + name: "external enum records required package", + specFormat: config.SpecProtobuf, + fieldPath: []string{"ext_mode"}, + want: &routingParamVariant{ + FieldSteps: []*routingFieldStep{{PropertyName: "extMode"}}, + IsEnum: true, + RequiredPackages: []string{"google.type"}, + }, + }, + { + name: "external unannotated intermediate ignores unconfigured sibling", + specFormat: config.SpecProtobuf, + fieldPath: []string{"ext_container", "rank"}, + want: &routingParamVariant{ + FieldSteps: []*routingFieldStep{ + {PropertyName: "extContainer"}, + {PropertyName: "rank", ChainOptional: true}, + }, + ConvertToString: true, + IsOptional: true, + NeedsParens: true, + RequiredPackages: []string{"google.type"}, + }, + }, + { + name: "discovery string enum non-optional", + specFormat: config.SpecDiscovery, + fieldPath: []string{"status"}, + want: &routingParamVariant{ + FieldSteps: []*routingFieldStep{{PropertyName: "status"}}, + IsEnum: true, + IsStringEnum: true, + }, + }, + { + name: "discovery string enum optional", + specFormat: config.SpecDiscovery, + fieldPath: []string{"opt_status"}, + want: &routingParamVariant{ + FieldSteps: []*routingFieldStep{{PropertyName: "optStatus"}}, + IsEnum: true, + IsStringEnum: true, + IsOptional: true, + }, + }, + { + name: "non-optional message to optional scalar does not need parens", + specFormat: config.SpecProtobuf, + fieldPath: []string{"req_inner", "opt_count"}, + want: &routingParamVariant{ + FieldSteps: []*routingFieldStep{ + {PropertyName: "reqInner"}, + {PropertyName: "optCount"}, + }, + ConvertToString: true, + IsOptional: true, + NeedsParens: false, + }, + }, + { + name: "nested optional message to scalar", + specFormat: config.SpecProtobuf, + fieldPath: []string{"info", "count"}, + want: &routingParamVariant{ + FieldSteps: []*routingFieldStep{ + {PropertyName: "info"}, + {PropertyName: "count", ChainOptional: true}, + }, + ConvertToString: true, + IsOptional: true, + NeedsParens: true, + }, + }, + { + name: "nested optional message to enum", + specFormat: config.SpecProtobuf, + fieldPath: []string{"info", "opt_status"}, + want: &routingParamVariant{ + FieldSteps: []*routingFieldStep{ + {PropertyName: "info"}, + {PropertyName: "optStatus", ChainOptional: true}, + }, + IsEnum: true, + IsOptional: true, + NeedsParens: true, + }, + }, + } { + t.Run(test.name, func(t *testing.T) { + c, requestMsg := makeFixture(test.specFormat) + got, err := c.resolveRoutingFieldPath(requestMsg, test.fieldPath) + if err != nil { + t.Fatal(err) + } + if diff := cmp.Diff(test.want, got); diff != "" { + t.Errorf("mismatch (-want +got):\n%s", diff) + } + }) + } +} + +func TestResolveRoutingFieldPath_Error(t *testing.T) { + innerMsg := api.NewTestMessage("Inner"). + WithPackage("google.cloud.test.v1"). + WithFields( + api.NewTestField("name").WithType(api.TypezString), + ) + nodeMsg := api.NewTestMessage("Node"). + WithPackage("google.cloud.test.v1"). + WithFields( + api.NewTestField("rank").WithType(api.TypezInt32), + ) + nodeMsg.WithFields( + api.NewTestField("child").WithMessageType(nodeMsg).WithOptional(), + ) + stringMap := api.NewTestMap("LabelsEntry", api.TypezString, api.TypezString) + requestMsg := api.NewTestMessage("Request"). + WithPackage("google.cloud.test.v1"). + WithFields( + api.NewTestField("name").WithType(api.TypezString), + api.NewTestField("tags").WithType(api.TypezString).WithRepeated(), + api.NewTestField("labels").WithMapType(stringMap).WithMap(), + api.NewTestField("payload").WithType(api.TypezBytes), + api.NewTestField("bytes_wrapper").WithType(api.TypezMessage).WithTypezID(api.WktBytesValueID).WithOptional(), + api.NewTestField("int64_wrapper").WithType(api.TypezMessage).WithTypezID(api.WktInt64ValueID).WithOptional(), + api.NewTestField("null_value").WithType(api.TypezEnum).WithTypezID(api.WktNullValueID).WithOptional(), + api.NewTestField("node").WithMessageType(nodeMsg).WithOptional().WithRecursive(), + api.NewTestField("inner").WithMessageType(innerMsg).WithOptional(), + ). + WithOneOfs( + api.NewTestOneOf("source").WithFields( + api.NewTestField("bucket").WithType(api.TypezString), + ), + ) + model := api.NewTestAPI([]*api.Message{innerMsg, nodeMsg, requestMsg}, nil, nil). + WithPackageName("google.cloud.test.v1"). + WithMaps(stringMap) + if err := api.CrossReference(model); err != nil { + t.Fatal(err) + } + c := newTestCodec(t, model, &config.Library{Swift: swiftConfig(t, nil)}) + if err := c.annotateModel(); err != nil { + t.Fatal(err) + } + + for _, test := range []struct { + name string + message *api.Message + fieldPath []string + wantErr string + }{ + { + name: "nil message", + message: nil, + fieldPath: []string{"name"}, + wantErr: "missing input message", + }, + { + name: "missing field", + message: requestMsg, + fieldPath: []string{"does_not_exist"}, + wantErr: "does_not_exist", + }, + { + name: "repeated field", + message: requestMsg, + fieldPath: []string{"tags"}, + wantErr: "tags", + }, + { + name: "map field", + message: requestMsg, + fieldPath: []string{"labels"}, + wantErr: "labels", + }, + { + name: "bytes field", + message: requestMsg, + fieldPath: []string{"payload"}, + wantErr: "payload", + }, + { + name: "WKT BytesValue field", + message: requestMsg, + fieldPath: []string{"bytes_wrapper"}, + wantErr: api.WktBytesValueID, + }, + { + name: "WKT Int64Value wrapper field", + message: requestMsg, + fieldPath: []string{"int64_wrapper"}, + wantErr: api.WktInt64ValueID, + }, + { + name: "WKT NullValue field", + message: requestMsg, + fieldPath: []string{"null_value"}, + wantErr: api.WktNullValueID, + }, + { + name: "oneof field", + message: requestMsg, + fieldPath: []string{"bucket"}, + wantErr: "bucket", + }, + { + name: "recursive field", + message: requestMsg, + fieldPath: []string{"node", "rank"}, + wantErr: "node", + }, + { + name: "non-message intermediate field", + message: requestMsg, + fieldPath: []string{"name", "sub"}, + wantErr: "not a message", + }, + { + name: "non-wrapper message leaf", + message: requestMsg, + fieldPath: []string{"inner"}, + wantErr: "inner", + }, + } { + t.Run(test.name, func(t *testing.T) { + got, gotErr := c.resolveRoutingFieldPath(test.message, test.fieldPath) + if gotErr == nil { + t.Fatalf("resolveRoutingFieldPath(%v) succeeded with %+v, want error", test.fieldPath, got) + } + if !strings.Contains(gotErr.Error(), test.wantErr) { + t.Errorf("resolveRoutingFieldPath(%v) error = %q, want substring %q", test.fieldPath, gotErr.Error(), test.wantErr) + } + }) + } +} diff --git a/internal/sidekick/swift/format_path_test.go b/internal/sidekick/swift/format_path_test.go index bfa664d6e3..33205f6b0e 100644 --- a/internal/sidekick/swift/format_path_test.go +++ b/internal/sidekick/swift/format_path_test.go @@ -306,14 +306,23 @@ func TestNewPathVariable(t *testing.T) { } func TestRoutingParams(t *testing.T) { + tableMessage := api.NewTestMessage("Table"). + WithPackage("google.storage.v2"). + WithFields( + api.NewTestField("parent").WithType(api.TypezString), + ) requestMessage := api.NewTestMessage("GetBucketRequest"). WithPackage("google.storage.v2"). WithFields( api.NewTestField("name").WithType(api.TypezString), api.NewTestField("parent").WithType(api.TypezString), + api.NewTestField("table").WithMessageType(tableMessage).WithOptional(), ) - model := api.NewTestAPI([]*api.Message{requestMessage}, nil, nil) + model := api.NewTestAPI([]*api.Message{tableMessage, requestMessage}, nil, nil) + if err := api.CrossReference(model); err != nil { + t.Fatal(err) + } codec := newTestCodec(t, model, nil) if err := codec.annotateModel(); err != nil { t.Fatal(err) @@ -341,8 +350,8 @@ func TestRoutingParams(t *testing.T) { RoutingKey: "bucket", Variants: []*routingParamVariant{ { - FieldAccessor: "request.name", - Last: true, + FieldSteps: []*routingFieldStep{{PropertyName: "name"}}, + Last: true, }, }, }, @@ -365,8 +374,8 @@ func TestRoutingParams(t *testing.T) { RoutingKey: "parent", Variants: []*routingParamVariant{ { - FieldAccessor: "request.parent", - Last: true, + FieldSteps: []*routingFieldStep{{PropertyName: "parent"}}, + Last: true, }, }, }, @@ -391,7 +400,7 @@ func TestRoutingParams(t *testing.T) { RoutingKey: "bucket", Variants: []*routingParamVariant{ { - FieldAccessor: "request.name", + FieldSteps: []*routingFieldStep{{PropertyName: "name"}}, MatchingSegments: []string{`.literal("projects/")`, `.singleWildcard`, `.literal("/buckets/")`, `.singleWildcard`}, SuffixSegments: []string{`.trailingMultiWildcard`}, Last: true, @@ -422,12 +431,12 @@ func TestRoutingParams(t *testing.T) { RoutingKey: "routing_id", Variants: []*routingParamVariant{ { - FieldAccessor: "request.name", + FieldSteps: []*routingFieldStep{{PropertyName: "name"}}, MatchingSegments: []string{`.literal("projects/")`, `.singleWildcard`}, Last: false, }, { - FieldAccessor: "request.parent", + FieldSteps: []*routingFieldStep{{PropertyName: "parent"}}, MatchingSegments: []string{`.multiWildcard`}, Last: true, }, @@ -455,7 +464,12 @@ func TestRoutingParams(t *testing.T) { RoutingKey: "table", Variants: []*routingParamVariant{ { - FieldAccessor: "request.table?.parent", + FieldSteps: []*routingFieldStep{ + {PropertyName: "table"}, + {PropertyName: "parent", ChainOptional: true}, + }, + IsOptional: true, + NeedsParens: true, PrefixSegments: []string{`.literal("projects/")`}, MatchingSegments: []string{`.singleWildcard`}, SuffixSegments: []string{`.literal("/tables/")`, `.singleWildcard`}, @@ -484,7 +498,7 @@ func TestRoutingParams(t *testing.T) { RoutingKey: "location", Variants: []*routingParamVariant{ { - FieldAccessor: "request.name", + FieldSteps: []*routingFieldStep{{PropertyName: "name"}}, PrefixSegments: []string{`.literal("projects/")`, `.singleWildcard`, `.literal("/")`}, MatchingSegments: []string{`.literal("locations/")`, `.singleWildcard`}, Last: true, @@ -500,7 +514,10 @@ func TestRoutingParams(t *testing.T) { }, } { t.Run(test.name, func(t *testing.T) { - got := codec.routingParamsFromRouting(test.routingInfos) + got, err := codec.routingParamsFromRouting(requestMessage, test.routingInfos) + if err != nil { + t.Fatal(err) + } if diff := cmp.Diff(test.want, got); diff != "" { t.Errorf("mismatch (-want +got):\n%s", diff) } @@ -536,11 +553,14 @@ func TestRoutingParamsFromPathTemplate(t *testing.T) { WithLiteral("v2"). WithVariableNamed("name"). Build(), - want: []*routingParam{newTestMultiWildcardRoutingParam("name", "request.name")}, + want: []*routingParam{newTestMultiWildcardRoutingParam("name", []*routingFieldStep{{PropertyName: "name"}}, false)}, }, } { t.Run(test.name, func(t *testing.T) { - got := codec.routingParamsFromPathTemplate(test.template) + got, err := codec.routingParamsFromPathTemplate(requestMessage, test.template) + if err != nil { + t.Fatal(err) + } if diff := cmp.Diff(test.want, got); diff != "" { t.Errorf("mismatch (-want +got):\n%s", diff) } @@ -549,7 +569,28 @@ func TestRoutingParamsFromPathTemplate(t *testing.T) { } func TestRoutingParamsFromBindings(t *testing.T) { - c := &codec{} + bookMessage := api.NewTestMessage("Book"). + WithPackage("test.v1"). + WithFields( + api.NewTestField("name").WithType(api.TypezString), + ) + requestMessage := api.NewTestMessage("RoutingBindingsRequest"). + WithPackage("test.v1"). + WithFields( + api.NewTestField("name").WithType(api.TypezString), + api.NewTestField("parent").WithType(api.TypezString), + api.NewTestField("destination_parent").WithType(api.TypezString), + api.NewTestField("shelf").WithType(api.TypezString), + api.NewTestField("book").WithMessageType(bookMessage).WithOptional(), + ) + model := api.NewTestAPI([]*api.Message{bookMessage, requestMessage}, nil, nil) + if err := api.CrossReference(model); err != nil { + t.Fatal(err) + } + c := newTestCodec(t, model, nil) + if err := c.annotateModel(); err != nil { + t.Fatal(err) + } for _, test := range []struct { name string @@ -575,7 +616,7 @@ func TestRoutingParamsFromBindings(t *testing.T) { api.NewPathBindingBuilder().WithVerb("GET").Build(), newTestPathBinding("GET", api.NewPathTemplateBuilder().WithLiteral("v1").WithVariableNamed("parent").Build()), }, - want: []*routingParam{newTestMultiWildcardRoutingParam("parent", "request.parent")}, + want: []*routingParam{newTestMultiWildcardRoutingParam("parent", []*routingFieldStep{{PropertyName: "parent"}}, false)}, }, { // CloudBilling.ListBillingAccounts: GET /v1/billingAccounts + GET /v1/{parent=organizations/*}/billingAccounts @@ -584,7 +625,7 @@ func TestRoutingParamsFromBindings(t *testing.T) { newTestPathBinding("GET", api.NewPathTemplateBuilder().WithLiteral("v1").WithLiteral("billingAccounts").Build()), newTestPathBinding("GET", api.NewPathTemplateBuilder().WithLiteral("v1").WithVariableNamed("parent").WithLiteral("billingAccounts").Build()), }, - want: []*routingParam{newTestMultiWildcardRoutingParam("parent", "request.parent")}, + want: []*routingParam{newTestMultiWildcardRoutingParam("parent", []*routingFieldStep{{PropertyName: "parent"}}, false)}, }, { // CloudBilling.MoveBillingAccount: POST /v1/{name=billingAccounts/*}:move + GET /v1/{destination_parent=organizations/*}/{name=billingAccounts/*}:move @@ -594,8 +635,8 @@ func TestRoutingParamsFromBindings(t *testing.T) { newTestPathBinding("GET", api.NewPathTemplateBuilder().WithLiteral("v1").WithVariableNamed("destination_parent").WithVariableNamed("name").WithVerb("move").Build()), }, want: []*routingParam{ - newTestMultiWildcardRoutingParam("name", "request.name"), - newTestMultiWildcardRoutingParam("destination_parent", "request.destinationParent"), + newTestMultiWildcardRoutingParam("name", []*routingFieldStep{{PropertyName: "name"}}, false), + newTestMultiWildcardRoutingParam("destination_parent", []*routingFieldStep{{PropertyName: "destinationParent"}}, false), }, }, { @@ -618,7 +659,7 @@ func TestRoutingParamsFromBindings(t *testing.T) { WithLiteral("intelligenceFindings"). WithVerb("summarize").Build()), }, - want: []*routingParam{newTestMultiWildcardRoutingParam("parent", "request.parent")}, + want: []*routingParam{newTestMultiWildcardRoutingParam("parent", []*routingFieldStep{{PropertyName: "parent"}}, false)}, }, { name: "nested field path deduplication", @@ -627,13 +668,23 @@ func TestRoutingParamsFromBindings(t *testing.T) { newTestPathBinding("PATCH", api.NewPathTemplateBuilder().WithLiteral("v1").WithVariableNamed("shelf").WithVariableNamed("book", "name").Build()), }, want: []*routingParam{ - newTestMultiWildcardRoutingParam("book.name", "request.book?.name"), - newTestMultiWildcardRoutingParam("shelf", "request.shelf"), + newTestMultiWildcardRoutingParam( + "book.name", + []*routingFieldStep{ + {PropertyName: "book"}, + {PropertyName: "name", ChainOptional: true}, + }, + true, + ), + newTestMultiWildcardRoutingParam("shelf", []*routingFieldStep{{PropertyName: "shelf"}}, false), }, }, } { t.Run(test.name, func(t *testing.T) { - got := c.routingParamsFromBindings(test.bindings) + got, err := c.routingParamsFromBindings(requestMessage, test.bindings) + if err != nil { + t.Fatal(err) + } if diff := cmp.Diff(test.want, got); diff != "" { t.Errorf("mismatch (-want +got):\n%s", diff) } @@ -645,12 +696,14 @@ func newTestPathBinding(verb string, template *api.PathTemplate) *api.PathBindin return api.NewPathBindingBuilder().WithVerb(verb).WithPathTemplate(template).Build() } -func newTestMultiWildcardRoutingParam(key, accessor string) *routingParam { +func newTestMultiWildcardRoutingParam(key string, steps []*routingFieldStep, isOptional bool) *routingParam { return &routingParam{ RoutingKey: key, Variants: []*routingParamVariant{ { - FieldAccessor: accessor, + FieldSteps: steps, + IsOptional: isOptional, + NeedsParens: isOptional && len(steps) > 1, MatchingSegments: []string{".multiWildcard"}, Last: true, }, diff --git a/internal/sidekick/swift/generate_grpc_routing_swift_test.go b/internal/sidekick/swift/generate_grpc_routing_swift_test.go new file mode 100644 index 0000000000..81db19a533 --- /dev/null +++ b/internal/sidekick/swift/generate_grpc_routing_swift_test.go @@ -0,0 +1,483 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package swift + +import ( + "os" + "os/exec" + "path/filepath" + "testing" + + "github.com/googleapis/librarian/internal/config" + "github.com/googleapis/librarian/internal/testhelper" +) + +func TestGenerateStub_GRPCClient_RoutingFieldTypes_SwiftTest(t *testing.T) { + if testing.Short() { + t.Skip("slow test: compiles and runs swift test") + } + testhelper.RequireCommand(t, "swift") + + pkgDir := t.TempDir() + genDir := filepath.Join(pkgDir, "Sources", "RoutingTestLib", "generated") + model := makeRoutingFieldTypesModel(t) + + module := &config.SwiftModule{ + Output: genDir, + ModuleType: "grpc-client", + ModulePath: "RoutingTestProtos", + } + swiftPkg := swiftConfig(t, []config.SwiftDependency{ + {Name: "GoogleType", ApiPackage: "google.type"}, + }) + swiftPkg.PackageNameOverride = "RoutingTestLib" + swiftPkg.LibraryNameOverride = "RoutingTestLib" + library := &config.Library{ + Name: "routing-test-lib", + Swift: swiftPkg, + } + if err := Generate(t.Context(), model, genDir, library, module); err != nil { + t.Fatal(err) + } + + writeTestFile := func(relPath, content string) { + t.Helper() + fullPath := filepath.Join(pkgDir, relPath) + if err := os.MkdirAll(filepath.Dir(fullPath), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(fullPath, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + + writeTestFile("Package.swift", `// swift-tools-version: 6.2 +import PackageDescription + +let strictSwiftSettings: [SwiftSetting] = [ + .enableUpcomingFeature("ExistentialAny"), + .enableUpcomingFeature("InternalImportsByDefault"), + .enableUpcomingFeature("MemberImportVisibility"), + .enableUpcomingFeature("NonisolatedNonsendingByDefault"), + .strictMemorySafety(), +] + +let package = Package( + name: "RoutingTestPackage", + platforms: [.macOS(.v15)], + targets: [ + .target(name: "GoogleAuth"), + .target(name: "GoogleWKT"), + .target(name: "GoogleWKTConvert", dependencies: ["GoogleWKT"]), + .target(name: "SwiftProtobuf"), + .target(name: "Logging"), + .target(name: "GoogleType", dependencies: ["GoogleWKT"]), + .target(name: "GoogleGax", swiftSettings: strictSwiftSettings), + .target( + name: "GoogleGaxGRPC", + dependencies: ["GoogleGax", "SwiftProtobuf"], + swiftSettings: strictSwiftSettings + ), + .target(name: "RoutingTestProtos", dependencies: ["SwiftProtobuf"]), + .target( + name: "RoutingTestLib", + dependencies: [ + "GoogleAuth", + "GoogleGax", + "GoogleGaxGRPC", + "GoogleType", + "GoogleWKT", + "GoogleWKTConvert", + "SwiftProtobuf", + "Logging", + "RoutingTestProtos", + ], + swiftSettings: strictSwiftSettings + ), + .testTarget( + name: "RoutingTestLibTests", + dependencies: ["RoutingTestLib", "GoogleGax", "GoogleGaxGRPC", "GoogleType", "GoogleWKT"], + swiftSettings: [ + .enableUpcomingFeature("ExistentialAny"), + .enableUpcomingFeature("InternalImportsByDefault"), + .enableUpcomingFeature("MemberImportVisibility"), + .enableUpcomingFeature("NonisolatedNonsendingByDefault"), + ] + ), + ] +) +`) + + writeTestFile("Sources/GoogleAuth/GoogleAuth.swift", `public enum _GoogleAuthStub {} +`) + + writeTestFile("Sources/SwiftProtobuf/SwiftProtobuf.swift", `import Foundation + +public struct UnknownStorage: Sendable, Equatable { + public var data: Data = Data() + public init() {} +} + +public protocol Message: Sendable { + init() +} + +public struct Google_Protobuf_Empty: Message { + public init() {} +} + +extension Message { + public mutating func merge(serializedBytes: Data) throws {} +} +`) + + writeTestFile("Sources/Logging/Logging.swift", `public struct Logger: Sendable { + public enum MetadataValue: Sendable, ExpressibleByStringLiteral, ExpressibleByStringInterpolation { + case string(String) + public init(stringLiteral value: String) { self = .string(value) } + } + public init() {} + public subscript(metadataKey key: String) -> MetadataValue? { + get { nil } + set {} + } + public func debug(_ message: @autoclosure () -> String) {} +} +`) + + writeTestFile("Sources/GoogleWKT/GoogleWKT.swift", `public import Foundation + +public typealias WKTStruct = [String: WKTValue] +public typealias WKTStringValue = Swift.String +public typealias WKTInt64Value = Swift.Int64 + +public struct WKTValue: Codable, Equatable, Sendable { + public init() {} +} + +public struct WKTAny: Sendable { + public init() {} +} + +public struct _UnknownFields: Equatable, Sendable { + public var json: [String: WKTValue] = [:] + @_spi(GoogleCloudInternal) public var proto: Data = Data() + public init() {} +} + +public protocol _AnyPackable: Sendable { + static var _anyTypeUrl: String { get } + init(fromAny any: WKTAny) throws + func _pack() throws -> WKTStruct +} + +public func _anyDeserialize(_ type: T.Type, from any: WKTAny) throws -> T { + fatalError("unused") +} + +public func _anySerialize(message: T) throws -> WKTStruct { + [:] +} + +extension Swift.String: _AnyPackable { + public static var _anyTypeUrl: String { "type.googleapis.com/google.protobuf.StringValue" } + public init(fromAny any: WKTAny) throws { self = "" } + public func _pack() throws -> WKTStruct { [:] } +} + +extension Swift.Int64: _AnyPackable { + public static var _anyTypeUrl: String { "type.googleapis.com/google.protobuf.Int64Value" } + public init(fromAny any: WKTAny) throws { self = 0 } + public func _pack() throws -> WKTStruct { [:] } +} + +public struct WKTRecursive: Codable, Sendable { + private final class Storage: @unchecked Sendable { + var value: T + init(_ value: T) { self.value = value } + } + private var storage: Storage + public var value: T { storage.value } + public init(value: T) { self.storage = Storage(value) } + public init(from decoder: any Decoder) throws { self.storage = Storage(try T(from: decoder)) } + public func encode(to encoder: any Encoder) throws { try storage.value.encode(to: encoder) } +} + +extension WKTRecursive: Equatable where T: Equatable { + public static func == (lhs: WKTRecursive, rhs: WKTRecursive) -> Bool { + lhs.value == rhs.value + } +} +`) + + writeTestFile("Sources/GoogleWKTConvert/GoogleWKTConvert.swift", `public enum _GoogleWKTConvertStub {} +`) + + writeTestFile("Sources/GoogleType/ExtDetail.swift", `public struct ExtDetail: Codable, Equatable, Sendable { + public var code: Swift.Int32 = 0 + public init() {} + public func with(_ config: (inout Self) throws -> Swift.Void) rethrows -> Self { + var copy = self + try config(©) + return copy + } +} +`) + + writeTestFile("Sources/GoogleGax/GoogleGax.swift", `internal import Foundation + +public struct ClientOptions: Sendable { + public init() {} +} + +public struct RequestOptions: Sendable { + public var attemptTimeout: Duration? + public init() {} +} + +@_spi(GoogleCloudInternal) +public struct _RetryLoop: Sendable { + public init(options: RequestOptions, withDefault: ClientOptions, idempotent: Bool) {} + public func run(attempt: (Duration?) async throws -> Output) async throws -> Output { + try await attempt(nil) + } +} + +@_spi(GoogleCloudInternal) +public enum _RoutingSegment: Sendable, Equatable { + case literal(String) + case singleWildcard + case multiWildcard + case trailingMultiWildcard + + func matchLength(in haystack: Substring) -> Int? { + switch self { + case .literal(let lit): + return haystack.hasPrefix(lit) ? lit.count : nil + case .singleWildcard: + if haystack.isEmpty || haystack.hasPrefix("/") { + return nil + } + if let slashIndex = haystack.firstIndex(of: "/") { + return haystack.distance(from: haystack.startIndex, to: slashIndex) + } + return haystack.count + case .multiWildcard: + return haystack.count + case .trailingMultiWildcard: + if haystack.isEmpty { return 0 } + if haystack.hasPrefix("/") || haystack.hasPrefix(":") { return haystack.count } + return nil + } + } +} + +@_spi(GoogleCloudInternal) +public enum _RoutingMatcher { + private static let unreservedCharacterSet = CharacterSet( + charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~" + ) + + public static func encode(_ value: String) -> String { + value.addingPercentEncoding(withAllowedCharacters: unreservedCharacterSet) ?? value + } + + public static func format(_ matches: [(key: String, value: String?)]) -> [String] { + matches.compactMap { key, value in + guard let value, !value.isEmpty else { return nil } + return "\(encode(key))=\(encode(value))" + } + } + + public static func value( + _ haystack: String?, + prefix: [_RoutingSegment] = [], + matching: [_RoutingSegment], + suffix: [_RoutingSegment] = [] + ) -> String? { + guard let haystack, !haystack.isEmpty else { return nil } + var remains = Substring(haystack) + var startOffset = 0 + var endOffset = 0 + for needle in prefix { + guard let count = needle.matchLength(in: remains) else { return nil } + startOffset += count + endOffset += count + remains = remains.dropFirst(count) + } + for needle in matching { + guard let count = needle.matchLength(in: remains) else { return nil } + endOffset += count + remains = remains.dropFirst(count) + } + for needle in suffix { + guard let count = needle.matchLength(in: remains) else { return nil } + remains = remains.dropFirst(count) + } + guard remains.isEmpty, startOffset < endOffset else { return nil } + let start = haystack.index(haystack.startIndex, offsetBy: startOffset) + let end = haystack.index(haystack.startIndex, offsetBy: endOffset) + return String(haystack[start.. [String]? { + calls.last?.routingParams + } +} + +@_spi(GoogleCloudInternal) +public final class _GRPCClient: Sendable { + public let store = RecordedCallStore() + + public init(from options: ClientOptions, withDefaultEndpoint: String, clientHeader: String) throws {} + public init() {} + + public func execute( + path: String, + request: Request, + options: RequestOptions, + routingParams: [String] = [] + ) async throws -> Response { + await store.record(path: path, routingParams: routingParams) + return Response() + } +} +`) + + writeTestFile("Sources/RoutingTestProtos/Protos.swift", `public import SwiftProtobuf + +public struct Google_Cloud_Test_V1_RouteRequest: SwiftProtobuf.Message { + public init() {} +} + +public struct Google_Cloud_Test_V1_RouteResponse: SwiftProtobuf.Message { + public init() {} +} +`) + + writeTestFile("Sources/RoutingTestLib/Clients.swift", `internal import RoutingTestProtos + +public enum Clients { + static let clientHeader: Swift.String = "test-client" +} + +extension RouteRequest { + internal func toProto() throws -> RoutingTestProtos.Google_Cloud_Test_V1_RouteRequest { + .init() + } +} + +extension RouteResponse { + internal init(proto: RoutingTestProtos.Google_Cloud_Test_V1_RouteResponse) throws { + self.init() + } +} +`) + + writeTestFile("Tests/RoutingTestLibTests/RoutingTransportTests.swift", `@_spi(GoogleCloudInternal) import GoogleGax +@_spi(GoogleCloudInternal) import GoogleGaxGRPC +import GoogleType +import Testing +@testable import RoutingTestLib + +@Suite struct RoutingTransportTests { + @Test func scalarsAndEnums() async throws { + let client = GoogleGaxGRPC._GRPCClient() + let transport = Clients.RoutingTestServiceTransport(client) + + let populated = RouteRequest().with { + $0.pageSize = 42 + $0.optCount = 7 + $0.active = true + $0.state = .active + $0.optState = .unknownIntValue(99) + $0.info = Inner().with { + $0.count = 123 + $0.optState = .active + } + $0.extDetail = ExtDetail().with { + $0.code = 505 + } + } + _ = try await transport.explicitScalarsAndEnums(request: populated, options: .init()) + let got = await client.store.lastRoutingParams() + #expect( + got == [ + "page_size=42", + "opt_count=7", + "active=true", + "state=STATE_ACTIVE", + "opt_state=99", + "info_count=123", + "info_opt_state=STATE_ACTIVE", + "ext_code=505", + ] + ) + + let defaults = RouteRequest() + _ = try await transport.explicitScalarsAndEnums(request: defaults, options: .init()) + let gotDefaults = await client.store.lastRoutingParams() + #expect( + gotDefaults == [ + "page_size=0", + "active=false", + "state=STATE_UNSPECIFIED", + ] + ) + + let httpReq = RouteRequest().with { + $0.name = "projects/p1/buckets/b1" + $0.pageSize = 321 + $0.state = .active + } + _ = try await transport.implicitHttpBindings(request: httpReq, options: .init()) + let gotHTTP = await client.store.lastRoutingParams() + #expect( + gotHTTP == [ + "name=projects%2Fp1%2Fbuckets%2Fb1", + "page_size=321", + "state=STATE_ACTIVE", + ] + ) + } +} +`) + + args := []string{"test", "--package-path", pkgDir, "-Xswiftc", "-warnings-as-errors"} + if _, err := os.Stat("/usr/bin/gcc"); err == nil { + args = append(args, "-Xcc", "--gcc-toolchain=/usr", "-Xcxx", "--gcc-toolchain=/usr") + } + cmd := exec.CommandContext(t.Context(), "swift", args...) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("swift %v failed: %v\n%s", args, err, out) + } +} diff --git a/internal/sidekick/swift/generate_grpc_routing_test.go b/internal/sidekick/swift/generate_grpc_routing_test.go new file mode 100644 index 0000000000..fc2e9210be --- /dev/null +++ b/internal/sidekick/swift/generate_grpc_routing_test.go @@ -0,0 +1,378 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package swift + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/googleapis/librarian/internal/config" + "github.com/googleapis/librarian/internal/sidekick/api" +) + +func TestGenerateStub_GRPCClient_RoutingFieldTypes(t *testing.T) { + outDir := t.TempDir() + model := makeRoutingFieldTypesModel(t) + + module := &config.SwiftModule{ + Output: outDir, + ModuleType: "grpc-client", + ModulePath: "RoutingTestProtos", + } + swiftPkg := swiftConfig(t, []config.SwiftDependency{ + {Name: "GoogleType", ApiPackage: "google.type"}, + }) + swiftPkg.PackageNameOverride = "RoutingTestLib" + swiftPkg.LibraryNameOverride = "RoutingTestLib" + library := &config.Library{ + Name: "routing-test-lib", + Swift: swiftPkg, + } + + if err := Generate(t.Context(), model, outDir, library, module); err != nil { + t.Fatal(err) + } + + transportContent, err := os.ReadFile(filepath.Join(outDir, "RoutingTestService+Transport.swift")) + if err != nil { + t.Fatal(err) + } + transportStr := string(transportContent) + + for _, wantImport := range []string{"import GoogleType"} { + if !strings.Contains(transportStr, wantImport) { + t.Errorf("transport missing %q:\n%s", wantImport, transportStr) + } + } + + for _, test := range []struct { + method string + want string + }{ + { + method: "explicitScalarsAndEnums", + want: ` public func explicitScalarsAndEnums( + request: RouteRequest, options: GoogleGax.RequestOptions +) async throws -> RouteResponse + { + let routingParams = GoogleGaxGRPC._RoutingMatcher.format([ + ("page_size", + GoogleGaxGRPC._RoutingMatcher.value( + Swift.String(request.pageSize), + prefix: [], + matching: [.multiWildcard, ], + suffix: [] + ) + ), + ("opt_count", + GoogleGaxGRPC._RoutingMatcher.value( + request.optCount.map { Swift.String($0) }, + prefix: [], + matching: [.multiWildcard, ], + suffix: [] + ) + ), + ("active", + GoogleGaxGRPC._RoutingMatcher.value( + Swift.String(request.active), + prefix: [], + matching: [.multiWildcard, ], + suffix: [] + ) + ), + ("state", + GoogleGaxGRPC._RoutingMatcher.value( + request.state.stringValue ?? request.state.intValue.map { Swift.String($0) }, + prefix: [], + matching: [.multiWildcard, ], + suffix: [] + ) + ), + ("opt_state", + GoogleGaxGRPC._RoutingMatcher.value( + request.optState.flatMap { $0.stringValue ?? $0.intValue.map { Swift.String($0) } }, + prefix: [], + matching: [.multiWildcard, ], + suffix: [] + ) + ), + ("info_count", + GoogleGaxGRPC._RoutingMatcher.value( + (request.info?.count).map { Swift.String($0) }, + prefix: [], + matching: [.multiWildcard, ], + suffix: [] + ) + ), + ("info_opt_state", + GoogleGaxGRPC._RoutingMatcher.value( + (request.info?.optState).flatMap { $0.stringValue ?? $0.intValue.map { Swift.String($0) } }, + prefix: [], + matching: [.multiWildcard, ], + suffix: [] + ) + ), + ("ext_code", + GoogleGaxGRPC._RoutingMatcher.value( + (request.extDetail?.code).map { Swift.String($0) }, + prefix: [], + matching: [.multiWildcard, ], + suffix: [] + ) + ), + ]) + + let protoRequest = try request.toProto() + let protoResponse: RoutingTestProtos.Google_Cloud_Test_V1_RouteResponse = try await self.inner.execute( + path: "/google.cloud.test.v1.RoutingTestService/ExplicitScalarsAndEnums", + request: protoRequest, + options: options, + routingParams: routingParams + ) + return try RouteResponse(proto: protoResponse) + }`, + }, + { + method: "implicitHttpBindings", + want: ` public func implicitHttpBindings( + request: RouteRequest, options: GoogleGax.RequestOptions +) async throws -> RouteResponse + { + let routingParams = GoogleGaxGRPC._RoutingMatcher.format([ + ("name", + GoogleGaxGRPC._RoutingMatcher.value( + request.name, + prefix: [], + matching: [.multiWildcard, ], + suffix: [] + ) + ), + ("page_size", + GoogleGaxGRPC._RoutingMatcher.value( + Swift.String(request.pageSize), + prefix: [], + matching: [.multiWildcard, ], + suffix: [] + ) + ), + ("state", + GoogleGaxGRPC._RoutingMatcher.value( + request.state.stringValue ?? request.state.intValue.map { Swift.String($0) }, + prefix: [], + matching: [.multiWildcard, ], + suffix: [] + ) + ), + ]) + + let protoRequest = try request.toProto() + let protoResponse: RoutingTestProtos.Google_Cloud_Test_V1_RouteResponse = try await self.inner.execute( + path: "/google.cloud.test.v1.RoutingTestService/ImplicitHttpBindings", + request: protoRequest, + options: options, + routingParams: routingParams + ) + return try RouteResponse(proto: protoResponse) + }`, + }, + } { + t.Run(test.method, func(t *testing.T) { + got := extractBlock(t, transportStr, " public func "+test.method+"(", "\n }") + if diff := cmp.Diff(test.want, got); diff != "" { + t.Errorf("mismatch (-want +got):\n%s", diff) + } + }) + } +} + +func TestGenerateStub_GRPCClient_StringEnumsRouting(t *testing.T) { + outDir := t.TempDir() + modeEnum := api.NewTestEnum("Mode"). + WithPackage("google.cloud.test.v1"). + WithValues(api.NewTestEnumValue("MODE_FAST", 0)) + requestMsg := api.NewTestMessage("StringEnumRequest"). + WithPackage("google.cloud.test.v1"). + WithFields( + api.NewTestField("mode").WithEnumType(modeEnum), + api.NewTestField("opt_mode").WithEnumType(modeEnum).WithOptional(), + ) + responseMsg := api.NewTestMessage("StringEnumResponse").WithPackage("google.cloud.test.v1") + method := api.NewTestMethod("CheckMode"). + WithInput(requestMsg). + WithOutput(responseMsg). + WithRouting( + newWildcardRoutingInfo("mode", "mode"), + newWildcardRoutingInfo("opt_mode", "opt_mode"), + ) + service := api.NewTestService("StringEnumService"). + WithPackage("google.cloud.test.v1"). + WithDefaultHost("test.googleapis.com"). + WithMethods(method) + model := api.NewTestAPI([]*api.Message{requestMsg, responseMsg}, []*api.Enum{modeEnum}, []*api.Service{service}). + WithPackageName("google.cloud.test.v1") + if err := api.CrossReference(model); err != nil { + t.Fatal(err) + } + + library := &config.Library{ + Name: "routing-string-enum", + SpecificationFormat: config.SpecDiscovery, + Swift: swiftConfig(t, nil), + } + module := &config.SwiftModule{ + Output: outDir, + ModuleType: "grpc-client", + ModulePath: "StringEnumProtos", + } + if err := Generate(t.Context(), model, outDir, library, module); err != nil { + t.Fatal(err) + } + transportContent, err := os.ReadFile(filepath.Join(outDir, "StringEnumService+Transport.swift")) + if err != nil { + t.Fatal(err) + } + got := extractBlock(t, string(transportContent), " public func checkMode(", "\n }") + want := ` public func checkMode( + request: StringEnumRequest, options: GoogleGax.RequestOptions +) async throws -> StringEnumResponse + { + let routingParams = GoogleGaxGRPC._RoutingMatcher.format([ + ("mode", + GoogleGaxGRPC._RoutingMatcher.value( + request.mode.stringValue, + prefix: [], + matching: [.multiWildcard, ], + suffix: [] + ) + ), + ("opt_mode", + GoogleGaxGRPC._RoutingMatcher.value( + request.optMode.map { $0.stringValue }, + prefix: [], + matching: [.multiWildcard, ], + suffix: [] + ) + ), + ]) + + let protoRequest = try request.toProto() + let protoResponse: StringEnumProtos.Google_Cloud_Test_V1_StringEnumResponse = try await self.inner.execute( + path: "/google.cloud.test.v1.StringEnumService/CheckMode", + request: protoRequest, + options: options, + routingParams: routingParams + ) + return try StringEnumResponse(proto: protoResponse) + }` + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("mismatch (-want +got):\n%s", diff) + } +} + +func newWildcardRoutingInfo(key string, fieldPath ...string) *api.RoutingInfo { + return api.NewTestRoutingInfo( + key, + api.NewRoutingInfoVariantBuilder(). + WithFieldPath(fieldPath...). + WithMatchingSegments(api.MultiSegmentWildcard). + Build(), + ) +} + +func makeRoutingFieldTypesModel(t *testing.T) *api.API { + t.Helper() + + stateEnum := api.NewTestEnum("State"). + WithPackage("google.cloud.test.v1"). + WithValues( + api.NewTestEnumValue("STATE_UNSPECIFIED", 0), + api.NewTestEnumValue("STATE_ACTIVE", 1), + ) + + extDetailMsg := api.NewTestMessage("ExtDetail"). + WithPackage("google.type"). + WithFields( + api.NewTestField("code").WithType(api.TypezInt32), + ) + + innerMsg := api.NewTestMessage("Inner"). + WithPackage("google.cloud.test.v1"). + WithFields( + api.NewTestField("count").WithType(api.TypezInt32), + api.NewTestField("opt_count").WithType(api.TypezInt32).WithOptional(), + api.NewTestField("state").WithEnumType(stateEnum), + api.NewTestField("opt_state").WithEnumType(stateEnum).WithOptional(), + ) + + requestMsg := api.NewTestMessage("RouteRequest"). + WithPackage("google.cloud.test.v1"). + WithFields( + api.NewTestField("name").WithType(api.TypezString), + api.NewTestField("page_size").WithType(api.TypezInt32), + api.NewTestField("opt_count").WithType(api.TypezInt32).WithOptional(), + api.NewTestField("active").WithType(api.TypezBool), + api.NewTestField("state").WithEnumType(stateEnum), + api.NewTestField("opt_state").WithEnumType(stateEnum).WithOptional(), + api.NewTestField("info").WithMessageType(innerMsg).WithOptional(), + api.NewTestField("ext_detail").WithMessageType(extDetailMsg).WithOptional(), + ) + + responseMsg := api.NewTestMessage("RouteResponse"). + WithPackage("google.cloud.test.v1"). + WithFields( + api.NewTestField("result").WithType(api.TypezString), + ) + + explicitScalarsAndEnums := api.NewTestMethod("ExplicitScalarsAndEnums"). + WithInput(requestMsg). + WithOutput(responseMsg). + WithRouting( + newWildcardRoutingInfo("page_size", "page_size"), + newWildcardRoutingInfo("opt_count", "opt_count"), + newWildcardRoutingInfo("active", "active"), + newWildcardRoutingInfo("state", "state"), + newWildcardRoutingInfo("opt_state", "opt_state"), + newWildcardRoutingInfo("info_count", "info", "count"), + newWildcardRoutingInfo("info_opt_state", "info", "opt_state"), + newWildcardRoutingInfo("ext_code", "ext_detail", "code"), + ) + + implicitHTTPBindings := api.NewTestMethod("ImplicitHttpBindings"). + WithInput(requestMsg). + WithOutput(responseMsg). + WithBindings( + newTestPathBinding("GET", api.NewPathTemplateBuilder().WithLiteral("v1").WithVariableNamed("name").Build()), + newTestPathBinding("GET", api.NewPathTemplateBuilder().WithLiteral("v1").WithVariableNamed("page_size").WithVariableNamed("state").Build()), + ) + + service := api.NewTestService("RoutingTestService"). + WithPackage("google.cloud.test.v1"). + WithDefaultHost("test.googleapis.com"). + WithMethods(explicitScalarsAndEnums, implicitHTTPBindings) + + model := api.NewTestAPI( + []*api.Message{innerMsg, requestMsg, responseMsg}, + []*api.Enum{stateEnum}, + []*api.Service{service}, + ).WithPackageName("google.cloud.test.v1") + model.AddMessage(extDetailMsg) + if err := api.CrossReference(model); err != nil { + t.Fatal(err) + } + return model +} diff --git a/internal/sidekick/swift/templates/grpc/routing_value_expr.gotmpl b/internal/sidekick/swift/templates/grpc/routing_value_expr.gotmpl new file mode 100644 index 0000000000..cc4e34d035 --- /dev/null +++ b/internal/sidekick/swift/templates/grpc/routing_value_expr.gotmpl @@ -0,0 +1,47 @@ +{{/* +Copyright 2026 Google LLC + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ -}} +{{- define "grpc_routing_field_access" -}} +request + {{- range .FieldSteps -}} + {{- if .ChainOptional }}?.{{ else }}.{{ end }}{{ .PropertyName }} + {{- end -}} +{{- end -}} +{{- define "grpc_routing_optional_access" -}} + {{- if .NeedsParens }}({{ template "grpc_routing_field_access" . }}){{ else }}{{ template "grpc_routing_field_access" . }}{{ end -}} +{{- end -}} +{{- if .ConvertToString -}} + {{- if .IsOptional -}} + {{ template "grpc_routing_optional_access" . }}.map { Swift.String($0) } + {{- else -}} + Swift.String({{ template "grpc_routing_field_access" . }}) + {{- end -}} +{{- else if .IsEnum -}} + {{- if .IsStringEnum -}} + {{- if .IsOptional -}} + {{ template "grpc_routing_optional_access" . }}.map { $0.stringValue } + {{- else -}} + {{ template "grpc_routing_field_access" . }}.stringValue + {{- end -}} + {{- else -}} + {{- if .IsOptional -}} + {{ template "grpc_routing_optional_access" . }}.flatMap { $0.stringValue ?? $0.intValue.map { Swift.String($0) } } + {{- else -}} + {{ template "grpc_routing_field_access" . }}.stringValue ?? {{ template "grpc_routing_field_access" . }}.intValue.map { Swift.String($0) } + {{- end -}} + {{- end -}} +{{- else -}} + {{ template "grpc_routing_field_access" . }} +{{- end -}} diff --git a/internal/sidekick/swift/templates/grpc/transport.swift.gotmpl b/internal/sidekick/swift/templates/grpc/transport.swift.gotmpl index 5aeba2af0c..702197a3b8 100644 --- a/internal/sidekick/swift/templates/grpc/transport.swift.gotmpl +++ b/internal/sidekick/swift/templates/grpc/transport.swift.gotmpl @@ -65,7 +65,7 @@ extension Clients { ("{{ .RoutingKey }}", {{- range .Variants }} GoogleGaxGRPC._RoutingMatcher.value( - {{ .FieldAccessor }}, + {{ template "templates/grpc/routing_value_expr" . }}, prefix: [{{ range .PrefixSegments }}{{ . }}, {{ end }}], matching: [{{ range .MatchingSegments }}{{ . }}, {{ end }}], suffix: [{{ range .SuffixSegments }}{{ . }}, {{ end }}]