Skip to content

Commit

Permalink
feat: support fallback by ctx
Browse files Browse the repository at this point in the history
  • Loading branch information
HeyJavaBean committed Oct 25, 2024
1 parent 99816dc commit 16a5d0b
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
6 changes: 5 additions & 1 deletion client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,11 @@ func (kc *kClient) Call(ctx context.Context, method string, request, response in
}

// do fallback if with setup
err, reportErr = doFallbackIfNeeded(ctx, ri, request, response, err, kc.opt.Fallback, callOpts)
fb := kc.opt.Fallback
if fb == nil {
fb = getContextFallback(ctx)
}
err, reportErr = doFallbackIfNeeded(ctx, ri, request, response, err, fb, callOpts)
return err
}

Expand Down
37 changes: 37 additions & 0 deletions client/context_fallback.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright 2022 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 client

import (
"context"

"github.com/cloudwego/kitex/pkg/fallback"
)

type ctxFallbackKey struct{}

// WithContextFallback add a fallback into current ctx
// Every client receive this ctx will execute the fallback.
// Note that ContextFallback is prior to the ClientFallback.
func WithContextFallback(ctx context.Context, fb *fallback.Policy) context.Context {
return context.WithValue(ctx, ctxFallbackKey{}, fb)
}

func getContextFallback(ctx context.Context) *fallback.Policy {
fb, _ := ctx.Value(ctxFallbackKey{}).(*fallback.Policy)
return fb
}

0 comments on commit 16a5d0b

Please sign in to comment.