From bd59d7625a385214fe94308182df9e6ea4915486 Mon Sep 17 00:00:00 2001 From: Kevin Date: Thu, 26 Nov 2026 23:01:13 +0800 Subject: [PATCH 1/3] fix(console): propagate timeoutMs to Dubbo and Triple generic invoke client Signed-off-by: Kevin --- pkg/console/service/service_generic_invoke.go | 63 +++++- .../service_generic_invoke_validation_test.go | 185 ++++++++++++++++++ 2 files changed, 239 insertions(+), 9 deletions(-) diff --git a/pkg/console/service/service_generic_invoke.go b/pkg/console/service/service_generic_invoke.go index 8373d9771..b5df9f052 100644 --- a/pkg/console/service/service_generic_invoke.go +++ b/pkg/console/service/service_generic_invoke.go @@ -55,6 +55,7 @@ type genericInvocation struct { MethodName string ParameterTypes []string Args []hessian.Object + Timeout time.Duration } type genericInvokeTarget struct { @@ -65,6 +66,11 @@ type genericInvokeTarget struct { } var invokeGenericServiceRPC = func(callCtx context.Context, invocation genericInvocation) (any, error) { + timeout, err := resolveGenericInvokeTimeout(callCtx, invocation) + if err != nil { + return nil, err + } + // TODO: Cache generic invoke clients to avoid recreating the Dubbo instance/client on every call. ins, err := dubbo.NewInstance(dubbo.WithName(genericInvokeInstanceName)) if err != nil { @@ -83,19 +89,24 @@ var invokeGenericServiceRPC = func(callCtx context.Context, invocation genericIn return nil, fmt.Errorf("unsupported invoke protocol %s", invocation.Protocol) } - cli, err := ins.NewClient(clientOpts...) - if err != nil { - return nil, err - } - - svc, err := cli.NewGenericService( - invocation.ServiceName, + referenceOpts := []client.ReferenceOption{ client.WithURL(invocation.URL), client.WithVersion(invocation.Version), client.WithGroup(invocation.Group), client.WithProtocol(invocation.Protocol), client.WithSerialization(invocation.Serialization), - ) + } + if timeout > 0 { + clientOpts = append(clientOpts, client.WithClientRequestTimeout(timeout)) + referenceOpts = append(referenceOpts, client.WithRequestTimeout(timeout)) + } + + cli, err := ins.NewClient(clientOpts...) + if err != nil { + return nil, err + } + + svc, err := cli.NewGenericService(invocation.ServiceName, referenceOpts...) if err != nil { return nil, err } @@ -103,6 +114,38 @@ var invokeGenericServiceRPC = func(callCtx context.Context, invocation genericIn return svc.Invoke(callCtx, invocation.MethodName, invocation.ParameterTypes, invocation.Args) } +func resolveGenericInvokeTimeout(callCtx context.Context, invocation genericInvocation) (time.Duration, error) { + timeout := invocation.Timeout + if callCtx != nil { + if err := callCtx.Err(); err != nil { + return 0, err + } + if deadline, ok := callCtx.Deadline(); ok { + remaining := time.Until(deadline) + if remaining <= 0 { + return 0, context.DeadlineExceeded + } + if timeout <= 0 || remaining < timeout { + timeout = remaining + } + } + } + if timeout <= 0 { + return timeout, nil + } + return ceilTimeoutToMillisecond(timeout), nil +} + +func ceilTimeoutToMillisecond(timeout time.Duration) time.Duration { + if timeout <= time.Millisecond { + return time.Millisecond + } + if rem := timeout % time.Millisecond; rem != 0 { + return timeout - rem + time.Millisecond + } + return timeout +} + func InvokeServiceGeneric(ctx consolectx.Context, req model.ServiceGenericInvokeReq) (*model.ServiceGenericInvokeResp, error) { instanceRes, err := getGenericInvokeInstance(ctx, req.Mesh, req.InstanceName) if err != nil { @@ -230,7 +273,8 @@ func InvokeServiceGeneric(ctx consolectx.Context, req model.ServiceGenericInvoke if ctx != nil && ctx.AppContext() != nil { parentCtx = ctx.AppContext() } - callCtx, cancel := context.WithTimeout(parentCtx, time.Duration(req.TimeoutMs)*time.Millisecond) + timeout := time.Duration(req.TimeoutMs) * time.Millisecond + callCtx, cancel := context.WithTimeout(parentCtx, timeout) defer cancel() if len(req.Attachments) > 0 { @@ -263,6 +307,7 @@ func InvokeServiceGeneric(ctx consolectx.Context, req model.ServiceGenericInvoke MethodName: req.MethodName, ParameterTypes: parameterTypes, Args: hessianArgs, + Timeout: timeout, }) elapsedMs := time.Since(startedAt).Milliseconds() if err != nil { diff --git a/pkg/console/service/service_generic_invoke_validation_test.go b/pkg/console/service/service_generic_invoke_validation_test.go index 1249cada6..2550e94cc 100644 --- a/pkg/console/service/service_generic_invoke_validation_test.go +++ b/pkg/console/service/service_generic_invoke_validation_test.go @@ -25,7 +25,10 @@ import ( "testing" "time" + dubbocommon "dubbo.apache.org/dubbo-go/v3/common" dubboconstant "dubbo.apache.org/dubbo-go/v3/common/constant" + "dubbo.apache.org/dubbo-go/v3/common/extension" + protocolbase "dubbo.apache.org/dubbo-go/v3/protocol/base" meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1" "github.com/apache/dubbo-admin/pkg/common/bizerror" @@ -37,6 +40,185 @@ import ( memoryst "github.com/apache/dubbo-admin/pkg/store/memory" ) +func TestResolveGenericInvokeTimeout(t *testing.T) { + invocation := genericInvocation{Timeout: 5 * time.Second} + + t.Run("uses remaining deadline", func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + deadline, _ := ctx.Deadline() + before := ceilTimeoutToMillisecond(time.Until(deadline)) + got, err := resolveGenericInvokeTimeout(ctx, invocation) + if err != nil || got <= 0 || got < time.Until(deadline) || got > before || got%time.Millisecond != 0 { + t.Fatalf("expected remaining millisecond-aligned context timeout, got %v, %v", got, err) + } + }) + + t.Run("rejects expired deadline", func(t *testing.T) { + ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) + defer cancel() + _, err := resolveGenericInvokeTimeout(ctx, invocation) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("expected deadline exceeded, got %v", err) + } + }) + + t.Run("rejects canceled context before deadline", func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + cancel() + _, err := resolveGenericInvokeTimeout(ctx, invocation) + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected context canceled, got %v", err) + } + }) + + t.Run("uses shorter invocation timeout than context deadline", func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + got, err := resolveGenericInvokeTimeout(ctx, genericInvocation{Timeout: 2 * time.Second}) + if err != nil || got != 2*time.Second { + t.Fatalf("expected shorter invocation timeout 2s, got %v, %v", got, err) + } + }) + + t.Run("rounds sub-millisecond timeout up to 1ms", func(t *testing.T) { + got, err := resolveGenericInvokeTimeout(context.Background(), genericInvocation{Timeout: 500 * time.Microsecond}) + if err != nil || got != time.Millisecond { + t.Fatalf("expected 1ms, got %v, %v", got, err) + } + }) + + t.Run("handles nil context", func(t *testing.T) { + got, err := resolveGenericInvokeTimeout(nil, invocation) + if err != nil || got != invocation.Timeout { + t.Fatalf("expected invocation timeout %v, got %v, %v", invocation.Timeout, got, err) + } + }) + + t.Run("uses request timeout without deadline", func(t *testing.T) { + got, err := resolveGenericInvokeTimeout(context.Background(), invocation) + if err != nil || got != invocation.Timeout { + t.Fatalf("expected request timeout %v, got %v, %v", invocation.Timeout, got, err) + } + }) +} + +type genericInvokeReferenceRecorder struct { + protocolbase.BaseProtocol + url *dubbocommon.URL +} + +func (p *genericInvokeReferenceRecorder) Refer(url *dubbocommon.URL) protocolbase.Invoker { + p.url = url + return protocolbase.NewBaseInvoker(url) +} + +func TestInvokeGenericServiceRPCReferenceTimeout(t *testing.T) { + originalDubbo := extension.GetProtocol(dubboconstant.DubboProtocol) + originalTriple := extension.GetProtocol(dubboconstant.TriProtocol) + t.Cleanup(func() { + extension.SetProtocol(dubboconstant.DubboProtocol, func() protocolbase.Protocol { return originalDubbo }) + extension.SetProtocol(dubboconstant.TriProtocol, func() protocolbase.Protocol { return originalTriple }) + }) + + for _, timeout := range []time.Duration{100 * time.Millisecond, 5 * time.Second} { + t.Run("dubbo/"+timeout.String(), func(t *testing.T) { + recorder := &genericInvokeReferenceRecorder{} + extension.SetProtocol(dubboconstant.DubboProtocol, func() protocolbase.Protocol { return recorder }) + + _, err := invokeGenericServiceRPC(context.Background(), genericInvocation{ + URL: "dubbo://127.0.0.1:20880", + Protocol: dubboconstant.DubboProtocol, + Serialization: dubboconstant.Hessian2Serialization, + ServiceName: "example.Calculator", + MethodName: "delay", + Timeout: timeout, + }) + if err != nil { + t.Fatalf("invoke generic service: %v", err) + } + if recorder.url == nil { + t.Fatal("expected a Dubbo reference URL") + } + if got := recorder.url.GetParam(dubboconstant.TimeoutKey, ""); got != timeout.String() { + t.Fatalf("expected reference timeout %v, got %q", timeout, got) + } + }) + } + + t.Run("dubbo/context-deadline", func(t *testing.T) { + recorder := &genericInvokeReferenceRecorder{} + extension.SetProtocol(dubboconstant.DubboProtocol, func() protocolbase.Protocol { return recorder }) + + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + _, err := invokeGenericServiceRPC(ctx, genericInvocation{ + URL: "dubbo://127.0.0.1:20880", + Protocol: dubboconstant.DubboProtocol, + Serialization: dubboconstant.Hessian2Serialization, + ServiceName: "example.Calculator", + MethodName: "delay", + Timeout: 5 * time.Second, + }) + if err != nil { + t.Fatalf("invoke generic service: %v", err) + } + if recorder.url == nil { + t.Fatal("expected a Dubbo reference URL") + } + rawTimeout := recorder.url.GetParam(dubboconstant.TimeoutKey, "") + parsed, err := time.ParseDuration(rawTimeout) + if err != nil || parsed <= 0 || parsed > 200*time.Millisecond || parsed%time.Millisecond != 0 { + t.Fatalf("expected millisecond-aligned timeout in (0, 200ms], got %q (%v)", rawTimeout, err) + } + }) + + t.Run("dubbo/expired-context-skips-refer", func(t *testing.T) { + recorder := &genericInvokeReferenceRecorder{} + extension.SetProtocol(dubboconstant.DubboProtocol, func() protocolbase.Protocol { return recorder }) + + ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) + defer cancel() + _, err := invokeGenericServiceRPC(ctx, genericInvocation{ + URL: "dubbo://127.0.0.1:20880", + Protocol: dubboconstant.DubboProtocol, + Serialization: dubboconstant.Hessian2Serialization, + ServiceName: "example.Calculator", + MethodName: "delay", + Timeout: 5 * time.Second, + }) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("expected deadline exceeded, got %v", err) + } + if recorder.url != nil { + t.Fatalf("expected Refer not to be called for expired context, got %v", recorder.url) + } + }) + + t.Run("triple/150ms", func(t *testing.T) { + recorder := &genericInvokeReferenceRecorder{} + extension.SetProtocol(dubboconstant.TriProtocol, func() protocolbase.Protocol { return recorder }) + + _, err := invokeGenericServiceRPC(context.Background(), genericInvocation{ + URL: "tri://127.0.0.1:50051", + Protocol: dubboconstant.TriProtocol, + Serialization: dubboconstant.Hessian2Serialization, + ServiceName: "example.Calculator", + MethodName: "delay", + Timeout: 150 * time.Millisecond, + }) + if err != nil { + t.Fatalf("invoke generic service: %v", err) + } + if recorder.url == nil { + t.Fatal("expected a Triple reference URL") + } + if got := recorder.url.GetParam(dubboconstant.TimeoutKey, ""); got != (150 * time.Millisecond).String() { + t.Fatalf("expected reference timeout 150ms, got %q", got) + } + }) +} + func TestInvokeServiceGenericInvalidArgsNoRPC(t *testing.T) { stores := make(map[coremodel.ResourceKind]store.ResourceStore) @@ -246,6 +428,9 @@ func TestInvokeServiceGenericInvalidArgsNoRPC(t *testing.T) { remaining, ) } + if capturedInvocation.Timeout != expectedTimeout { + t.Fatalf("expected invocation timeout %v, got %v", expectedTimeout, capturedInvocation.Timeout) + } if receivedTraceID != "abc" { t.Fatalf( "expected traceId abc, got %v", From 511e5334fe04098a40b0da4c6990c5181bc22a6f Mon Sep 17 00:00:00 2001 From: Kevin Date: Sun, 29 Nov 2026 13:41:05 +0800 Subject: [PATCH 2/3] fix(console): harden generic invoke timeout with fail-fast and remaining budget Signed-off-by: Kevin --- pkg/console/service/service_generic_invoke.go | 101 ++++++- .../service_generic_invoke_timeout_test.go | 267 ++++++++++++++++++ .../service_generic_invoke_validation_test.go | 223 ++++++++++++++- 3 files changed, 578 insertions(+), 13 deletions(-) create mode 100644 pkg/console/service/service_generic_invoke_timeout_test.go diff --git a/pkg/console/service/service_generic_invoke.go b/pkg/console/service/service_generic_invoke.go index b5df9f052..a86460429 100644 --- a/pkg/console/service/service_generic_invoke.go +++ b/pkg/console/service/service_generic_invoke.go @@ -31,6 +31,7 @@ import ( dubbo "dubbo.apache.org/dubbo-go/v3" "dubbo.apache.org/dubbo-go/v3/client" dubboconstant "dubbo.apache.org/dubbo-go/v3/common/constant" + dubbogeneric "dubbo.apache.org/dubbo-go/v3/filter/generic" _ "dubbo.apache.org/dubbo-go/v3/imports" protocolbase "dubbo.apache.org/dubbo-go/v3/protocol/base" @@ -65,12 +66,27 @@ type genericInvokeTarget struct { serialization string } +type genericServiceCreateResult struct { + svc *dubbogeneric.GenericService + err error +} + var invokeGenericServiceRPC = func(callCtx context.Context, invocation genericInvocation) (any, error) { + if callCtx == nil { + callCtx = context.Background() + } timeout, err := resolveGenericInvokeTimeout(callCtx, invocation) if err != nil { return nil, err } + rpcCtx := callCtx + var cancel context.CancelFunc + if timeout > 0 { + rpcCtx, cancel = context.WithTimeout(callCtx, timeout) + defer cancel() + } + // TODO: Cache generic invoke clients to avoid recreating the Dubbo instance/client on every call. ins, err := dubbo.NewInstance(dubbo.WithName(genericInvokeInstanceName)) if err != nil { @@ -95,6 +111,7 @@ var invokeGenericServiceRPC = func(callCtx context.Context, invocation genericIn client.WithGroup(invocation.Group), client.WithProtocol(invocation.Protocol), client.WithSerialization(invocation.Serialization), + client.WithClusterFailFast(), } if timeout > 0 { clientOpts = append(clientOpts, client.WithClientRequestTimeout(timeout)) @@ -106,12 +123,85 @@ var invokeGenericServiceRPC = func(callCtx context.Context, invocation genericIn return nil, err } - svc, err := cli.NewGenericService(invocation.ServiceName, referenceOpts...) + svc, err := newGenericServiceWithContext(rpcCtx, cli, invocation.ServiceName, referenceOpts...) + if err != nil { + return nil, err + } + + remainingTimeout, err := resolveGenericInvokeTimeout(rpcCtx, invocation) if err != nil { return nil, err } + invokeCtx := applyGenericInvokeTimeoutAttachment(rpcCtx, remainingTimeout) + + return svc.Invoke(invokeCtx, invocation.MethodName, invocation.ParameterTypes, invocation.Args) +} + +func newGenericServiceWithContext( + ctx context.Context, + cli *client.Client, + serviceName string, + opts ...client.ReferenceOption, +) (*dubbogeneric.GenericService, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + + resultCh := make(chan genericServiceCreateResult, 1) + go func() { + defer func() { + if r := recover(); r != nil { + resultCh <- genericServiceCreateResult{ + err: fmt.Errorf("create generic service %s panicked: %v", serviceName, r), + } + } + }() + svc, err := cli.NewGenericService(serviceName, opts...) + resultCh <- genericServiceCreateResult{svc: svc, err: err} + }() + + select { + case res := <-resultCh: + if err := ctx.Err(); err != nil { + return nil, err + } + return res.svc, res.err + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +func applyGenericInvokeTimeoutAttachment(ctx context.Context, timeout time.Duration) context.Context { + existing := ctx.Value(dubboconstant.AttachmentKey) + var attachments map[string]any + switch raw := existing.(type) { + case map[string]any: + attachments = make(map[string]any, len(raw)+1) + for k, v := range raw { + if strings.EqualFold(strings.TrimSpace(k), dubboconstant.TimeoutKey) { + continue + } + attachments[k] = v + } + case map[string]string: + attachments = make(map[string]any, len(raw)+1) + for k, v := range raw { + if strings.EqualFold(strings.TrimSpace(k), dubboconstant.TimeoutKey) { + continue + } + attachments[k] = v + } + default: + if timeout <= 0 { + return ctx + } + attachments = make(map[string]any, 1) + } - return svc.Invoke(callCtx, invocation.MethodName, invocation.ParameterTypes, invocation.Args) + if timeout > 0 { + attachments[dubboconstant.TimeoutKey] = timeout.String() + } + return context.WithValue(ctx, dubboconstant.AttachmentKey, attachments) } func resolveGenericInvokeTimeout(callCtx context.Context, invocation genericInvocation) (time.Duration, error) { @@ -280,9 +370,14 @@ func InvokeServiceGeneric(ctx consolectx.Context, req model.ServiceGenericInvoke if len(req.Attachments) > 0 { attachmentValues := make(map[string]any, len(req.Attachments)) for key, value := range req.Attachments { + if strings.EqualFold(strings.TrimSpace(key), dubboconstant.TimeoutKey) { + continue + } attachmentValues[key] = value } - callCtx = context.WithValue(callCtx, dubboconstant.AttachmentKey, attachmentValues) + if len(attachmentValues) > 0 { + callCtx = context.WithValue(callCtx, dubboconstant.AttachmentKey, attachmentValues) + } } if idl { diff --git a/pkg/console/service/service_generic_invoke_timeout_test.go b/pkg/console/service/service_generic_invoke_timeout_test.go new file mode 100644 index 000000000..4965de8ac --- /dev/null +++ b/pkg/console/service/service_generic_invoke_timeout_test.go @@ -0,0 +1,267 @@ +/* + * 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" + "errors" + "fmt" + "net" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + dubbocommon "dubbo.apache.org/dubbo-go/v3/common" + dubboconstant "dubbo.apache.org/dubbo-go/v3/common/constant" + "dubbo.apache.org/dubbo-go/v3/common/extension" + "dubbo.apache.org/dubbo-go/v3/global" + protocolbase "dubbo.apache.org/dubbo-go/v3/protocol/base" + protocolresult "dubbo.apache.org/dubbo-go/v3/protocol/result" + tri "dubbo.apache.org/dubbo-go/v3/protocol/triple/triple_protocol" + hessian "github.com/apache/dubbo-go-hessian2" +) + +type delayedRealGenericInvoker struct { + protocolbase.BaseInvoker + attempts atomic.Int32 + mu sync.Mutex + delay time.Duration + release chan struct{} +} + +func newDelayedRealGenericInvoker(url *dubbocommon.URL) *delayedRealGenericInvoker { + return &delayedRealGenericInvoker{ + BaseInvoker: *protocolbase.NewBaseInvoker(url), + } +} + +func (inv *delayedRealGenericInvoker) configure(delay time.Duration) (release func()) { + ch := make(chan struct{}) + inv.mu.Lock() + inv.delay = delay + inv.release = ch + inv.mu.Unlock() + inv.attempts.Store(0) + + var once sync.Once + return func() { + once.Do(func() { close(ch) }) + } +} + +func (inv *delayedRealGenericInvoker) Invoke(ctx context.Context, _ protocolbase.Invocation) protocolresult.Result { + inv.attempts.Add(1) + inv.mu.Lock() + delay := inv.delay + release := inv.release + inv.mu.Unlock() + + if delay > 0 { + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-timer.C: + case <-release: + case <-ctx.Done(): + return &protocolresult.RPCResult{Err: ctx.Err()} + } + } + return &protocolresult.RPCResult{Rest: "ok"} +} + +func reserveLocalTCPPort(t *testing.T) int { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("reserve local TCP port: %v", err) + } + port := ln.Addr().(*net.TCPAddr).Port + if err := ln.Close(); err != nil { + t.Fatalf("close reserved listener: %v", err) + } + return port +} + +func waitForLocalTCPReady(t *testing.T, addr string) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + conn, err := net.DialTimeout("tcp", addr, 100*time.Millisecond) + if err == nil { + _ = conn.Close() + return + } + time.Sleep(20 * time.Millisecond) + } + t.Fatalf("server at %s did not become ready in time", addr) +} + +func exportDelayedGenericServer(t *testing.T, protoName, serviceName string) (string, *delayedRealGenericInvoker) { + t.Helper() + port := reserveLocalTCPPort(t) + addr := fmt.Sprintf("127.0.0.1:%d", port) + rawURL := fmt.Sprintf( + "%s://%s/%s?interface=%s&serialization=%s", + protoName, + addr, + serviceName, + serviceName, + dubboconstant.Hessian2Serialization, + ) + url, err := dubbocommon.NewURL(rawURL) + if err != nil { + t.Fatalf("build server url %s: %v", rawURL, err) + } + url.Port = strconv.Itoa(port) + if protoName == dubboconstant.TriProtocol { + url.SetParam(dubboconstant.IDLMode, dubboconstant.NONIDL) + url.SetAttribute(dubboconstant.TripleConfigKey, global.DefaultTripleConfig()) + url.SetAttribute(dubboconstant.ServiceInfoKey, &dubbocommon.ServiceInfo{ + InterfaceName: serviceName, + Methods: []dubbocommon.MethodInfo{{ + Name: dubboconstant.Generic, + Type: dubboconstant.CallUnary, + ReqInitFunc: func() any { + methodName := "" + return []any{&methodName, &[]string{}, &[]hessian.Object{}} + }, + }}, + }) + } + + invoker := newDelayedRealGenericInvoker(url) + exporter := extension.GetProtocol(protoName).Export(invoker) + t.Cleanup(func() { + exporter.UnExport() + }) + waitForLocalTCPReady(t, addr) + return fmt.Sprintf("%s://%s", protoName, addr), invoker +} + +func isGenericInvokeTimeoutErr(err error) bool { + if err == nil { + return false + } + if errors.Is(err, context.DeadlineExceeded) { + return true + } + if tri.IsWireError(err) && tri.CodeOf(err) == tri.CodeDeadlineExceeded { + return true + } + msg := strings.ToLower(err.Error()) + return strings.Contains(msg, "timeout") || strings.Contains(msg, "deadline") +} + +func TestInvokeGenericServiceRPCRealProtocolTimeout(t *testing.T) { + const serviceName = "example.DelayedGenericService" + + for _, protoName := range []string{dubboconstant.DubboProtocol, dubboconstant.TriProtocol} { + protoName := protoName + t.Run(protoName, func(t *testing.T) { + serverURL, invoker := exportDelayedGenericServer(t, protoName, serviceName) + + baseInvocation := genericInvocation{ + URL: serverURL, + Protocol: protoName, + Serialization: dubboconstant.Hessian2Serialization, + ServiceName: serviceName, + MethodName: "delay", + ParameterTypes: []string{"java.lang.String"}, + Args: []hessian.Object{"ping"}, + } + + // Warm up connection once so short-timeout subtests measure RPC timeout rather than initial dial setup. + releaseWarmup := invoker.configure(0) + defer releaseWarmup() + warmupInv := baseInvocation + warmupInv.Timeout = 2 * time.Second + got, err := invokeGenericServiceRPC(context.Background(), warmupInv) + if err != nil || got != "ok" { + t.Fatalf("%s warmup invoke failed: got=%#v err=%v", protoName, got, err) + } + + t.Run("below-3s-times-out-without-retry", func(t *testing.T) { + release := invoker.configure(800 * time.Millisecond) + defer release() + + inv := baseInvocation + inv.Timeout = 100 * time.Millisecond + startedAt := time.Now() + _, err := invokeGenericServiceRPC(context.Background(), inv) + elapsed := time.Since(startedAt) + + if !isGenericInvokeTimeoutErr(err) { + t.Fatalf("expected %s timeout error, got %v", protoName, err) + } + if elapsed >= 2*time.Second { + t.Fatalf("expected %s timeout well below 3s fallback, took %v", protoName, elapsed) + } + if attempts := invoker.attempts.Load(); attempts != 1 { + t.Fatalf("expected fail-fast single attempt, got %d attempts", attempts) + } + }) + + t.Run("timeout-attachment-cannot-override-timeoutMs", func(t *testing.T) { + release := invoker.configure(800 * time.Millisecond) + defer release() + + ctx := context.WithValue(context.Background(), dubboconstant.AttachmentKey, map[string]any{ + "timeout": "5s", + "Timeout": "5s", + "traceId": "keep-me", + }) + inv := baseInvocation + inv.Timeout = 100 * time.Millisecond + startedAt := time.Now() + _, err := invokeGenericServiceRPC(ctx, inv) + elapsed := time.Since(startedAt) + + if !isGenericInvokeTimeoutErr(err) { + t.Fatalf("expected %s timeout error despite timeout attachment, got %v", protoName, err) + } + if elapsed >= 2*time.Second { + t.Fatalf("expected %s timeout well below 5s attachment override, took %v", protoName, elapsed) + } + if attempts := invoker.attempts.Load(); attempts != 1 { + t.Fatalf("expected fail-fast single attempt, got %d attempts", attempts) + } + }) + + t.Run("above-3s-succeeds-beyond-sdk-default", func(t *testing.T) { + release := invoker.configure(3200 * time.Millisecond) + defer release() + + inv := baseInvocation + inv.Timeout = 5 * time.Second + got, err := invokeGenericServiceRPC(context.Background(), inv) + if err != nil { + t.Fatalf("expected %s call >3s to succeed with 5s timeout, got %v", protoName, err) + } + if got != "ok" { + t.Fatalf("expected result \"ok\", got %#v", got) + } + if attempts := invoker.attempts.Load(); attempts != 1 { + t.Fatalf("expected single attempt, got %d attempts", attempts) + } + }) + }) + } +} diff --git a/pkg/console/service/service_generic_invoke_validation_test.go b/pkg/console/service/service_generic_invoke_validation_test.go index 2550e94cc..b72baf206 100644 --- a/pkg/console/service/service_generic_invoke_validation_test.go +++ b/pkg/console/service/service_generic_invoke_validation_test.go @@ -22,6 +22,8 @@ import ( "encoding/json" "errors" "reflect" + "sync" + "sync/atomic" "testing" "time" @@ -29,6 +31,7 @@ import ( dubboconstant "dubbo.apache.org/dubbo-go/v3/common/constant" "dubbo.apache.org/dubbo-go/v3/common/extension" protocolbase "dubbo.apache.org/dubbo-go/v3/protocol/base" + protocolresult "dubbo.apache.org/dubbo-go/v3/protocol/result" meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1" "github.com/apache/dubbo-admin/pkg/common/bizerror" @@ -103,14 +106,56 @@ func TestResolveGenericInvokeTimeout(t *testing.T) { }) } +type genericInvokeRecordingInvoker struct { + protocolbase.BaseInvoker + recorder *genericInvokeReferenceRecorder +} + +func (inv *genericInvokeRecordingInvoker) Invoke(_ context.Context, ivc protocolbase.Invocation) protocolresult.Result { + inv.recorder.invoked.Add(1) + copied := make(map[string]any, len(ivc.Attachments())) + for k, v := range ivc.Attachments() { + copied[k] = v + } + inv.recorder.mu.Lock() + inv.recorder.invAttachments = copied + inv.recorder.mu.Unlock() + return &protocolresult.RPCResult{} +} + type genericInvokeReferenceRecorder struct { protocolbase.BaseProtocol - url *dubbocommon.URL + mu sync.Mutex + url *dubbocommon.URL + invAttachments map[string]any + referHook func(*dubbocommon.URL) + invoked atomic.Int32 } func (p *genericInvokeReferenceRecorder) Refer(url *dubbocommon.URL) protocolbase.Invoker { + p.mu.Lock() p.url = url - return protocolbase.NewBaseInvoker(url) + hook := p.referHook + p.mu.Unlock() + if hook != nil { + hook(url) + } + return &genericInvokeRecordingInvoker{ + BaseInvoker: *protocolbase.NewBaseInvoker(url), + recorder: p, + } +} + +func (p *genericInvokeReferenceRecorder) recordedURL() *dubbocommon.URL { + p.mu.Lock() + defer p.mu.Unlock() + return p.url +} + +func (p *genericInvokeReferenceRecorder) recordedAttachments() map[string]any { + p.mu.Lock() + defer p.mu.Unlock() + return p.invAttachments } func TestInvokeGenericServiceRPCReferenceTimeout(t *testing.T) { @@ -137,12 +182,16 @@ func TestInvokeGenericServiceRPCReferenceTimeout(t *testing.T) { if err != nil { t.Fatalf("invoke generic service: %v", err) } - if recorder.url == nil { + url := recorder.recordedURL() + if url == nil { t.Fatal("expected a Dubbo reference URL") } - if got := recorder.url.GetParam(dubboconstant.TimeoutKey, ""); got != timeout.String() { + if got := url.GetParam(dubboconstant.TimeoutKey, ""); got != timeout.String() { t.Fatalf("expected reference timeout %v, got %q", timeout, got) } + if got := url.GetParam(dubboconstant.ClusterKey, ""); got != dubboconstant.ClusterKeyFailfast { + t.Fatalf("expected failfast cluster, got %q", got) + } }) } @@ -163,10 +212,11 @@ func TestInvokeGenericServiceRPCReferenceTimeout(t *testing.T) { if err != nil { t.Fatalf("invoke generic service: %v", err) } - if recorder.url == nil { + url := recorder.recordedURL() + if url == nil { t.Fatal("expected a Dubbo reference URL") } - rawTimeout := recorder.url.GetParam(dubboconstant.TimeoutKey, "") + rawTimeout := url.GetParam(dubboconstant.TimeoutKey, "") parsed, err := time.ParseDuration(rawTimeout) if err != nil || parsed <= 0 || parsed > 200*time.Millisecond || parsed%time.Millisecond != 0 { t.Fatalf("expected millisecond-aligned timeout in (0, 200ms], got %q (%v)", rawTimeout, err) @@ -190,8 +240,147 @@ func TestInvokeGenericServiceRPCReferenceTimeout(t *testing.T) { if !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("expected deadline exceeded, got %v", err) } - if recorder.url != nil { - t.Fatalf("expected Refer not to be called for expired context, got %v", recorder.url) + if recorder.recordedURL() != nil { + t.Fatalf("expected Refer not to be called for expired context, got %v", recorder.recordedURL()) + } + }) + + t.Run("dubbo/slow-refer-aborts-at-deadline", func(t *testing.T) { + releaseCh := make(chan struct{}) + doneCh := make(chan struct{}) + recorder := &genericInvokeReferenceRecorder{ + referHook: func(*dubbocommon.URL) { + defer close(doneCh) + <-releaseCh + }, + } + t.Cleanup(func() { + close(releaseCh) + <-doneCh + }) + extension.SetProtocol(dubboconstant.DubboProtocol, func() protocolbase.Protocol { return recorder }) + + ctx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancel() + startedAt := time.Now() + _, err := invokeGenericServiceRPC(ctx, genericInvocation{ + URL: "dubbo://127.0.0.1:20880", + Protocol: dubboconstant.DubboProtocol, + Serialization: dubboconstant.Hessian2Serialization, + ServiceName: "example.Calculator", + MethodName: "delay", + Timeout: 5 * time.Second, + }) + elapsed := time.Since(startedAt) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("expected deadline exceeded during slow Refer, got %v", err) + } + if elapsed > time.Second { + t.Fatalf("expected slow Refer to abort near 80ms deadline, took %v", elapsed) + } + if recorder.invoked.Load() != 0 { + t.Fatalf("expected Invoke not to run after Refer deadline, got %d calls", recorder.invoked.Load()) + } + }) + + t.Run("dubbo/recomputes-remaining-budget-after-refer", func(t *testing.T) { + recorder := &genericInvokeReferenceRecorder{ + referHook: func(*dubbocommon.URL) { + time.Sleep(160 * time.Millisecond) + }, + } + extension.SetProtocol(dubboconstant.DubboProtocol, func() protocolbase.Protocol { return recorder }) + + ctx, cancel := context.WithTimeout(context.Background(), 350*time.Millisecond) + defer cancel() + _, err := invokeGenericServiceRPC(ctx, genericInvocation{ + URL: "dubbo://127.0.0.1:20880", + Protocol: dubboconstant.DubboProtocol, + Serialization: dubboconstant.Hessian2Serialization, + ServiceName: "example.Calculator", + MethodName: "delay", + Timeout: 5 * time.Second, + }) + if err != nil { + t.Fatalf("invoke generic service: %v", err) + } + if recorder.invoked.Load() != 1 { + t.Fatalf("expected 1 Invoke call, got %d", recorder.invoked.Load()) + } + attachments := recorder.recordedAttachments() + rawTimeout, ok := attachments[dubboconstant.TimeoutKey].(string) + if !ok { + t.Fatalf("expected string timeout attachment, got %#v", attachments[dubboconstant.TimeoutKey]) + } + parsed, err := time.ParseDuration(rawTimeout) + if err != nil || parsed <= 0 || parsed > 230*time.Millisecond { + t.Fatalf("expected remaining timeout <= 230ms after 160ms Refer, got %q (%v)", rawTimeout, err) + } + }) + + t.Run("dubbo/rejects-canceled-after-refer", func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + recorder := &genericInvokeReferenceRecorder{ + referHook: func(*dubbocommon.URL) { + cancel() + }, + } + extension.SetProtocol(dubboconstant.DubboProtocol, func() protocolbase.Protocol { return recorder }) + + _, err := invokeGenericServiceRPC(ctx, genericInvocation{ + URL: "dubbo://127.0.0.1:20880", + Protocol: dubboconstant.DubboProtocol, + Serialization: dubboconstant.Hessian2Serialization, + ServiceName: "example.Calculator", + MethodName: "delay", + Timeout: 5 * time.Second, + }) + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected context canceled after Refer, got %v", err) + } + if recorder.invoked.Load() != 0 { + t.Fatalf("expected Invoke not to run after cancellation, got %d calls", recorder.invoked.Load()) + } + }) + + t.Run("dubbo/overrides-user-timeout-attachment", func(t *testing.T) { + recorder := &genericInvokeReferenceRecorder{} + extension.SetProtocol(dubboconstant.DubboProtocol, func() protocolbase.Protocol { return recorder }) + + originalAttachments := map[string]any{ + "timeout": "5s", + "Timeout": "6s", + "traceId": "keep-me", + } + ctx := context.WithValue(context.Background(), dubboconstant.AttachmentKey, originalAttachments) + _, err := invokeGenericServiceRPC(ctx, genericInvocation{ + URL: "dubbo://127.0.0.1:20880", + Protocol: dubboconstant.DubboProtocol, + Serialization: dubboconstant.Hessian2Serialization, + ServiceName: "example.Calculator", + MethodName: "delay", + Timeout: 120 * time.Millisecond, + }) + if err != nil { + t.Fatalf("invoke generic service: %v", err) + } + attachments := recorder.recordedAttachments() + rawTimeout, ok := attachments[dubboconstant.TimeoutKey].(string) + if !ok { + t.Fatalf("expected string timeout attachment, got %#v", attachments[dubboconstant.TimeoutKey]) + } + parsed, err := time.ParseDuration(rawTimeout) + if err != nil || parsed <= 0 || parsed > 120*time.Millisecond { + t.Fatalf("expected overridden timeout in (0, 120ms], got %q (%v)", rawTimeout, err) + } + if _, exists := attachments["Timeout"]; exists { + t.Fatalf("expected case-variant Timeout attachment to be stripped, got %#v", attachments) + } + if got := attachments["traceId"]; got != "keep-me" { + t.Fatalf("expected non-timeout attachment traceId=keep-me, got %#v", got) + } + if got := originalAttachments["timeout"]; got != "5s" { + t.Fatalf("expected caller attachments map not to be mutated, got %#v", got) } }) @@ -210,12 +399,16 @@ func TestInvokeGenericServiceRPCReferenceTimeout(t *testing.T) { if err != nil { t.Fatalf("invoke generic service: %v", err) } - if recorder.url == nil { + url := recorder.recordedURL() + if url == nil { t.Fatal("expected a Triple reference URL") } - if got := recorder.url.GetParam(dubboconstant.TimeoutKey, ""); got != (150 * time.Millisecond).String() { + if got := url.GetParam(dubboconstant.TimeoutKey, ""); got != (150 * time.Millisecond).String() { t.Fatalf("expected reference timeout 150ms, got %q", got) } + if got := url.GetParam(dubboconstant.ClusterKey, ""); got != dubboconstant.ClusterKeyFailfast { + t.Fatalf("expected failfast cluster, got %q", got) + } }) } @@ -305,6 +498,7 @@ func TestInvokeServiceGenericInvalidArgsNoRPC(t *testing.T) { var hasDeadline bool var remaining time.Duration var receivedTraceID any + var receivedAttachments map[string]any var capturedInvocation genericInvocation invokeGenericServiceRPC = func( @@ -325,6 +519,7 @@ func TestInvokeServiceGenericInvalidArgsNoRPC(t *testing.T) { if ok { receivedTraceID = attachments["traceId"] + receivedAttachments = attachments } return int32(30), nil } @@ -392,6 +587,8 @@ func TestInvokeServiceGenericInvalidArgsNoRPC(t *testing.T) { req.TimeoutMs = 0 req.Attachments = map[string]string{ "traceId": "abc", + "timeout": "5s", + "Timeout": "6s", } if err := req.Validate(); err != nil { t.Fatal(err) @@ -437,6 +634,12 @@ func TestInvokeServiceGenericInvalidArgsNoRPC(t *testing.T) { receivedTraceID, ) } + if _, exists := receivedAttachments[dubboconstant.TimeoutKey]; exists { + t.Fatalf("expected timeout attachment to be stripped, got %#v", receivedAttachments) + } + if _, exists := receivedAttachments["Timeout"]; exists { + t.Fatalf("expected Timeout attachment to be stripped, got %#v", receivedAttachments) + } if capturedInvocation.MethodName != "add" { t.Fatalf( "expected method add, got %s", From 24a65e43dd619713a3c72185208f59a882e8048b Mon Sep 17 00:00:00 2001 From: Kevin Date: Sun, 6 Dec 2026 10:51:57 +0800 Subject: [PATCH 3/3] fix(console): destroy abandoned generic invoke references and harden timeout tests Signed-off-by: Kevin --- pkg/console/service/service_generic_invoke.go | 72 ++++++++-- .../service_generic_invoke_timeout_test.go | 128 +++++++++++------- .../service_generic_invoke_validation_test.go | 43 +++++- 3 files changed, 175 insertions(+), 68 deletions(-) diff --git a/pkg/console/service/service_generic_invoke.go b/pkg/console/service/service_generic_invoke.go index a86460429..9ab0f7901 100644 --- a/pkg/console/service/service_generic_invoke.go +++ b/pkg/console/service/service_generic_invoke.go @@ -67,8 +67,9 @@ type genericInvokeTarget struct { } type genericServiceCreateResult struct { - svc *dubbogeneric.GenericService - err error + svc *dubbogeneric.GenericService + cleanup func() + err error } var invokeGenericServiceRPC = func(callCtx context.Context, invocation genericInvocation) (any, error) { @@ -123,10 +124,13 @@ var invokeGenericServiceRPC = func(callCtx context.Context, invocation genericIn return nil, err } - svc, err := newGenericServiceWithContext(rpcCtx, cli, invocation.ServiceName, referenceOpts...) + svc, cleanup, err := newGenericServiceWithContext(rpcCtx, cli, invocation.ServiceName, referenceOpts...) if err != nil { return nil, err } + if cleanup != nil { + defer cleanup() + } remainingTimeout, err := resolveGenericInvokeTimeout(rpcCtx, invocation) if err != nil { @@ -142,32 +146,70 @@ func newGenericServiceWithContext( cli *client.Client, serviceName string, opts ...client.ReferenceOption, -) (*dubbogeneric.GenericService, error) { +) (*dubbogeneric.GenericService, func(), error) { if err := ctx.Err(); err != nil { - return nil, err + return nil, nil, err } - resultCh := make(chan genericServiceCreateResult, 1) + resultCh := make(chan genericServiceCreateResult) + doneCh := make(chan struct{}) + defer close(doneCh) + go func() { - defer func() { - if r := recover(); r != nil { - resultCh <- genericServiceCreateResult{ - err: fmt.Errorf("create generic service %s panicked: %v", serviceName, r), + var capturedRefOpts *client.ReferenceOptions + cleanup := func() { + if capturedRefOpts == nil { + return + } + if invoker := capturedRefOpts.GetInvoker(); invoker != nil { + invoker.Destroy() + } + } + + var res genericServiceCreateResult + func() { + defer func() { + if r := recover(); r != nil { + cleanup() + res = genericServiceCreateResult{ + err: fmt.Errorf("create generic service %s panicked: %v", serviceName, r), + } } + }() + callOpts := make([]client.ReferenceOption, 0, len(opts)+1) + callOpts = append(callOpts, opts...) + callOpts = append(callOpts, func(refOpts *client.ReferenceOptions) { + capturedRefOpts = refOpts + }) + svc, err := cli.NewGenericService(serviceName, callOpts...) + if err != nil { + cleanup() + res = genericServiceCreateResult{err: err} + return } + res = genericServiceCreateResult{svc: svc, cleanup: cleanup} }() - svc, err := cli.NewGenericService(serviceName, opts...) - resultCh <- genericServiceCreateResult{svc: svc, err: err} + + select { + case resultCh <- res: + case <-doneCh: + if res.cleanup != nil { + res.cleanup() + } + } }() select { case res := <-resultCh: if err := ctx.Err(); err != nil { - return nil, err + if res.cleanup != nil { + res.cleanup() + } + return nil, nil, err } - return res.svc, res.err + return res.svc, res.cleanup, res.err case <-ctx.Done(): - return nil, ctx.Err() + return nil, nil, ctx.Err() } } diff --git a/pkg/console/service/service_generic_invoke_timeout_test.go b/pkg/console/service/service_generic_invoke_timeout_test.go index 4965de8ac..7da5e0567 100644 --- a/pkg/console/service/service_generic_invoke_timeout_test.go +++ b/pkg/console/service/service_generic_invoke_timeout_test.go @@ -100,74 +100,98 @@ func reserveLocalTCPPort(t *testing.T) int { return port } -func waitForLocalTCPReady(t *testing.T, addr string) { - t.Helper() - deadline := time.Now().Add(5 * time.Second) +func waitForLocalTCPReady(addr string, timeout time.Duration) bool { + deadline := time.Now().Add(timeout) for time.Now().Before(deadline) { conn, err := net.DialTimeout("tcp", addr, 100*time.Millisecond) if err == nil { _ = conn.Close() - return + return true } time.Sleep(20 * time.Millisecond) } - t.Fatalf("server at %s did not become ready in time", addr) + return false } func exportDelayedGenericServer(t *testing.T, protoName, serviceName string) (string, *delayedRealGenericInvoker) { t.Helper() - port := reserveLocalTCPPort(t) - addr := fmt.Sprintf("127.0.0.1:%d", port) - rawURL := fmt.Sprintf( - "%s://%s/%s?interface=%s&serialization=%s", - protoName, - addr, - serviceName, - serviceName, - dubboconstant.Hessian2Serialization, - ) - url, err := dubbocommon.NewURL(rawURL) - if err != nil { - t.Fatalf("build server url %s: %v", rawURL, err) - } - url.Port = strconv.Itoa(port) - if protoName == dubboconstant.TriProtocol { - url.SetParam(dubboconstant.IDLMode, dubboconstant.NONIDL) - url.SetAttribute(dubboconstant.TripleConfigKey, global.DefaultTripleConfig()) - url.SetAttribute(dubboconstant.ServiceInfoKey, &dubbocommon.ServiceInfo{ - InterfaceName: serviceName, - Methods: []dubbocommon.MethodInfo{{ - Name: dubboconstant.Generic, - Type: dubboconstant.CallUnary, - ReqInitFunc: func() any { - methodName := "" - return []any{&methodName, &[]string{}, &[]hessian.Object{}} - }, - }}, - }) - } + var lastErr error + for attempt := 0; attempt < 5; attempt++ { + port := reserveLocalTCPPort(t) + addr := fmt.Sprintf("127.0.0.1:%d", port) + rawURL := fmt.Sprintf( + "%s://%s/%s?interface=%s&serialization=%s", + protoName, + addr, + serviceName, + serviceName, + dubboconstant.Hessian2Serialization, + ) + url, err := dubbocommon.NewURL(rawURL) + if err != nil { + t.Fatalf("build server url %s: %v", rawURL, err) + } + url.Port = strconv.Itoa(port) + if protoName == dubboconstant.TriProtocol { + url.SetParam(dubboconstant.IDLMode, dubboconstant.NONIDL) + url.SetAttribute(dubboconstant.TripleConfigKey, global.DefaultTripleConfig()) + url.SetAttribute(dubboconstant.ServiceInfoKey, &dubbocommon.ServiceInfo{ + InterfaceName: serviceName, + Methods: []dubbocommon.MethodInfo{{ + Name: dubboconstant.Generic, + Type: dubboconstant.CallUnary, + ReqInitFunc: func() any { + methodName := "" + return []any{&methodName, &[]string{}, &[]hessian.Object{}} + }, + }}, + }) + } - invoker := newDelayedRealGenericInvoker(url) - exporter := extension.GetProtocol(protoName).Export(invoker) - t.Cleanup(func() { + invoker := newDelayedRealGenericInvoker(url) + var exporter protocolbase.Exporter + var exportErr error + func() { + defer func() { + if r := recover(); r != nil { + exportErr = fmt.Errorf("export %s on %s panicked: %v", protoName, addr, r) + } + }() + exporter = extension.GetProtocol(protoName).Export(invoker) + }() + if exportErr != nil { + lastErr = exportErr + continue + } + if waitForLocalTCPReady(addr, 3*time.Second) { + t.Cleanup(func() { + exporter.UnExport() + }) + return fmt.Sprintf("%s://%s", protoName, addr), invoker + } exporter.UnExport() - }) - waitForLocalTCPReady(t, addr) - return fmt.Sprintf("%s://%s", protoName, addr), invoker + lastErr = fmt.Errorf("server at %s did not become ready", addr) + } + t.Fatalf("failed to export %s server after retries: %v", protoName, lastErr) + return "", nil } -func isGenericInvokeTimeoutErr(err error) bool { +func isGenericInvokeTimeoutErr(protoName string, err error) bool { if err == nil { return false } if errors.Is(err, context.DeadlineExceeded) { return true } - if tri.IsWireError(err) && tri.CodeOf(err) == tri.CodeDeadlineExceeded { - return true + switch protoName { + case dubboconstant.TriProtocol: + return tri.IsWireError(err) && tri.CodeOf(err) == tri.CodeDeadlineExceeded + case dubboconstant.DubboProtocol: + // The pinned dubbo-go getty transport returns an unexported errClientReadTimeout sentinel. + return strings.Contains(strings.ToLower(err.Error()), "client read timeout") + default: + return false } - msg := strings.ToLower(err.Error()) - return strings.Contains(msg, "timeout") || strings.Contains(msg, "deadline") } func TestInvokeGenericServiceRPCRealProtocolTimeout(t *testing.T) { @@ -199,7 +223,7 @@ func TestInvokeGenericServiceRPCRealProtocolTimeout(t *testing.T) { } t.Run("below-3s-times-out-without-retry", func(t *testing.T) { - release := invoker.configure(800 * time.Millisecond) + release := invoker.configure(1000 * time.Millisecond) defer release() inv := baseInvocation @@ -208,10 +232,10 @@ func TestInvokeGenericServiceRPCRealProtocolTimeout(t *testing.T) { _, err := invokeGenericServiceRPC(context.Background(), inv) elapsed := time.Since(startedAt) - if !isGenericInvokeTimeoutErr(err) { + if !isGenericInvokeTimeoutErr(protoName, err) { t.Fatalf("expected %s timeout error, got %v", protoName, err) } - if elapsed >= 2*time.Second { + if elapsed >= 2500*time.Millisecond { t.Fatalf("expected %s timeout well below 3s fallback, took %v", protoName, elapsed) } if attempts := invoker.attempts.Load(); attempts != 1 { @@ -220,7 +244,7 @@ func TestInvokeGenericServiceRPCRealProtocolTimeout(t *testing.T) { }) t.Run("timeout-attachment-cannot-override-timeoutMs", func(t *testing.T) { - release := invoker.configure(800 * time.Millisecond) + release := invoker.configure(1000 * time.Millisecond) defer release() ctx := context.WithValue(context.Background(), dubboconstant.AttachmentKey, map[string]any{ @@ -234,10 +258,10 @@ func TestInvokeGenericServiceRPCRealProtocolTimeout(t *testing.T) { _, err := invokeGenericServiceRPC(ctx, inv) elapsed := time.Since(startedAt) - if !isGenericInvokeTimeoutErr(err) { + if !isGenericInvokeTimeoutErr(protoName, err) { t.Fatalf("expected %s timeout error despite timeout attachment, got %v", protoName, err) } - if elapsed >= 2*time.Second { + if elapsed >= 2500*time.Millisecond { t.Fatalf("expected %s timeout well below 5s attachment override, took %v", protoName, elapsed) } if attempts := invoker.attempts.Load(); attempts != 1 { diff --git a/pkg/console/service/service_generic_invoke_validation_test.go b/pkg/console/service/service_generic_invoke_validation_test.go index b72baf206..a745583cd 100644 --- a/pkg/console/service/service_generic_invoke_validation_test.go +++ b/pkg/console/service/service_generic_invoke_validation_test.go @@ -123,13 +123,27 @@ func (inv *genericInvokeRecordingInvoker) Invoke(_ context.Context, ivc protocol return &protocolresult.RPCResult{} } +func (inv *genericInvokeRecordingInvoker) Destroy() { + inv.BaseInvoker.Destroy() + inv.recorder.destroyed.Add(1) + inv.recorder.mu.Lock() + ch := inv.recorder.destroyCh + inv.recorder.destroyCh = nil + inv.recorder.mu.Unlock() + if ch != nil { + close(ch) + } +} + type genericInvokeReferenceRecorder struct { protocolbase.BaseProtocol mu sync.Mutex url *dubbocommon.URL invAttachments map[string]any referHook func(*dubbocommon.URL) + destroyCh chan struct{} invoked atomic.Int32 + destroyed atomic.Int32 } func (p *genericInvokeReferenceRecorder) Refer(url *dubbocommon.URL) protocolbase.Invoker { @@ -248,14 +262,20 @@ func TestInvokeGenericServiceRPCReferenceTimeout(t *testing.T) { t.Run("dubbo/slow-refer-aborts-at-deadline", func(t *testing.T) { releaseCh := make(chan struct{}) doneCh := make(chan struct{}) + destroyCh := make(chan struct{}) + var releaseOnce sync.Once + release := func() { + releaseOnce.Do(func() { close(releaseCh) }) + } recorder := &genericInvokeReferenceRecorder{ + destroyCh: destroyCh, referHook: func(*dubbocommon.URL) { defer close(doneCh) <-releaseCh }, } t.Cleanup(func() { - close(releaseCh) + release() <-doneCh }) extension.SetProtocol(dubboconstant.DubboProtocol, func() protocolbase.Protocol { return recorder }) @@ -281,6 +301,17 @@ func TestInvokeGenericServiceRPCReferenceTimeout(t *testing.T) { if recorder.invoked.Load() != 0 { t.Fatalf("expected Invoke not to run after Refer deadline, got %d calls", recorder.invoked.Load()) } + + // Unblock the background Refer and confirm the abandoned invoker is destroyed. + release() + select { + case <-destroyCh: + case <-time.After(2 * time.Second): + t.Fatal("expected abandoned generic service invoker to be destroyed after timeout") + } + if got := recorder.destroyed.Load(); got != 1 { + t.Fatalf("expected abandoned invoker Destroy count 1, got %d", got) + } }) t.Run("dubbo/recomputes-remaining-budget-after-refer", func(t *testing.T) { @@ -320,7 +351,9 @@ func TestInvokeGenericServiceRPCReferenceTimeout(t *testing.T) { t.Run("dubbo/rejects-canceled-after-refer", func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + destroyCh := make(chan struct{}) recorder := &genericInvokeReferenceRecorder{ + destroyCh: destroyCh, referHook: func(*dubbocommon.URL) { cancel() }, @@ -341,6 +374,14 @@ func TestInvokeGenericServiceRPCReferenceTimeout(t *testing.T) { if recorder.invoked.Load() != 0 { t.Fatalf("expected Invoke not to run after cancellation, got %d calls", recorder.invoked.Load()) } + select { + case <-destroyCh: + case <-time.After(2 * time.Second): + t.Fatal("expected canceled generic service invoker to be destroyed") + } + if got := recorder.destroyed.Load(); got != 1 { + t.Fatalf("expected canceled invoker Destroy count 1, got %d", got) + } }) t.Run("dubbo/overrides-user-timeout-attachment", func(t *testing.T) {