diff --git a/pkg/console/handler/service.go b/pkg/console/handler/service.go index d78ff5264..35058db38 100644 --- a/pkg/console/handler/service.go +++ b/pkg/console/handler/service.go @@ -132,13 +132,13 @@ func ServiceGenericInvoke(ctx consolectx.Context) gin.HandlerFunc { } if err := req.Validate(); err != nil { - util.HandleArgumentError(c, err) + writeGenericInvokeError(c, err) return } resp, err := service.InvokeServiceGeneric(ctx, req) if err != nil { - util.HandleServiceError(c, err) + writeGenericInvokeError(c, err) return } diff --git a/pkg/console/handler/service_generic_invoke_e2e_test.go b/pkg/console/handler/service_generic_invoke_e2e_test.go new file mode 100644 index 000000000..2a2091f0b --- /dev/null +++ b/pkg/console/handler/service_generic_invoke_e2e_test.go @@ -0,0 +1,331 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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 handler + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/gin-gonic/gin" + + meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1" + "github.com/apache/dubbo-admin/pkg/core/manager" + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" + coremodel "github.com/apache/dubbo-admin/pkg/core/resource/model" + "github.com/apache/dubbo-admin/pkg/core/store" + memoryst "github.com/apache/dubbo-admin/pkg/store/memory" +) + +func TestServiceGenericInvokeHTTPRealJavaProvider(t *testing.T) { + if os.Getenv("RUN_DUBBO_E2E") != "1" { + t.Skip("requires Java Dubbo Provider on 127.0.0.1:20880") + } + stores := make(map[coremodel.ResourceKind]store.ResourceStore) + + for _, kind := range []coremodel.ResourceKind{ + meshresource.InstanceKind, + meshresource.ServiceProviderMetadataKind, + meshresource.RPCInstanceKind, + } { + s := memoryst.NewMemoryResourceStore(kind) + if err := s.Init(nil); err != nil { + t.Fatal(err) + } + stores[kind] = s + } + + instance := meshresource.NewInstanceResourceWithAttributes( + "provider-1", "test-mesh", + ) + instance.Spec.AppName = "generic-e2e-provider" + instance.Spec.Ip = "127.0.0.1" + instance.Spec.RpcPort = 20880 + + if err := stores[meshresource.InstanceKind].Add(instance); err != nil { + t.Fatal(err) + } + + metadata := meshresource.NewServiceProviderMetadataResourceWithAttributes( + "echo-metadata", "test-mesh", + ) + metadata.Spec.ServiceName = "example.EchoService" + metadata.Spec.Methods = []*meshproto.Method{ + { + Name: "echo", + ParameterTypes: []string{"java.lang.String"}, + ReturnType: "java.lang.String", + }, + } + + if err := stores[meshresource.ServiceProviderMetadataKind].Add(metadata); err != nil { + t.Fatal(err) + } + + rpcName := meshresource.BuildInstanceResName( + "generic-e2e-provider", + "127.0.0.1", + 20880, + ) + + rpcInstance := meshresource.NewRPCInstanceResourceWithAttributes( + rpcName, "test-mesh", + ) + rpcInstance.Spec.Name = rpcName + rpcInstance.Spec.AppName = "generic-e2e-provider" + rpcInstance.Spec.Ip = "127.0.0.1" + rpcInstance.Spec.Port = 20880 + rpcInstance.Spec.Endpoints = []*meshproto.Endpoint{ + { + Protocol: "dubbo", + Port: 20880, + }, + } + + if err := stores[meshresource.RPCInstanceKind].Add(rpcInstance); err != nil { + t.Fatal(err) + } + + ctx := &genericHTTPTestContext{ + rm: manager.NewResourceManager( + &genericHTTPTestRouter{stores: stores}, + nil, + ), + } + + router := gin.New() + router.POST("/test/invoke", ServiceGenericInvoke(ctx)) + + body := `{ + "mesh": "test-mesh", + "serviceName": "example.EchoService", + "instanceName": "provider-1", + "methodName": "echo", + "signature": "java.lang.String->java.lang.String", + "args": ["hello"], + "timeoutMs": 0, + "attachments": { + "traceId": "abc" + } + }` + + req := httptest.NewRequest( + http.MethodPost, + "/test/invoke", + bytes.NewBufferString(body), + ) + req.Header.Set("Content-Type", "application/json") + + recorder := httptest.NewRecorder() + + router.ServeHTTP(recorder, req) + + if recorder.Code != http.StatusOK { + t.Fatalf( + "expected HTTP 200, got %d: %s", + recorder.Code, + recorder.Body.String(), + ) + } + + var response struct { + Code string `json:"code"` + Message string `json:"message"` + Data struct { + RawResult string `json:"rawResult"` + ElapsedMs int64 `json:"elapsedMs"` + } `json:"data"` + } + if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil { + t.Fatal(err) + } + if response.Code != "Success" { + t.Fatalf( + "expected Success, got %s: %s", + response.Code, + recorder.Body.String(), + ) + } + if response.Data.RawResult != "hello" { + t.Fatalf( + "expected hello, got %q", + response.Data.RawResult, + ) + } + + t.Logf("HTTP response: %s", recorder.Body.String()) +} + +func TestServiceGenericInvokeHTTPRealJavaProviderTriple(t *testing.T) { + if os.Getenv("RUN_DUBBO_E2E") != "1" { + t.Skip("requires Triple Java Provider on 127.0.0.1:50051") + } + + const ( + meshName = "test-mesh" + instanceName = "provider-1" + appName = "generic-e2e-provider" + serviceName = "example.EchoService" + providerIP = "127.0.0.1" + providerPort = 50051 + ) + + stores := make(map[coremodel.ResourceKind]store.ResourceStore) + + for _, kind := range []coremodel.ResourceKind{ + meshresource.InstanceKind, + meshresource.ServiceProviderMetadataKind, + meshresource.RPCInstanceKind, + } { + s := memoryst.NewMemoryResourceStore(kind) + if err := s.Init(nil); err != nil { + t.Fatal(err) + } + stores[kind] = s + } + instance := meshresource.NewInstanceResourceWithAttributes( + instanceName, + meshName, + ) + + instance.Spec.AppName = appName + instance.Spec.Ip = providerIP + instance.Spec.RpcPort = providerPort + + if err := stores[meshresource.InstanceKind].Add(instance); err != nil { + t.Fatal(err) + } + metadata := meshresource.NewServiceProviderMetadataResourceWithAttributes( + "echo-metadata", + meshName, + ) + + metadata.Spec.ServiceName = serviceName + metadata.Spec.Methods = []*meshproto.Method{ + { + Name: "echo", + ParameterTypes: []string{"java.lang.String"}, + ReturnType: "java.lang.String", + }, + } + + if err := stores[meshresource.ServiceProviderMetadataKind].Add(metadata); err != nil { + t.Fatal(err) + } + rpcName := meshresource.BuildInstanceResName( + appName, + providerIP, + providerPort, + ) + + rpcInstance := meshresource.NewRPCInstanceResourceWithAttributes( + rpcName, + meshName, + ) + + rpcInstance.Spec.Name = rpcName + rpcInstance.Spec.AppName = appName + rpcInstance.Spec.Ip = providerIP + rpcInstance.Spec.Port = providerPort + + rpcInstance.Spec.Endpoints = []*meshproto.Endpoint{ + { + Protocol: "tri", + Port: providerPort, + }, + } + + if err := stores[meshresource.RPCInstanceKind].Add(rpcInstance); err != nil { + t.Fatal(err) + } + ctx := &genericHTTPTestContext{ + rm: manager.NewResourceManager( + &genericHTTPTestRouter{stores: stores}, + nil, + ), + } + router := gin.New() + router.POST("/test/invoke", ServiceGenericInvoke(ctx)) + body := `{ + "mesh": "test-mesh", + "serviceName": "example.EchoService", + "instanceName": "provider-1", + "methodName": "echo", + "signature": "java.lang.String->java.lang.String", + "args": ["hello"], + "timeoutMs": 0, + "attachments": { + "traceId": "abc" + } + }` + + req := httptest.NewRequest( + http.MethodPost, + "/test/invoke", + bytes.NewBufferString(body), + ) + req.Header.Set("Content-Type", "application/json") + + recorder := httptest.NewRecorder() + + router.ServeHTTP(recorder, req) + + if recorder.Code != http.StatusOK { + t.Fatalf( + "expected HTTP 200, got %d: %s", + recorder.Code, + recorder.Body.String(), + ) + } + + var response struct { + Code string `json:"code"` + Message string `json:"message"` + Data struct { + RawResult string `json:"rawResult"` + ElapsedMs int64 `json:"elapsedMs"` + } `json:"data"` + } + + if err := json.Unmarshal( + recorder.Body.Bytes(), + &response, + ); err != nil { + t.Fatalf("invalid response JSON: %v", err) + } + + if response.Code != "Success" { + t.Fatalf( + "expected Success, got %q: %s", + response.Code, + recorder.Body.String(), + ) + } + + if response.Data.RawResult != "hello" { + t.Fatalf( + "expected hello, got %q", + response.Data.RawResult, + ) + } + + t.Logf("Triple HTTP response: %s", recorder.Body.String()) + t.Logf("Triple RPC elapsed: %d ms", response.Data.ElapsedMs) +} diff --git a/pkg/console/handler/service_generic_invoke_error.go b/pkg/console/handler/service_generic_invoke_error.go new file mode 100644 index 000000000..2f749fdc7 --- /dev/null +++ b/pkg/console/handler/service_generic_invoke_error.go @@ -0,0 +1,109 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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 handler + +import ( + "errors" + "net/http" + + "github.com/gin-gonic/gin" + + "github.com/apache/dubbo-admin/pkg/common/bizerror" + "github.com/apache/dubbo-admin/pkg/console/model" + "github.com/apache/dubbo-admin/pkg/console/service" + "github.com/apache/dubbo-admin/pkg/console/util" +) + +func writeGenericInvokeError(c *gin.Context, err error) { + var validationErr *model.ServiceGenericInvokeValidationError + if errors.As(err, &validationErr) { + writeGenericInvokeFieldResponse( + c, + model.NewBizErrorResp(bizerror.New(bizerror.InvalidArgument, validationErr.Error())), + validationErr.Field, + validationErr.Expected, + validationErr.Actual, + ) + return + } + + var fieldErr *service.GenericInvokeArgumentError + + if !errors.As(err, &fieldErr) { + util.HandleServiceError(c, err) + return + } + message := "invalid argument" + + switch fieldErr.Kind { + case service.ArgumentErrorType: + message = "invalid argument type" + if fieldErr.Cause != nil { + // Type causes come from local argument decoding, not RPC or service errors. + message += ": " + fieldErr.Cause.Error() + } + + case service.ArgumentErrorCount: + message = "invalid argument count" + + case service.ArgumentErrorSignature: + message = "invalid method signature" + } + + baseResp := model.NewBizErrorResp( + bizerror.New( + bizerror.InvalidArgument, + message, + ), + ) + if fieldErr.Kind == service.ArgumentErrorSignature { + var bizErr bizerror.Error + + if errors.As(err, &bizErr) { + baseResp = model.NewBizErrorResp(bizErr) + } + } + + writeGenericInvokeFieldResponse( + c, + baseResp, + fieldErr.Field, + fieldErr.Expected, + fieldErr.Actual, + ) +} + +func writeGenericInvokeFieldResponse( + c *gin.Context, + baseResp *model.CommonResp, + field string, + expected string, + actual string, +) { + c.JSON(http.StatusOK, struct { + *model.CommonResp + + Field string `json:"field"` + Expected string `json:"expected"` + Actual string `json:"actual"` + }{ + CommonResp: baseResp, + Field: field, + Expected: expected, + Actual: actual, + }) +} diff --git a/pkg/console/handler/service_generic_invoke_error_test.go b/pkg/console/handler/service_generic_invoke_error_test.go new file mode 100644 index 000000000..dd2467601 --- /dev/null +++ b/pkg/console/handler/service_generic_invoke_error_test.go @@ -0,0 +1,296 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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 handler + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + + "github.com/apache/dubbo-admin/pkg/common/bizerror" + "github.com/apache/dubbo-admin/pkg/console/service" +) + +func TestWriteGenericInvokeErrorStructuredType(t *testing.T) { + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + + err := &service.GenericInvokeArgumentError{ + Kind: service.ArgumentErrorType, + Field: "args[0]", + Expected: "int", + Actual: "string", + } + + writeGenericInvokeError(ctx, err) + + if recorder.Code != http.StatusOK { + t.Fatalf("unexpected HTTP status: %d", recorder.Code) + } + var response struct { + Code string `json:"code"` + Message string `json:"message"` + Field string `json:"field"` + Expected string `json:"expected"` + Actual string `json:"actual"` + } + + if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil { + t.Fatalf("invalid response JSON: %v", err) + } + if response.Message != "invalid argument type" { + t.Errorf( + "expected invalid argument type, got %s", + response.Message, + ) + } + + if response.Code != "InvalidArgument" { + t.Errorf("unexpected code: %s", response.Code) + } + + if response.Field != "args[0]" { + t.Errorf("unexpected field: %s", response.Field) + } + + if response.Expected != "int" { + t.Errorf("unexpected expected type: %s", response.Expected) + } + + if response.Actual != "string" { + t.Errorf("unexpected actual type: %s", response.Actual) + } +} + +func TestWriteGenericInvokeErrorWrappedError(t *testing.T) { + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + + fieldErr := &service.GenericInvokeArgumentError{ + Kind: service.ArgumentErrorType, + Field: "args[0]", + Expected: "int", + Actual: "string", + } + + wrappedErr := fmt.Errorf( + "%w: %w", + bizerror.New( + bizerror.InvalidArgument, + "invalid generic invoke arguments", + ), + fieldErr, + ) + writeGenericInvokeError(ctx, wrappedErr) + + var response struct { + Code string `json:"code"` + Field string `json:"field"` + Expected string `json:"expected"` + Actual string `json:"actual"` + Message string `json:"message"` + } + + if err := json.Unmarshal( + recorder.Body.Bytes(), + &response, + ); err != nil { + t.Fatal(err) + } + + if response.Message != "invalid argument type" { + t.Errorf( + "expected invalid argument type, got %s", + response.Message, + ) + } + + if response.Code != "InvalidArgument" { + t.Errorf("unexpected code: %s", response.Code) + } + + if response.Field != "args[0]" { + t.Errorf("unexpected field: %s", response.Field) + } + + if response.Expected != "int" { + t.Errorf("unexpected expected: %s", response.Expected) + } + + if response.Actual != "string" { + t.Errorf("unexpected actual: %s", response.Actual) + } +} + +func TestWriteGenericInvokeErrorCountMismatch(t *testing.T) { + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + err := &service.GenericInvokeArgumentError{ + Kind: service.ArgumentErrorCount, + Field: "args", + Expected: "2", + Actual: "1", + } + + writeGenericInvokeError(ctx, err) + if recorder.Code != http.StatusOK { + t.Fatalf( + "unexpected HTTP status: %d", + recorder.Code, + ) + } + + var response struct { + Code string `json:"code"` + Message string `json:"message"` + Field string `json:"field"` + Expected string `json:"expected"` + Actual string `json:"actual"` + } + + if err := json.Unmarshal( + recorder.Body.Bytes(), + &response, + ); err != nil { + t.Fatal(err) + } + + if response.Code != "InvalidArgument" { + t.Errorf("unexpected code: %s", response.Code) + } + + if response.Message != "invalid argument count" { + t.Errorf("unexpected message: %s", response.Message) + } + + if response.Field != "args" { + t.Errorf("unexpected field: %s", response.Field) + } + + if response.Expected != "2" { + t.Errorf("unexpected expected: %s", response.Expected) + } + + if response.Actual != "1" { + t.Errorf("unexpected actual: %s", response.Actual) + } +} + +func TestWriteGenericInvokeErrorFallback(t *testing.T) { + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + err := bizerror.New( + bizerror.NotFoundError, + "method not found", + ) + + writeGenericInvokeError(ctx, err) + + if recorder.Code != http.StatusOK { + t.Fatalf( + "unexpected HTTP status: %d", + recorder.Code, + ) + } + + var response struct { + Code string `json:"code"` + Message string `json:"message"` + Field json.RawMessage `json:"field"` + Expected json.RawMessage `json:"expected"` + Actual json.RawMessage `json:"actual"` + } + + if err := json.Unmarshal( + recorder.Body.Bytes(), + &response, + ); err != nil { + t.Fatal(err) + } + if response.Code != "NotFoundError" { + t.Errorf( + "expected NotFoundError, got %s", + response.Code, + ) + } + if response.Message != "method not found" { + t.Errorf( + "unexpected message: %s", + response.Message, + ) + } + if response.Field != nil || + response.Expected != nil || + response.Actual != nil { + t.Fatalf( + "unexpected structured fields: %s", + recorder.Body.String(), + ) + } +} + +func TestWriteGenericInvokeErrorTypeCause(t *testing.T) { + tests := []struct { + name, expected, actual, cause string + }{ + {"byte overflow", "byte", "number", "value 300 out of range"}, + {"primitive null", "int", "null", "null is not allowed for primitive type int"}, + {"invalid array element", "int[]", "array", "invalid array element at index 1: value 2147483648 out of range"}, + {"float32 overflow", "float", "number", "value 1e+40 out of float32 range"}, + {"nil cause", "int", "string", ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fieldErr := &service.GenericInvokeArgumentError{ + Kind: service.ArgumentErrorType, Field: "args[0]", Expected: tt.expected, Actual: tt.actual, + } + if tt.cause != "" { + fieldErr.Cause = errors.New(tt.cause) + } + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + // Service wrappers can contain internal context; expose only the decoding cause. + writeGenericInvokeError(ctx, fmt.Errorf("internal service context: %w", fieldErr)) + if recorder.Code != http.StatusOK { + t.Fatalf("unexpected HTTP status: %d", recorder.Code) + } + var response struct{ Code, Message, Field, Expected, Actual string } + if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil { + t.Fatal(err) + } + want := "invalid argument type" + if tt.cause != "" { + want += ": " + tt.cause + } + if response.Message != want { + t.Errorf("want message %q, got %q", want, response.Message) + } + if response.Code != "InvalidArgument" || response.Field != "args[0]" || response.Expected != tt.expected || response.Actual != tt.actual { + t.Errorf("unexpected structured response: %+v", response) + } + if strings.Contains(recorder.Body.String(), "internal service context") { + t.Fatal("internal context leaked") + } + }) + } +} diff --git a/pkg/console/handler/service_generic_invoke_http_test.go b/pkg/console/handler/service_generic_invoke_http_test.go new file mode 100644 index 000000000..b31d77024 --- /dev/null +++ b/pkg/console/handler/service_generic_invoke_http_test.go @@ -0,0 +1,303 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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 handler + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + + meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1" + consolectx "github.com/apache/dubbo-admin/pkg/console/context" + "github.com/apache/dubbo-admin/pkg/core/manager" + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" + coremodel "github.com/apache/dubbo-admin/pkg/core/resource/model" + "github.com/apache/dubbo-admin/pkg/core/store" + memoryst "github.com/apache/dubbo-admin/pkg/store/memory" +) + +type genericHTTPTestContext struct { + consolectx.Context + rm manager.ResourceManager +} + +func (c *genericHTTPTestContext) AppContext() context.Context { + return context.Background() +} + +func (c *genericHTTPTestContext) ResourceManager() manager.ResourceManager { + return c.rm +} + +type genericHTTPTestRouter struct { + stores map[coremodel.ResourceKind]store.ResourceStore +} + +func (r *genericHTTPTestRouter) ResourceRoute( + res coremodel.Resource, +) (store.ResourceStore, error) { + return r.ResourceKindRoute(res.ResourceKind()) +} + +func (r *genericHTTPTestRouter) ResourceKindRoute( + kind coremodel.ResourceKind, +) (store.ResourceStore, error) { + s, ok := r.stores[kind] + if !ok { + return nil, fmt.Errorf("store not found for %s", kind) + } + return s, nil +} + +func TestServiceGenericInvokeHTTPValidation(t *testing.T) { + stores := make(map[coremodel.ResourceKind]store.ResourceStore) + + for _, kind := range []coremodel.ResourceKind{ + meshresource.InstanceKind, + meshresource.ServiceProviderMetadataKind, + } { + s := memoryst.NewMemoryResourceStore(kind) + + if err := s.Init(nil); err != nil { + t.Fatal(err) + } + + stores[kind] = s + } + + instance := meshresource.NewInstanceResourceWithAttributes( + "provider-1", + "test-mesh", + ) + + instance.Spec.AppName = "calculator" + instance.Spec.Ip = "127.0.0.1" + instance.Spec.RpcPort = 20880 + + if err := stores[meshresource.InstanceKind].Add(instance); err != nil { + t.Fatal(err) + } + + metadata := meshresource.NewServiceProviderMetadataResourceWithAttributes( + "calculator-metadata", + "test-mesh", + ) + + metadata.Spec.ServiceName = "example.Calculator" + metadata.Spec.Methods = []*meshproto.Method{ + { + Name: "add", + ParameterTypes: []string{"int", "int"}, + ReturnType: "int", + }, + } + + if err := stores[meshresource.ServiceProviderMetadataKind].Add(metadata); err != nil { + t.Fatal(err) + } + + ctx := &genericHTTPTestContext{ + rm: manager.NewResourceManager( + &genericHTTPTestRouter{stores: stores}, + nil, + ), + } + + router := gin.New() + + router.POST( + "/test/invoke", + ServiceGenericInvoke(ctx), + ) + + tests := []struct { + name string + body string + wantHTTPStatus int + wantCode string + wantMessage string + wantField string + wantExpected string + wantActual string + }{ + { + name: "count_mismatch", + body: `{ + "mesh": "test-mesh", + "serviceName": "example.Calculator", + "instanceName": "provider-1", + "methodName": "add", + "signature": "int,int->int", + "args": [10], + "timeoutMs": 3000 + }`, + + wantHTTPStatus: http.StatusOK, + wantCode: "InvalidArgument", + wantMessage: "invalid argument count", + wantField: "args", + wantExpected: "2", + wantActual: "1", + }, + { + name: "unknown_signature", + body: `{ + "mesh": "test-mesh", + "serviceName": "example.Calculator", + "instanceName": "provider-1", + "methodName": "add", + "signature": "int->int", + "args": [10, 20], + "timeoutMs": 3000 + }`, + + wantHTTPStatus: http.StatusOK, + wantCode: "NotFoundError", + wantMessage: "method add not found for service example.Calculator", + wantField: "signature", + wantExpected: "int,int->int", + wantActual: "int->int", + }, + { + name: "empty_args", + + body: `{ + "mesh": "test-mesh", + "serviceName": "example.Calculator", + "instanceName": "provider-1", + "methodName": "add", + "signature": "int,int->int", + "args": [], + "timeoutMs": 3000 + }`, + + wantHTTPStatus: http.StatusOK, + wantCode: "InvalidArgument", + wantMessage: "invalid argument count", + wantField: "args", + wantExpected: "2", + wantActual: "0", + }, + { + name: "missing_signature", + body: `{ + "mesh": "test-mesh", + "serviceName": "example.Calculator", + "instanceName": "provider-1", + "methodName": "add", + "args": [10, 20], + "timeoutMs": 3000 + }`, + + wantHTTPStatus: http.StatusOK, + wantCode: "InvalidArgument", + wantMessage: "signature is empty", + wantField: "signature", + wantExpected: "non-empty", + wantActual: "", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + req := httptest.NewRequest( + http.MethodPost, + "/test/invoke", + bytes.NewBufferString(tt.body), + ) + + req.Header.Set( + "Content-Type", + "application/json", + ) + + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, req) + + if recorder.Code != tt.wantHTTPStatus { + t.Fatalf( + "expected HTTP status %d, got %d, body: %s", + tt.wantHTTPStatus, + recorder.Code, + recorder.Body.String(), + ) + } + + var response struct { + Code string `json:"code"` + Message string `json:"message"` + Field string `json:"field"` + Expected string `json:"expected"` + Actual string `json:"actual"` + } + + if err := json.Unmarshal( + recorder.Body.Bytes(), + &response, + ); err != nil { + t.Fatalf( + "invalid response JSON: %v, body: %s", + err, + recorder.Body.String(), + ) + } + + if response.Code != tt.wantCode { + t.Errorf( + "expected code %q, got %q", + tt.wantCode, + response.Code, + ) + } + + if response.Message != tt.wantMessage { + t.Errorf( + "expected message %q, got %q", + tt.wantMessage, + response.Message, + ) + } + if response.Field != tt.wantField { + t.Errorf( + "expected field %q, got %q", + tt.wantField, + response.Field, + ) + } + if response.Expected != tt.wantExpected { + t.Errorf( + "expected value %q, got %q", + tt.wantExpected, + response.Expected, + ) + } + if response.Actual != tt.wantActual { + t.Errorf( + "expected actual %q, got %q", + tt.wantActual, + response.Actual, + ) + } + }) + } +} diff --git a/pkg/console/model/service.go b/pkg/console/model/service.go index 09b236de8..5cba9f7ba 100644 --- a/pkg/console/model/service.go +++ b/pkg/console/model/service.go @@ -173,6 +173,18 @@ type ServiceMethodTypeResp struct { const DefaultServiceGenericInvokeTimeoutMs int64 = 3000 +// ServiceGenericInvokeValidationError describes an invalid request field. +type ServiceGenericInvokeValidationError struct { + Field string + Expected string + Actual string + Message string +} + +func (e *ServiceGenericInvokeValidationError) Error() string { + return e.Message +} + type ServiceGenericInvokeReq struct { BaseServiceReq @@ -187,27 +199,52 @@ type ServiceGenericInvokeReq struct { func (s *ServiceGenericInvokeReq) Validate() error { s.Mesh = strings.TrimSpace(s.Mesh) if strutil.IsBlank(s.Mesh) { - return fmt.Errorf("mesh is empty") + return &ServiceGenericInvokeValidationError{ + Field: "mesh", + Expected: "non-empty", + Actual: s.Mesh, + Message: "mesh is empty", + } } s.ServiceName = strings.TrimSpace(s.ServiceName) if strutil.IsBlank(s.ServiceName) { - return fmt.Errorf("service name is empty") + return &ServiceGenericInvokeValidationError{ + Field: "serviceName", + Expected: "non-empty", + Actual: s.ServiceName, + Message: "service name is empty", + } } s.MethodName = strings.TrimSpace(s.MethodName) if strutil.IsBlank(s.MethodName) { - return fmt.Errorf("method name is empty") + return &ServiceGenericInvokeValidationError{ + Field: "methodName", + Expected: "non-empty", + Actual: s.MethodName, + Message: "method name is empty", + } } s.Signature = strings.TrimSpace(s.Signature) if strutil.IsBlank(s.Signature) { - return fmt.Errorf("signature is empty") + return &ServiceGenericInvokeValidationError{ + Field: "signature", + Expected: "non-empty", + Actual: s.Signature, + Message: "signature is empty", + } } s.InstanceName = strings.TrimSpace(s.InstanceName) if strutil.IsBlank(s.InstanceName) { - return fmt.Errorf("instance name is empty") + return &ServiceGenericInvokeValidationError{ + Field: "instanceName", + Expected: "non-empty", + Actual: s.InstanceName, + Message: "instance name is empty", + } } s.Group = strings.TrimSpace(s.Group) diff --git a/pkg/console/model/service_generic_invoke_test.go b/pkg/console/model/service_generic_invoke_test.go new file mode 100644 index 000000000..d2fcd216c --- /dev/null +++ b/pkg/console/model/service_generic_invoke_test.go @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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 model + +import ( + "testing" +) + +func TestServiceGenericInvokeReqDefaultTimeout(t *testing.T) { + req := ServiceGenericInvokeReq{ + BaseServiceReq: BaseServiceReq{ + Mesh: "test", + ServiceName: "com.example.EchoService", + }, + InstanceName: "provider-1", + MethodName: "echo", + Signature: "java.lang.String", + TimeoutMs: 0, + } + + if err := req.Validate(); err != nil { + t.Fatalf("Validate failed: %v", err) + } + + if req.TimeoutMs != 3000 { + t.Fatalf( + "expected timeout 3000, got %d", + req.TimeoutMs, + ) + } +} diff --git a/pkg/console/service/generic_filter_wire_test.go b/pkg/console/service/generic_filter_wire_test.go new file mode 100644 index 000000000..25a2a0b2e --- /dev/null +++ b/pkg/console/service/generic_filter_wire_test.go @@ -0,0 +1,244 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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 service + +import ( + "context" + "net/url" + "reflect" + "testing" + + hessian "github.com/apache/dubbo-go-hessian2" + + "dubbo.apache.org/dubbo-go/v3/common" + "dubbo.apache.org/dubbo-go/v3/common/constant" + "dubbo.apache.org/dubbo-go/v3/common/extension" + _ "dubbo.apache.org/dubbo-go/v3/filter/generic" + "dubbo.apache.org/dubbo-go/v3/protocol/base" + "dubbo.apache.org/dubbo-go/v3/protocol/invocation" + "dubbo.apache.org/dubbo-go/v3/protocol/result" +) + +type genericWireCaptureInvoker struct { + *base.BaseInvoker + + captured base.Invocation + calls int +} + +func (c *genericWireCaptureInvoker) Invoke( + _ context.Context, + inv base.Invocation, +) result.Result { + c.calls++ + c.captured = inv + + return &result.RPCResult{} +} + +func TestGenericFilterTripleNonIDLWireContract(t *testing.T) { + gf, ok := extension.GetFilter(constant.GenericFilterKey) + if !ok { + t.Fatal("Generic Filter is not registered") + } + u := common.NewURLWithOptions( + common.WithParams(url.Values{}), + common.WithParamsValue( + constant.GenericKey, + constant.GenericSerializationDefault, + ), + ) + + next := &genericWireCaptureInvoker{ + BaseInvoker: base.NewBaseInvoker(u), + } + + types := []string{"java.lang.String"} + args := []hessian.Object{"hello"} + + var reply any + + original := invocation.NewRPCInvocationWithOptions( + invocation.WithMethodName(constant.Generic), + invocation.WithArguments([]any{ + "echo", + types, + args, + }), + invocation.WithReply(&reply), + invocation.WithAttachments(map[string]any{ + "traceId": "abc", + }), + ) + res := gf.Invoke( + context.Background(), + next, + original, + ) + + if res == nil { + t.Fatal("expected non-nil result") + } + if err := res.Error(); err != nil { + t.Fatalf("unexpected filter error: %v", err) + } + if next.calls != 1 { + t.Fatalf( + "expected 1 downstream invocation, got %d", + next.calls, + ) + } + + if next.captured == nil { + t.Fatal("expected captured invocation") + } + + got := next.captured + if got.MethodName() != constant.Generic { + t.Fatalf( + "expected method %q, got %q", + constant.Generic, + got.MethodName(), + ) + } + wantArgs := []any{"echo", types, args} + + if !reflect.DeepEqual(got.Arguments(), wantArgs) { + t.Fatalf( + "unexpected Arguments:\n got: %#v\nwant: %#v", + got.Arguments(), + wantArgs, + ) + } + raw := got.ParameterRawValues() + + if len(raw) != 4 { + t.Fatalf( + "expected 4 raw values, got %d: %#v", + len(raw), + raw, + ) + } + if !reflect.DeepEqual(raw[:3], wantArgs) { + t.Fatalf( + "unexpected request raw values:\n got: %#v\nwant: %#v", + raw[:3], + wantArgs, + ) + } + if raw[3] != &reply { + t.Fatalf( + "reply pointer changed: got %#v", + raw[3], + ) + } + + if got.Reply() != &reply { + t.Fatal("Invocation.Reply pointer changed") + } + callType, exists := got.GetAttribute(constant.CallTypeKey) + + if !exists || callType != constant.CallUnary { + t.Fatalf( + "expected CallUnary, got %#v, exists=%v", + callType, + exists, + ) + } + if traceID := got.GetAttachmentWithDefaultValue( + "traceId", "", + ); traceID != "abc" { + t.Fatalf( + "expected traceId=abc, got %q", + traceID, + ) + } + + t.Log("Generic Filter wire contract verified") + t.Logf("method: %s", got.MethodName()) + t.Logf("Arguments length: %d", len(got.Arguments())) + t.Logf("ParameterRawValues length: %d", len(raw)) + t.Logf("CallType: %v", callType) +} + +func TestGenericFilterPreservesExplicitCallType(t *testing.T) { + gf, ok := extension.GetFilter(constant.GenericFilterKey) + if !ok { + t.Fatal("Generic Filter is not registered") + } + + u := common.NewURLWithOptions( + common.WithParams(url.Values{}), + common.WithParamsValue( + constant.GenericKey, + constant.GenericSerializationDefault, + ), + ) + + next := &genericWireCaptureInvoker{ + BaseInvoker: base.NewBaseInvoker(u), + } + + types := []string{"java.lang.String"} + args := []hessian.Object{"hello"} + + var reply any + + original := invocation.NewRPCInvocationWithOptions( + invocation.WithMethodName(constant.Generic), + invocation.WithArguments([]any{ + "echo", + types, + args, + }), + invocation.WithReply(&reply), + invocation.WithAttachments(map[string]any{}), + ) + original.SetAttribute( + constant.CallTypeKey, + constant.CallServerStream, + ) + + res := gf.Invoke(context.Background(), next, original) + + if res == nil { + t.Fatal("expected non-nil result") + } + if err := res.Error(); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if next.calls != 1 || next.captured == nil { + t.Fatalf( + "expected one captured invocation, got %d", + next.calls, + ) + } + + callType, exists := next.captured.GetAttribute( + constant.CallTypeKey, + ) + + if !exists || callType != constant.CallServerStream { + t.Fatalf( + "expected preserved CallServerStream, got %#v", + callType, + ) + } + + t.Logf("explicit CallType preserved: %v", callType) +} diff --git a/pkg/console/service/service_generic_invoke.go b/pkg/console/service/service_generic_invoke.go index 8fa5b8b05..0670e59d6 100644 --- a/pkg/console/service/service_generic_invoke.go +++ b/pkg/console/service/service_generic_invoke.go @@ -115,23 +115,70 @@ func InvokeServiceGeneric(ctx consolectx.Context, req model.ServiceGenericInvoke } resolvedMethod := findMethod(metadataList, req.MethodName, req.Signature) if resolvedMethod == nil { - err := bizerror.New( + bizErr := bizerror.New( bizerror.NotFoundError, - fmt.Sprintf("method %s not found for service %s", req.MethodName, req.ServiceName), + fmt.Sprintf( + "method %s not found for service %s", + req.MethodName, + req.ServiceName, + ), ) - logger.Errorf("resolve service method failed, service=%s, mesh=%s, instance=%s, method=%s, cause: %v", - req.ServiceName, req.Mesh, req.InstanceName, req.MethodName, err) - return nil, err + + logger.Errorf( + "resolve service method failed, service=%s, mesh=%s, instance=%s, method=%s, cause: %v", + req.ServiceName, + req.Mesh, + req.InstanceName, + req.MethodName, + bizErr, + ) + + var expectedSignatures []string + + for _, method := range collectMethods(metadataList) { + if method.GetName() == req.MethodName { + expectedSignatures = append( + expectedSignatures, + methodSig(method), + ) + } + } + if len(expectedSignatures) == 0 { + return nil, bizErr + } + fieldErr := &GenericInvokeArgumentError{ + Kind: ArgumentErrorSignature, + Field: "signature", + Expected: strings.Join(expectedSignatures, " | "), + Actual: req.Signature, + } + return nil, fmt.Errorf("%w: %w", bizErr, fieldErr) } parameterTypes := resolvedMethod.GetParameterTypes() if len(parameterTypes) != len(req.Args) { - return nil, bizerror.New(bizerror.InvalidArgument, "resolved method parameter count does not match args length") + fieldErr := &GenericInvokeArgumentError{ + Field: "args", + Expected: fmt.Sprintf("%d", len(parameterTypes)), + Actual: fmt.Sprintf("%d", len(req.Args)), + Kind: ArgumentErrorCount, + } + + return nil, fmt.Errorf( + "%w: %w", + bizerror.New( + bizerror.InvalidArgument, + "resolved method parameter count does not match args length", + ), + fieldErr, + ) } decodedArgs, err := decodeGenericInvokeArgs(parameterTypes, req.Args) if err != nil { - return nil, bizerror.New(bizerror.InvalidArgument, err.Error()) + return nil, fmt.Errorf( + "%w: %w", bizerror.New(bizerror.InvalidArgument, "invalid generic invoke arguments"), err, + ) } rpcInstanceRes, err := findRPCInstanceByInstance(ctx, instanceRes) diff --git a/pkg/console/service/service_generic_invoke_decode.go b/pkg/console/service/service_generic_invoke_decode.go index 36b16428c..cb5ef40b8 100644 --- a/pkg/console/service/service_generic_invoke_decode.go +++ b/pkg/console/service/service_generic_invoke_decode.go @@ -18,9 +18,12 @@ package service import ( + "bytes" "encoding/json" "fmt" "math" + "math/big" + "regexp" "strconv" "strings" ) @@ -34,7 +37,22 @@ func decodeGenericInvokeArgs(parameterTypes []string, args []json.RawMessage) ([ for index, arg := range args { decodedArg, err := decodeGenericInvokeArg(parameterTypes[index], arg) if err != nil { - return nil, fmt.Errorf("invalid argument at index %d for type %s: %w", index, strings.TrimSpace(parameterTypes[index]), err) + expected := strings.TrimSpace(parameterTypes[index]) + + fieldErr := &GenericInvokeArgumentError{ + Field: fmt.Sprintf("args[%d]", index), + Expected: expected, + Actual: genericJSONType(arg), + Cause: err, + Kind: ArgumentErrorType, + } + + return nil, fmt.Errorf( + "invalid argument at index %d for type %s: %w", + index, + expected, + fieldErr, + ) } decodedArgs[index] = decodedArg } @@ -42,8 +60,14 @@ func decodeGenericInvokeArgs(parameterTypes []string, args []json.RawMessage) ([ } func decodeGenericInvokeArg(parameterType string, raw json.RawMessage) (any, error) { + parameterType = strings.TrimSpace(parameterType) if isNullRawMessage(raw) { - return nil, nil + switch parameterType { + case "byte", "short", "int", "long", "float", "double", "boolean", "char": + return nil, fmt.Errorf("null is not allowed for primitive type %s", parameterType) + default: + return nil, nil + } } if parameterType == "" { return decodeJSONValue(raw) @@ -54,6 +78,18 @@ func decodeGenericInvokeArg(parameterType string, raw json.RawMessage) (any, err } switch parameterType { + case "java.lang.String", "String": + var value string + if err := json.Unmarshal(raw, &value); err != nil { + return nil, fmt.Errorf("expected JSON string: %w", err) + } + return value, nil + case "boolean", "java.lang.Boolean": + var value bool + if err := json.Unmarshal(raw, &value); err != nil { + return nil, fmt.Errorf("expected JSON boolean: %w", err) + } + return value, nil case "byte", "java.lang.Byte": return decodeInt8Raw(raw) case "short", "java.lang.Short": @@ -157,6 +193,9 @@ func decodeFloat32Raw(raw json.RawMessage) (float32, error) { if err != nil { return 0, err } + if math.Abs(value) > math.MaxFloat32 { + return 0, fmt.Errorf("value %v out of float32 range", value) + } return float32(value), nil } @@ -235,19 +274,50 @@ func parseJSONStringRaw(raw json.RawMessage) (string, bool, error) { return value, true, nil } +// Accept decimal text (including scientific notation), excluding Go literal syntax. +var genericInvokeDecimalPattern = regexp.MustCompile(`^[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$`) + func parseInt64Text(text string) (int64, error) { text = strings.TrimSpace(text) if text == "" { return 0, fmt.Errorf("empty value") } - if strings.ContainsAny(text, ".eE") { - value, err := parseFloat64Text(text) - if err != nil { - return 0, err + + // Bound numeric input before arbitrary-precision parsing. + const ( + maxNumericTextLen = 64 + maxExponent = 64 + ) + if len(text) > maxNumericTextLen { + return 0, fmt.Errorf("integer value is too long") + } + if !genericInvokeDecimalPattern.MatchString(text) { + return 0, fmt.Errorf("invalid integer value %q", text) + } + if !strings.ContainsAny(text, ".eE") { + return strconv.ParseInt(text, 10, 64) + } + + // Reject excessive exponents before allocating big integers. + if index := strings.IndexAny(text, "eE"); index >= 0 { + exp, err := strconv.ParseInt(text[index+1:], 10, 64) + if err != nil || exp < -maxExponent || exp > maxExponent { + return 0, fmt.Errorf("invalid integer exponent in %q", text) } - return int64FromFloat(value) } - return strconv.ParseInt(text, 10, 64) + + // Parse exactly without float64 precision loss. + value, ok := new(big.Rat).SetString(text) + if !ok { + return 0, fmt.Errorf("invalid integer value %q", text) + } + if !value.IsInt() { + return 0, fmt.Errorf("value %q is not an integer", text) + } + if !value.Num().IsInt64() { + return 0, fmt.Errorf("value %q out of int64 range", text) + } + return value.Num().Int64(), nil } func parseFloat64Text(text string) (float64, error) { @@ -265,19 +335,29 @@ func parseFloat64Text(text string) (float64, error) { return value, nil } -func int64FromFloat(value float64) (int64, error) { - if math.IsNaN(value) || math.IsInf(value, 0) { - return 0, fmt.Errorf("invalid numeric value") - } - if math.Trunc(value) != value { - return 0, fmt.Errorf("value %v is not an integer", value) - } - if value < math.MinInt64 || value > math.MaxInt64 { - return 0, fmt.Errorf("value %v out of range", value) - } - return int64(value), nil -} - func isNullRawMessage(raw json.RawMessage) bool { return strings.TrimSpace(string(raw)) == "null" } + +func genericJSONType(raw json.RawMessage) string { + raw = bytes.TrimSpace(raw) + + if !json.Valid(raw) { + return "invalid JSON" + } + + switch raw[0] { + case '"': + return "string" + case '{': + return "object" + case '[': + return "array" + case 't', 'f': + return "boolean" + case 'n': + return "null" + default: + return "number" + } +} diff --git a/pkg/console/service/service_generic_invoke_decode_test.go b/pkg/console/service/service_generic_invoke_decode_test.go new file mode 100644 index 000000000..595dcfbf8 --- /dev/null +++ b/pkg/console/service/service_generic_invoke_decode_test.go @@ -0,0 +1,339 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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 service + +import ( + "encoding/json" + "errors" + "reflect" + "strings" + "testing" +) + +func TestDecodeGenericInvokeArgsCountMismatch(t *testing.T) { + parameterTypes := []string{"int", "int"} + args := []json.RawMessage{ + json.RawMessage(`10`), + } + + result, err := decodeGenericInvokeArgs(parameterTypes, args) + if err == nil { + t.Fatal("expected parameter count mismatch error") + } + if !strings.Contains(err.Error(), "count 2 does not match args count 1") { + t.Fatalf("unexpected error: %v", err) + } + if result != nil { + t.Fatalf("expected nil result, got %v", result) + } +} + +func TestDecodeGenericInvokeArgsInvalidType(t *testing.T) { + parameterTypes := []string{"int", "int"} + args := []json.RawMessage{ + json.RawMessage(`"hello"`), + json.RawMessage(`20`), + } + result, err := decodeGenericInvokeArgs(parameterTypes, args) + + if err == nil { + t.Fatal("expected invalid argument type error") + } + if !strings.Contains( + err.Error(), + "invalid argument at index 0 for type int", + ) { + t.Fatalf("unexpected error: %v", err) + } + if result != nil { + t.Fatalf("expected nil result, got %v", result) + } +} + +func TestDecodeGenericInvokeArgsStructuredError(t *testing.T) { + parameterTypes := []string{"int", "int"} + + args := []json.RawMessage{ + json.RawMessage(`"hello"`), + json.RawMessage(`20`), + } + + _, err := decodeGenericInvokeArgs(parameterTypes, args) + + if err == nil { + t.Fatal("expected decoding error") + } + + var fieldErr *GenericInvokeArgumentError + + if !errors.As(err, &fieldErr) { + t.Fatalf("expected GenericInvokeArgumentError, got %T: %v", err, err) + } + + if fieldErr.Field != "args[0]" { + t.Errorf("expected field args[0], got %s", fieldErr.Field) + } + + if fieldErr.Expected != "int" { + t.Errorf("expected type int, got %s", fieldErr.Expected) + } + + if fieldErr.Actual != "string" { + t.Errorf("expected actual string, got %s", fieldErr.Actual) + } +} + +func TestDecodeGenericInvokeArgsRejectsInvalidValues(t *testing.T) { + tests := []struct { + name string + javaType string + raw string + }{ + {"string receives number", "java.lang.String", `42`}, + {"boolean receives object", "boolean", `{"a":1}`}, + {"primitive int receives null", "int", `null`}, + {"long overflow", "long", `9.223372036854776e18`}, + {"float overflow", "float", `1e40`}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := decodeGenericInvokeArgs( + []string{tt.javaType}, + []json.RawMessage{json.RawMessage(tt.raw)}, + ) + + if err == nil { + t.Fatalf( + "expected error for Java type %s with JSON %s", + tt.javaType, + tt.raw, + ) + } + }) + } +} + +func TestDecodeGenericInvokeArgsAcceptsValidBoundaries(t *testing.T) { + tests := []struct { + name string + javaType string + raw string + want any + }{ + {"string", "java.lang.String", `"hello"`, "hello"}, + {"boolean", "boolean", `true`, true}, + {"nullable wrapper", "java.lang.Integer", `null`, nil}, + {"max int64", "long", `9223372036854775807`, int64(9223372036854775807)}, + {"min int64", "long", `-9223372036854775808`, int64(-9223372036854775808)}, + {"scientific integer", "long", `1e3`, int64(1000)}, + {"float", "float", `1.5`, float32(1.5)}, + {"integer array", "int[]", `[1,2]`, []int32{1, 2}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := decodeGenericInvokeArgs( + []string{tt.javaType}, + []json.RawMessage{json.RawMessage(tt.raw)}, + ) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(got) != 1 || !reflect.DeepEqual(got[0], tt.want) { + t.Fatalf("want %#v, got %#v", tt.want, got) + } + }) + } +} + +func TestParseInt64TextExponentBounds(t *testing.T) { + tests := []struct { + name string + input string + want int64 + wantErr bool + }{ + { + name: "normal scientific notation", + input: "1e3", + want: 1000, + }, + { + name: "exact integer from decimal", + input: "1.5e1", + want: 15, + }, + { + name: "max int64 precision", + input: "9.223372036854775807e18", + want: 9223372036854775807, + }, + { + name: "min int64 precision", + input: "-9.223372036854775808e18", + want: -9223372036854775808, + }, + { + name: "huge positive exponent", + input: "1e999999999", + wantErr: true, + }, + { + name: "huge negative exponent", + input: "1e-999999999", + wantErr: true, + }, + { + name: "zero with huge exponent", + input: "0e999999999", + wantErr: true, + }, + { + name: "fractional value", + input: "1e-1", + wantErr: true, + }, + { + name: "int64 overflow", + input: "1e64", + wantErr: true, + }, + { + name: "positive exponent boundary exceeded", + input: "1e65", + wantErr: true, + }, + { + name: "negative exponent boundary exceeded", + input: "1e-65", + wantErr: true, + }, + { + name: "numeric text too long", + input: strings.Repeat("1", 65), + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := parseInt64Text(tt.input) + + if tt.wantErr { + if err == nil { + t.Fatalf("expected error for %q, got %d", tt.input, got) + } + return + } + + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if got != tt.want { + t.Fatalf("want %d, got %d", tt.want, got) + } + }) + } +} + +func TestDecodeGenericInvokeArgsRejectsExcessiveExponent(t *testing.T) { + tests := []struct { + name string + raw string + }{ + {"huge positive exponent", "1e999999999"}, + {"huge negative exponent", "1e-999999999"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := decodeGenericInvokeArgs( + []string{"long"}, + []json.RawMessage{json.RawMessage(tt.raw)}, + ) + if err == nil { + t.Fatal("expected decoding error") + } + + var fieldErr *GenericInvokeArgumentError + if !errors.As(err, &fieldErr) { + t.Fatalf("expected structured error, got %v", err) + } + if fieldErr.Field != "args[0]" { + t.Errorf("expected args[0], got %s", fieldErr.Field) + } + if fieldErr.Expected != "long" { + t.Errorf("expected long, got %s", fieldErr.Expected) + } + if fieldErr.Actual != "number" { + t.Errorf("expected number, got %s", fieldErr.Actual) + } + if fieldErr.Kind != ArgumentErrorType { + t.Errorf("expected type error, got %s", fieldErr.Kind) + } + }) + } +} + +func TestParseInt64TextDecimalSyntax(t *testing.T) { + for _, input := range []string{"0x1.8p1", "1_0.0", "0x1.0p9999999", "0x0.0p9999999", "0X1.8P1", "1.0p2", "1/1", "1e", "1e+", "1e1e1", ".", "+"} { + t.Run(input, func(t *testing.T) { + if got, err := parseInt64Text(input); err == nil { + t.Fatalf("expected decimal syntax error for %q, got %d", input, got) + } + }) + } + for _, tt := range []struct { + input string + want int64 + }{ + {"1E3", 1000}, {"+1.5e+1", 15}, {"9223372036854775807.0", 9223372036854775807}, + {"-9223372036854775808.0", -9223372036854775808}, {"10e-1", 1}, {"0e64", 0}, {"0e-64", 0}, + {"1.", 1}, {".0", 0}, {" +001.0 ", 1}, + } { + t.Run(tt.input, func(t *testing.T) { + got, err := parseInt64Text(tt.input) + if err != nil || got != tt.want { + t.Fatalf("want %d, got %d, err %v", tt.want, got, err) + } + }) + } +} + +func TestDecodeGenericInvokeArgsRejectsNonDecimalSyntax(t *testing.T) { + for _, input := range []string{"0x1.8p1", "1_0.0", "0x1.0p9999999", "0x0.0p9999999"} { + t.Run(input, func(t *testing.T) { + raw, err := json.Marshal(input) + if err != nil { + t.Fatal(err) + } + got, err := decodeGenericInvokeArgs([]string{"long"}, []json.RawMessage{raw}) + if err == nil { + t.Fatalf("expected decoding error, got %v", got) + } + var fieldErr *GenericInvokeArgumentError + if !errors.As(err, &fieldErr) { + t.Fatalf("expected structured error, got %v", err) + } + if got != nil || fieldErr.Kind != ArgumentErrorType || fieldErr.Field != "args[0]" || fieldErr.Expected != "long" || fieldErr.Actual != "string" || fieldErr.Cause == nil { + t.Fatalf("unexpected result %v or structured error: %+v", got, fieldErr) + } + }) + } +} diff --git a/pkg/console/service/service_generic_invoke_e2e_test.go b/pkg/console/service/service_generic_invoke_e2e_test.go new file mode 100644 index 000000000..7c19b7afa --- /dev/null +++ b/pkg/console/service/service_generic_invoke_e2e_test.go @@ -0,0 +1,257 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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 service + +import ( + "context" + "encoding/json" + "fmt" + "os" + "testing" + "time" + + dubboconstant "dubbo.apache.org/dubbo-go/v3/common/constant" + hessian "github.com/apache/dubbo-go-hessian2" + + meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1" + appcfg "github.com/apache/dubbo-admin/pkg/config/app" + "github.com/apache/dubbo-admin/pkg/console/counter" + "github.com/apache/dubbo-admin/pkg/console/model" + "github.com/apache/dubbo-admin/pkg/core/lock" + "github.com/apache/dubbo-admin/pkg/core/manager" + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" + coremodel "github.com/apache/dubbo-admin/pkg/core/resource/model" + "github.com/apache/dubbo-admin/pkg/core/store" + "github.com/apache/dubbo-admin/pkg/core/versioning" + memoryst "github.com/apache/dubbo-admin/pkg/store/memory" +) + +// These tests require the Java EchoService provider. Keep it running with: +// dubbo://127.0.0.1:20880 +// tri://127.0.0.1:50051 +// Enable tests explicitly using RUN_DUBBO_E2E=1. + +const ( + genericE2EMeshName = "test-mesh" + genericE2EInstanceName = "provider-1" + genericE2EAppName = "generic-e2e-provider" + genericE2EServiceName = "example.EchoService" + genericE2EProviderIP = "127.0.0.1" +) + +// Use an independently named test context to avoid coupling these E2E tests +// to helpers declared in other *_test.go files. +type genericServiceE2EContext struct { + rm manager.ResourceManager +} + +func (c *genericServiceE2EContext) ResourceManager() manager.ResourceManager { + return c.rm +} +func (c *genericServiceE2EContext) AppContext() context.Context { return context.Background() } +func (c *genericServiceE2EContext) CounterManager() counter.CounterManager { return nil } +func (c *genericServiceE2EContext) Config() appcfg.AdminConfig { return appcfg.AdminConfig{} } +func (c *genericServiceE2EContext) LockManager() lock.Lock { return nil } +func (c *genericServiceE2EContext) RuleVersioning() *versioning.Service { return nil } + +type genericServiceE2ERouter struct { + stores map[coremodel.ResourceKind]store.ResourceStore +} + +func (r *genericServiceE2ERouter) ResourceRoute(res coremodel.Resource) (store.ResourceStore, error) { + return r.ResourceKindRoute(res.ResourceKind()) +} + +func (r *genericServiceE2ERouter) ResourceKindRoute(kind coremodel.ResourceKind) (store.ResourceStore, error) { + s, ok := r.stores[kind] + if !ok { + return nil, fmt.Errorf("E2E resource store not registered for %s", kind) + } + return s, nil +} + +// The Service-layer test uses real Metadata/Instance/RPCInstance discovery, +// but runs against isolated in-memory stores rather than external registries. +func newGenericServiceJavaE2EContext(t *testing.T, protocol string, port int64, explicitSerialization bool) *genericServiceE2EContext { + t.Helper() + + stores := make(map[coremodel.ResourceKind]store.ResourceStore) + for _, kind := range []coremodel.ResourceKind{ + meshresource.InstanceKind, + meshresource.ServiceProviderMetadataKind, + meshresource.RPCInstanceKind, + } { + s := memoryst.NewMemoryResourceStore(kind) + if err := s.Init(nil); err != nil { + t.Fatalf("init %s store: %v", kind, err) + } + stores[kind] = s + } + + instance := meshresource.NewInstanceResourceWithAttributes( + genericE2EInstanceName, genericE2EMeshName, + ) + instance.Spec.AppName = genericE2EAppName + instance.Spec.Ip = genericE2EProviderIP + instance.Spec.RpcPort = port + if err := stores[meshresource.InstanceKind].Add(instance); err != nil { + t.Fatalf("add instance: %v", err) + } + + metadata := meshresource.NewServiceProviderMetadataResourceWithAttributes( + "echo-metadata", genericE2EMeshName, + ) + metadata.Spec.ServiceName = genericE2EServiceName + metadata.Spec.Methods = []*meshproto.Method{{ + Name: "echo", + ParameterTypes: []string{"java.lang.String"}, + ReturnType: "java.lang.String", + }} + if err := stores[meshresource.ServiceProviderMetadataKind].Add(metadata); err != nil { + t.Fatalf("add provider metadata: %v", err) + } + + rpcName := meshresource.BuildInstanceResName( + genericE2EAppName, genericE2EProviderIP, port, + ) + rpcInstance := meshresource.NewRPCInstanceResourceWithAttributes( + rpcName, genericE2EMeshName, + ) + rpcInstance.Spec.Name = rpcName + rpcInstance.Spec.AppName = genericE2EAppName + rpcInstance.Spec.Ip = genericE2EProviderIP + rpcInstance.Spec.Port = port + // Unset serialization covers the production Hessian2 fallback. + if explicitSerialization { + rpcInstance.Spec.Serialization = dubboconstant.Hessian2Serialization + } + rpcInstance.Spec.Endpoints = []*meshproto.Endpoint{{ + Protocol: protocol, + Port: port, + }} + if err := stores[meshresource.RPCInstanceKind].Add(rpcInstance); err != nil { + t.Fatalf("add RPC instance: %v", err) + } + + return &genericServiceE2EContext{ + rm: manager.NewResourceManager( + &genericServiceE2ERouter{stores: stores}, nil, + ), + } +} + +func requireGenericJavaE2E(t *testing.T) { + t.Helper() + if os.Getenv("RUN_DUBBO_E2E") != "1" { + t.Skip("set RUN_DUBBO_E2E=1 and start the Java EchoService provider") + } +} + +// Layer 1: Direct Go SDK -> Java Provider, without Admin Service or Metadata. +func runGenericSDKJavaE2E(t *testing.T, protocol string, port int64) { + t.Helper() + requireGenericJavaE2E(t) + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + + ctx = context.WithValue(ctx, dubboconstant.AttachmentKey, map[string]any{ + "traceId": "abc", + }) + + got, err := invokeGenericServiceRPC(ctx, genericInvocation{ + URL: fmt.Sprintf("%s://%s:%d", protocol, genericE2EProviderIP, port), + Protocol: protocol, + Serialization: dubboconstant.Hessian2Serialization, + ServiceName: genericE2EServiceName, + MethodName: "echo", + ParameterTypes: []string{"java.lang.String"}, + Args: []hessian.Object{"hello"}, + }) + if err != nil { + t.Fatalf("%s SDK generic invoke failed: %v", protocol, err) + } + if value, ok := got.(string); !ok || value != "hello" { + t.Fatalf("%s SDK result: want %q, got %#v (%T)", protocol, "hello", got, got) + } + + t.Logf("%s SDK RPC result: %#v", protocol, got) +} + +func TestGenericInvokeRealJavaProvider(t *testing.T) { + runGenericSDKJavaE2E(t, dubboconstant.DubboProtocol, 20880) +} + +func TestGenericInvokeRealJavaProviderTriple(t *testing.T) { + runGenericSDKJavaE2E(t, dubboconstant.TriProtocol, 50051) +} + +// Layer 2: Admin Service -> Metadata and target resolution -> real SDK -> Java Provider. +func runInvokeServiceGenericJavaE2E(t *testing.T, protocol string, port int64, explicitSerialization bool) { + t.Helper() + requireGenericJavaE2E(t) + + ctx := newGenericServiceJavaE2EContext(t, protocol, port, explicitSerialization) + req := model.ServiceGenericInvokeReq{ + BaseServiceReq: model.BaseServiceReq{ + Mesh: genericE2EMeshName, + ServiceName: genericE2EServiceName, + }, + InstanceName: genericE2EInstanceName, + MethodName: "echo", + Signature: "java.lang.String->java.lang.String", + Args: []json.RawMessage{json.RawMessage(`"hello"`)}, + TimeoutMs: 0, + Attachments: map[string]string{"traceId": "abc"}, + } + + if err := req.Validate(); err != nil { + t.Fatalf("validate generic invoke request: %v", err) + } + if req.TimeoutMs != model.DefaultServiceGenericInvokeTimeoutMs { + t.Fatalf("default timeout: want %d ms, got %d ms", + model.DefaultServiceGenericInvokeTimeoutMs, req.TimeoutMs) + } + + resp, err := InvokeServiceGeneric(ctx, req) + if err != nil { + t.Fatalf("%s Service generic invoke failed: %v", protocol, err) + } + if resp == nil { + t.Fatalf("%s Service generic invoke returned nil response", protocol) + } + if resp.RawResult != "hello" { + t.Fatalf("%s Service result: want %q, got %#v", protocol, "hello", resp.RawResult) + } + if resp.ElapsedMs < 0 { + t.Fatalf("%s Service elapsedMs is negative: %d", protocol, resp.ElapsedMs) + } + + t.Logf("%s Service RPC result: %#v", protocol, resp.RawResult) + t.Logf("%s Service RPC elapsed: %d ms", protocol, resp.ElapsedMs) + // Confirm traceId=abc in the Java Provider's business logs separately. +} + +// Verify the default Hessian2 fallback with omitted serialization metadata. +func TestInvokeServiceGenericRealJavaProvider(t *testing.T) { + runInvokeServiceGenericJavaE2E(t, dubboconstant.DubboProtocol, 20880, false) +} + +func TestInvokeServiceGenericRealJavaProviderTriple(t *testing.T) { + runInvokeServiceGenericJavaE2E(t, dubboconstant.TriProtocol, 50051, true) +} diff --git a/pkg/console/service/service_generic_invoke_error.go b/pkg/console/service/service_generic_invoke_error.go new file mode 100644 index 000000000..c0505fd26 --- /dev/null +++ b/pkg/console/service/service_generic_invoke_error.go @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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 service + +import "fmt" + +type GenericInvokeArgumentError struct { + Kind GenericInvokeArgumentErrorKind + Field string + Expected string + Actual string + Cause error +} + +type GenericInvokeArgumentErrorKind string + +const ( + ArgumentErrorType GenericInvokeArgumentErrorKind = "type" + ArgumentErrorSignature GenericInvokeArgumentErrorKind = "signature" + ArgumentErrorCount GenericInvokeArgumentErrorKind = "count" +) + +func (e *GenericInvokeArgumentError) Error() string { + msg := fmt.Sprintf( + "%s: expected %s, actual %s", + e.Field, + e.Expected, + e.Actual, + ) + + if e.Cause != nil { + return fmt.Sprintf("%s: %v", msg, e.Cause) + } + + return msg +} + +func (e *GenericInvokeArgumentError) Unwrap() error { + return e.Cause +} diff --git a/pkg/console/service/service_generic_invoke_validation_test.go b/pkg/console/service/service_generic_invoke_validation_test.go new file mode 100644 index 000000000..1249cada6 --- /dev/null +++ b/pkg/console/service/service_generic_invoke_validation_test.go @@ -0,0 +1,417 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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 service + +import ( + "context" + "encoding/json" + "errors" + "reflect" + "testing" + "time" + + dubboconstant "dubbo.apache.org/dubbo-go/v3/common/constant" + + meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1" + "github.com/apache/dubbo-admin/pkg/common/bizerror" + "github.com/apache/dubbo-admin/pkg/console/model" + "github.com/apache/dubbo-admin/pkg/core/manager" + meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1" + coremodel "github.com/apache/dubbo-admin/pkg/core/resource/model" + "github.com/apache/dubbo-admin/pkg/core/store" + memoryst "github.com/apache/dubbo-admin/pkg/store/memory" +) + +func TestInvokeServiceGenericInvalidArgsNoRPC(t *testing.T) { + stores := make(map[coremodel.ResourceKind]store.ResourceStore) + + for _, kind := range []coremodel.ResourceKind{ + meshresource.InstanceKind, + meshresource.ServiceProviderMetadataKind, + meshresource.RPCInstanceKind, + } { + s := memoryst.NewMemoryResourceStore(kind) + + if err := s.Init(nil); err != nil { + t.Fatal(err) + } + + stores[kind] = s + } + ctx := &testContext{ + rm: manager.NewResourceManager( + &testRouter{stores: stores}, + nil, + ), + } + instance := meshresource.NewInstanceResourceWithAttributes( + "provider-1", + "test-mesh", + ) + + instance.Spec.AppName = "calculator" + instance.Spec.Ip = "127.0.0.1" + instance.Spec.RpcPort = 20880 + + if err := stores[meshresource.InstanceKind].Add(instance); err != nil { + t.Fatal(err) + } + + metadata := meshresource.NewServiceProviderMetadataResourceWithAttributes( + "calculator-metadata", + "test-mesh", + ) + + metadata.Spec.ServiceName = "example.Calculator" + metadata.Spec.Methods = []*meshproto.Method{ + { + Name: "add", + ParameterTypes: []string{"int", "int"}, + ReturnType: "int", + }, + } + + if err := stores[meshresource.ServiceProviderMetadataKind].Add(metadata); err != nil { + t.Fatal(err) + } + + rpcName := meshresource.BuildInstanceResName( + "calculator", + "127.0.0.1", + 20880, + ) + + rpcInstance := meshresource.NewRPCInstanceResourceWithAttributes( + rpcName, + "test-mesh", + ) + + rpcInstance.Spec.Name = rpcName + rpcInstance.Spec.AppName = "calculator" + rpcInstance.Spec.Ip = "127.0.0.1" + rpcInstance.Spec.Port = 20880 + rpcInstance.Spec.Endpoints = []*meshproto.Endpoint{ + { + Protocol: "dubbo", + Port: 20880, + }, + } + + if err := stores[meshresource.RPCInstanceKind].Add(rpcInstance); err != nil { + t.Fatal(err) + } + + originalRPC := invokeGenericServiceRPC + + rpcCallCount := 0 + + var hasDeadline bool + var remaining time.Duration + var receivedTraceID any + var capturedInvocation genericInvocation + + invokeGenericServiceRPC = func( + callCtx context.Context, + invocation genericInvocation, + ) (any, error) { + rpcCallCount++ + capturedInvocation = invocation + deadline, ok := callCtx.Deadline() + hasDeadline = ok + + if ok { + remaining = time.Until(deadline) + } + attachments, ok := callCtx.Value( + dubboconstant.AttachmentKey, + ).(map[string]any) + + if ok { + receivedTraceID = attachments["traceId"] + } + return int32(30), nil + } + t.Cleanup(func() { + invokeGenericServiceRPC = originalRPC + }) + + req := model.ServiceGenericInvokeReq{ + BaseServiceReq: model.BaseServiceReq{ + Mesh: "test-mesh", + ServiceName: "example.Calculator", + }, + InstanceName: "provider-1", + MethodName: "add", + Signature: "int,int->int", + Args: []json.RawMessage{ + json.RawMessage(`"hello"`), + json.RawMessage(`20`), + }, + TimeoutMs: 3000, + } + + _, err := InvokeServiceGeneric(ctx, req) + + if err == nil { + t.Fatal("expected invalid argument type error") + } + + var fieldErr *GenericInvokeArgumentError + + if !errors.As(err, &fieldErr) { + t.Fatalf( + "expected structured argument error, got %T: %v", + err, + err, + ) + } + + if fieldErr.Kind != ArgumentErrorType { + t.Fatalf( + "expected type error, got %s", + fieldErr.Kind, + ) + } + + if fieldErr.Field != "args[0]" { + t.Fatalf( + "expected field args[0], got %s", + fieldErr.Field, + ) + } + + if rpcCallCount != 0 { + t.Fatalf( + "invalid args triggered %d RPC calls", + rpcCallCount, + ) + } + + req.Args = []json.RawMessage{ + json.RawMessage(`10`), + json.RawMessage(`20`), + } + + req.TimeoutMs = 0 + req.Attachments = map[string]string{ + "traceId": "abc", + } + if err := req.Validate(); err != nil { + t.Fatal(err) + } + if req.TimeoutMs != model.DefaultServiceGenericInvokeTimeoutMs { + t.Fatalf( + "expected default timeout %d, got %d", + model.DefaultServiceGenericInvokeTimeoutMs, + req.TimeoutMs, + ) + } + + _, err = InvokeServiceGeneric(ctx, req) + + if err != nil { + t.Fatalf("valid request failed: %v", err) + } + if rpcCallCount != 1 { + t.Fatalf( + "expected 1 RPC call, got %d", + rpcCallCount, + ) + } + if !hasDeadline { + t.Fatal("expected RPC context deadline") + } + + expectedTimeout := time.Duration( + model.DefaultServiceGenericInvokeTimeoutMs, + ) * time.Millisecond + if remaining <= 0 || remaining > expectedTimeout { + t.Fatalf( + "unexpected remaining timeout: %v", + remaining, + ) + } + if receivedTraceID != "abc" { + t.Fatalf( + "expected traceId abc, got %v", + receivedTraceID, + ) + } + if capturedInvocation.MethodName != "add" { + t.Fatalf( + "expected method add, got %s", + capturedInvocation.MethodName, + ) + } + + expectedTypes := []string{"int", "int"} + + if !reflect.DeepEqual( + capturedInvocation.ParameterTypes, + expectedTypes, + ) { + t.Fatalf( + "expected parameter types %v, got %v", + expectedTypes, + capturedInvocation.ParameterTypes, + ) + } + if len(capturedInvocation.Args) != 2 { + t.Fatalf( + "expected 2 decoded args, got %d", + len(capturedInvocation.Args), + ) + } + if !reflect.DeepEqual( + capturedInvocation.Args[0], + int32(10), + ) { + t.Fatalf( + "expected first arg int32(10), got %T: %v", + capturedInvocation.Args[0], + capturedInvocation.Args[0], + ) + } + if !reflect.DeepEqual( + capturedInvocation.Args[1], + int32(20), + ) { + t.Fatalf( + "expected second arg int32(20), got %T: %v", + capturedInvocation.Args[1], + capturedInvocation.Args[1], + ) + } + rpcCallCount = 0 + req.Args = []json.RawMessage{ + json.RawMessage(`10`), + } + + _, err = InvokeServiceGeneric(ctx, req) + + if err == nil { + t.Fatal("expected argument count mismatch error") + } + + var countErr *GenericInvokeArgumentError + + if !errors.As(err, &countErr) { + t.Fatalf( + "expected structured count error, got %T: %v", + err, + err, + ) + } + if countErr.Kind != ArgumentErrorCount { + t.Errorf( + "expected count error, got %s", + countErr.Kind, + ) + } + if countErr.Field != "args" { + t.Errorf( + "expected field args, got %s", + countErr.Field, + ) + } + + if countErr.Expected != "2" { + t.Errorf( + "expected 2 arguments, got %s", + countErr.Expected, + ) + } + + if countErr.Actual != "1" { + t.Errorf( + "expected 1 argument, got %s", + countErr.Actual, + ) + } + + if rpcCallCount != 0 { + t.Fatalf( + "count mismatch triggered %d RPC calls", + rpcCallCount, + ) + } + + rpcCallCount = 0 + + req.Args = []json.RawMessage{ + json.RawMessage(`10`), + json.RawMessage(`20`), + } + + req.Signature = "int->int" + + _, err = InvokeServiceGeneric(ctx, req) + + if err == nil { + t.Fatal("expected unknown signature error") + } + if rpcCallCount != 0 { + t.Fatalf( + "unknown signature triggered %d RPC calls", + rpcCallCount, + ) + } + var bizErr bizerror.Error + + if !errors.As(err, &bizErr) { + t.Fatalf( + "expected bizerror, got %T: %v", + err, + err, + ) + } + if bizErr.Code() != bizerror.NotFoundError { + t.Fatalf( + "expected NotFoundError, got %s", + bizErr.Code(), + ) + } + + var signatureErr *GenericInvokeArgumentError + + if !errors.As(err, &signatureErr) { + t.Fatalf( + "expected structured signature error, got %T: %v", + err, + err, + ) + } + if signatureErr.Field != "signature" { + t.Errorf( + "expected field signature, got %s", + signatureErr.Field, + ) + } + if signatureErr.Actual != "int->int" { + t.Errorf( + "expected actual int->int, got %s", + signatureErr.Actual, + ) + } + if signatureErr.Expected != "int,int->int" { + t.Errorf( + "expected int,int->int, got %s", + signatureErr.Expected, + ) + } +}