Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
204 changes: 193 additions & 11 deletions pkg/console/service/service_generic_invoke.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand All @@ -55,6 +56,7 @@ type genericInvocation struct {
MethodName string
ParameterTypes []string
Args []hessian.Object
Timeout time.Duration
}

type genericInvokeTarget struct {
Expand All @@ -64,7 +66,28 @@ type genericInvokeTarget struct {
serialization string
}

type genericServiceCreateResult struct {
svc *dubbogeneric.GenericService
cleanup func()
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 {
Expand All @@ -83,24 +106,176 @@ 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),
)
client.WithClusterFailFast(),
}
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, 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 {
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, func(), error) {
if err := ctx.Err(); err != nil {
return nil, nil, err
}

resultCh := make(chan genericServiceCreateResult)
doneCh := make(chan struct{})
defer close(doneCh)

go func() {
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}
}()

select {
case resultCh <- res:
case <-doneCh:
if res.cleanup != nil {
res.cleanup()
}
}
}()

select {
case res := <-resultCh:
if err := ctx.Err(); err != nil {
if res.cleanup != nil {
res.cleanup()
}
return nil, nil, err
}
return res.svc, res.cleanup, res.err
case <-ctx.Done():
return nil, nil, ctx.Err()
}
}

return svc.Invoke(callCtx, invocation.MethodName, invocation.ParameterTypes, invocation.Args)
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)
}

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) {
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) {
Expand Down Expand Up @@ -230,15 +405,21 @@ 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 {
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 {
Expand All @@ -263,6 +444,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 {
Expand Down
Loading
Loading