Skip to content

Commit 2210462

Browse files
authored
fix(metadata, protocol, proxy): preserve request context across RPC paths (#3579)
* fix(context): preserve request context across RPC paths * fix: resolve context propagation lint findings * fix(rest): stop invocation after parameter parse errors * fix(context): address PR review cancellation feedback * fix: address context lint review findings * refactor(registry): simplify metadata lookup * fix(jsonrpc): preserve pipelined response order * refactor(jsonrpc): reuse content type header constant * fix(jsonrpc): isolate pipelined request timeouts * fix(jsonrpc): bound pipelined request window * chore(jsonrpc): apply modernize formatting
1 parent c79f616 commit 2210462

16 files changed

Lines changed: 1213 additions & 146 deletions

‎metadata/client.go‎

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,18 @@ func GetMetadataFromMetadataReport(revision string, instance registry.ServiceIns
5555
}
5656

5757
func GetMetadataFromRpc(revision string, instance registry.ServiceInstance) (*info.MetadataInfo, error) {
58+
return GetMetadataFromRpcWithContext(context.Background(), revision, instance)
59+
}
60+
61+
// GetMetadataFromRpcWithContext fetches metadata through the metadata service
62+
// while preserving the caller's context for the underlying RPC invocation.
63+
func GetMetadataFromRpcWithContext(ctx context.Context, revision string, instance registry.ServiceInstance) (*info.MetadataInfo, error) {
64+
if ctx == nil {
65+
ctx = context.Background()
66+
}
67+
if err := ctx.Err(); err != nil {
68+
return nil, err
69+
}
5870
url, err := buildStandardMetadataServiceURL(instance)
5971
if err != nil {
6072
return nil, err
@@ -74,27 +86,28 @@ func GetMetadataFromRpc(revision string, instance registry.ServiceInstance) (*in
7486
defer func() {
7587
invoker.Destroy()
7688
}()
77-
return remoteService.getMetadataInfo(context.Background(), revision)
89+
return remoteService.getMetadataInfo(ctx, revision)
7890
}
7991

8092
// remoteMetadataService is the internal interface for fetching MetadataInfo via RPC.
81-
// The context parameter is accepted for future cancellation support but is not yet propagated.
8293
type remoteMetadataService interface {
83-
getMetadataInfo(_ context.Context, revision string) (*info.MetadataInfo, error)
94+
getMetadataInfo(ctx context.Context, revision string) (*info.MetadataInfo, error)
8495
}
8596

8697
type triMetadataServiceV2 struct {
8798
invoker base.Invoker
8899
}
89100

90101
// getMetadataInfo fetches metadata via RPC using the Triple protocol (Protobuf).
91-
// TODO(context-propagation): ctx is not yet forwarded to the invoker; cancellation is not respected.
92-
func (m *triMetadataServiceV2) getMetadataInfo(_ context.Context, revision string) (*info.MetadataInfo, error) {
102+
func (m *triMetadataServiceV2) getMetadataInfo(ctx context.Context, revision string) (*info.MetadataInfo, error) {
93103
const methodName = "GetMetadataInfo"
94104
req := &tripleapi.MetadataRequest{Revision: revision}
95105
metadataInfo := &tripleapi.MetadataInfoV2{}
96106
inv, _ := generateInvocation(m.invoker.GetURL(), methodName, req, metadataInfo, constant.CallUnary)
97-
res := m.invoker.Invoke(context.Background(), inv)
107+
if rpcInv, ok := inv.(*invocation.RPCInvocation); ok {
108+
rpcInv.SetContext(ctx)
109+
}
110+
res := m.invoker.Invoke(ctx, inv)
98111
if res.Error() != nil {
99112
logger.Errorf("[Metadata][RPC] could not get the metadata info from remote provider, err=%v", res.Error())
100113
return nil, perrors.Wrapf(res.Error(), "remote metadata call failed")
@@ -160,15 +173,17 @@ type remoteMetadataServiceV1 struct {
160173
}
161174

162175
// getMetadataInfo fetches metadata via RPC using the dubbo:// protocol (Hessian2 serialization).
163-
// TODO(context-propagation): ctx is not yet forwarded to the invoker; cancellation is not respected.
164-
func (m *remoteMetadataServiceV1) getMetadataInfo(_ context.Context, revision string) (*info.MetadataInfo, error) {
176+
func (m *remoteMetadataServiceV1) getMetadataInfo(ctx context.Context, revision string) (*info.MetadataInfo, error) {
165177
const methodName = "getMetadataInfo"
166178
// Use interface{} as reply parameter to accept any type (MetadataInfo or string)
167179
// This avoids panic when Java returns String instead of MetadataInfo
168180
var rawResult any
169181
inv, _ := generateInvocation(m.invoker.GetURL(), methodName, revision, &rawResult, constant.CallUnary)
182+
if rpcInv, ok := inv.(*invocation.RPCInvocation); ok {
183+
rpcInv.SetContext(ctx)
184+
}
170185

171-
res := m.invoker.Invoke(context.Background(), inv)
186+
res := m.invoker.Invoke(ctx, inv)
172187
if res.Error() != nil {
173188
logger.Errorf("[Metadata][RPC] RPC call failed to %s, err=%v", m.invoker.GetURL().Location, res.Error())
174189
return nil, perrors.Wrapf(res.Error(), "RPC call failed to %s", m.invoker.GetURL().Location)

‎metadata/client_test.go‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ var (
6363
}
6464
)
6565

66+
type metadataContextKey struct{}
67+
6668
func TestConvertMetadataInfoV2PreservesTag(t *testing.T) {
6769
got := convertMetadataInfoV2(&tripleapi.MetadataInfoV2{
6870
App: "dubbo-app",
@@ -186,6 +188,39 @@ func TestGetMetadataFromRpc(t *testing.T) {
186188
})
187189
}
188190

191+
func TestGetMetadataFromRpcWithContext(t *testing.T) {
192+
mockInvoker := new(mockInvoker)
193+
mockProtocol := new(mockProtocol)
194+
extension.SetProtocol("dubbo", func() base.Protocol {
195+
return mockProtocol
196+
})
197+
198+
mockProtocol.On("Refer").Return(mockInvoker).Once()
199+
mockInvoker.On("Invoke").Return(&result.RPCResult{
200+
Attrs: map[string]any{},
201+
Rest: metadataInfo,
202+
}).Once()
203+
mockInvoker.On("Destroy").Once()
204+
205+
ctx := context.WithValue(context.Background(), metadataContextKey{}, "request-value")
206+
metadata, err := GetMetadataFromRpcWithContext(ctx, "111", ins)
207+
require.NoError(t, err)
208+
assert.Equal(t, metadataInfo, metadata)
209+
assert.Same(t, ctx, mockInvoker.invokedContext)
210+
}
211+
212+
func TestTriMetadataServiceWithContext(t *testing.T) {
213+
mockInvoker := new(mockInvoker)
214+
mockInvoker.url = common.NewURLWithOptions(common.WithProtocol(constant.TriProtocol))
215+
mockInvoker.On("Invoke").Return(&result.RPCResult{Attrs: map[string]any{}}).Once()
216+
217+
ctx := context.WithValue(context.Background(), metadataContextKey{}, "request-value")
218+
metadata, err := (&triMetadataServiceV2{invoker: mockInvoker}).getMetadataInfo(ctx, "111")
219+
require.NoError(t, err)
220+
require.NotNil(t, metadata)
221+
assert.Same(t, ctx, mockInvoker.invokedContext)
222+
}
223+
189224
func TestGetMetadataFromRpc_MissingURLParams(t *testing.T) {
190225
t.Run("missing protocol", func(t *testing.T) {
191226
insNoProto := &registry.DefaultServiceInstance{
@@ -377,9 +412,14 @@ func (m *mockProtocol) Destroy() {
377412

378413
type mockInvoker struct {
379414
mock.Mock
415+
invokedContext context.Context
416+
url *common.URL
380417
}
381418

382419
func (m *mockInvoker) GetURL() *common.URL {
420+
if m.url != nil {
421+
return m.url
422+
}
383423
return common.NewURLWithOptions(common.WithProtocol(constant.DefaultProtocol))
384424
}
385425

@@ -392,6 +432,7 @@ func (m *mockInvoker) Destroy() {
392432
}
393433

394434
func (m *mockInvoker) Invoke(ctx context.Context, inv base.Invocation) result.Result {
435+
m.invokedContext = ctx
395436
args := m.Called()
396437
res := args.Get(0).(result.Result)
397438

‎protocol/dubbo/dubbo_invoker.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -137,17 +137,17 @@ func (di *DubboInvoker) Invoke(ctx context.Context, ivc base.Invocation) result.
137137
timeout := di.getTimeout(inv)
138138
if async {
139139
if callBack, ok := inv.CallBack().(func(response common.CallbackResponse)); ok {
140-
err = client.AsyncRequest(&ivc, url, timeout, callBack, rest)
140+
err = client.AsyncRequestContext(ctx, &ivc, url, timeout, callBack, rest)
141141
res.SetError(err)
142142
} else {
143-
err = client.Send(&ivc, url, timeout)
143+
err = client.SendContext(ctx, &ivc, url, timeout)
144144
res.SetError(err)
145145
}
146146
} else {
147147
if inv.Reply() == nil {
148148
res.SetError(base.ErrNoReply)
149149
} else {
150-
err = client.Request(&ivc, url, timeout, rest)
150+
err = client.RequestContext(ctx, &ivc, url, timeout, rest)
151151
res.SetError(err)
152152
}
153153
}

‎protocol/invocation/rpcinvocation.go‎

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ type RPCInvocation struct {
4747
arguments []any
4848
reply any
4949
callBack any
50+
ctx context.Context
5051
attachments map[string]any
5152
// Refer to dubbo 2.7.6. It is different from attachment. It is used in internal process.
5253
attributes map[string]any
@@ -180,6 +181,27 @@ func (r *RPCInvocation) SetCallBack(c any) {
180181
r.callBack = c
181182
}
182183

184+
// Context returns the request context associated with this invocation.
185+
func (r *RPCInvocation) Context() context.Context {
186+
r.lock.RLock()
187+
ctx := r.ctx
188+
r.lock.RUnlock()
189+
if ctx == nil {
190+
return context.Background()
191+
}
192+
return ctx
193+
}
194+
195+
// SetContext associates a request context with this invocation.
196+
func (r *RPCInvocation) SetContext(ctx context.Context) {
197+
if ctx == nil {
198+
return
199+
}
200+
r.lock.Lock()
201+
defer r.lock.Unlock()
202+
r.ctx = ctx
203+
}
204+
183205
func (r *RPCInvocation) ServiceKey() string {
184206
return common.ServiceKey(strings.TrimPrefix(r.GetAttachmentWithDefaultValue(constant.PathKey, r.GetAttachmentWithDefaultValue(constant.InterfaceKey, "")), "/"),
185207
r.GetAttachmentWithDefaultValue(constant.GroupKey, ""), r.GetAttachmentWithDefaultValue(constant.VersionKey, ""))
@@ -250,14 +272,16 @@ func (r *RPCInvocation) GetAttributeWithDefaultValue(key string, defaultValue an
250272
}
251273

252274
func (r *RPCInvocation) GetAttachmentAsContext() context.Context {
253-
ctx := context.Background()
254-
var header = http.Header{}
275+
ctx := r.Context()
276+
header := cloneOutgoingHeader(triple_protocol.ExtractFromOutgoingContext(ctx))
255277
for k, v := range r.Attachments() {
256278
if str, ok := v.(string); ok {
279+
header.Del(k)
257280
header.Set(k, str)
258281
continue
259282
}
260283
if str, ok := v.([]string); ok {
284+
header.Del(k)
261285
for _, s := range str {
262286
header.Add(k, s)
263287
}
@@ -267,6 +291,14 @@ func (r *RPCInvocation) GetAttachmentAsContext() context.Context {
267291
return triple_protocol.NewOutgoingContext(ctx, header)
268292
}
269293

294+
func cloneOutgoingHeader(header http.Header) http.Header {
295+
cloned := make(http.Header, len(header))
296+
for key, values := range header {
297+
cloned[key] = append([]string(nil), values...)
298+
}
299+
return cloned
300+
}
301+
270302
func (r *RPCInvocation) MergeAttachmentFromContext(ctx context.Context) {
271303
header := triple_protocol.ExtractFromOutgoingContext(ctx)
272304
if header == nil {
@@ -349,6 +381,13 @@ func WithCallBack(callBack any) option {
349381
}
350382
}
351383

384+
// WithContext creates an option with the request context.
385+
func WithContext(ctx context.Context) option {
386+
return func(invo *RPCInvocation) {
387+
invo.SetContext(ctx)
388+
}
389+
}
390+
352391
// WithAttachments creates option with @attachments.
353392
func WithAttachments(attachments map[string]any) option {
354393
return func(invo *RPCInvocation) {

‎protocol/invocation/rpcinvocation_test.go‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,38 @@ func TestRPCInvocation_GetAttachmentAsContext(t *testing.T) {
408408
assert.NotContains(t, header, "key3")
409409
}
410410

411+
func TestRPCInvocation_GetAttachmentAsContextPreservesRequestContext(t *testing.T) {
412+
type requestContextKey struct{}
413+
requestCtx := context.WithValue(context.Background(), requestContextKey{}, "request-value")
414+
invocation := NewRPCInvocationWithOptions(
415+
WithContext(requestCtx),
416+
WithAttachment("key", "value"),
417+
)
418+
419+
ctx := invocation.GetAttachmentAsContext()
420+
assert.Equal(t, "request-value", ctx.Value(requestContextKey{}))
421+
assert.Equal(t, "value", triple_protocol.ExtractFromOutgoingContext(ctx).Get("key"))
422+
}
423+
424+
func TestRPCInvocation_GetAttachmentAsContextPreservesOutgoingAttachments(t *testing.T) {
425+
requestCtx := context.Background()
426+
requestCtx = triple_protocol.NewOutgoingContext(requestCtx, http.Header{
427+
"Existing": {"existing-value"},
428+
"Shared": {"old-value"},
429+
})
430+
invocation := NewRPCInvocationWithOptions(
431+
WithContext(requestCtx),
432+
WithAttachment("New", "new-value"),
433+
WithAttachment("Shared", "new-shared-value"),
434+
)
435+
436+
ctx := invocation.GetAttachmentAsContext()
437+
header := triple_protocol.ExtractFromOutgoingContext(ctx)
438+
assert.Equal(t, []string{"existing-value"}, header.Values("Existing"))
439+
assert.Equal(t, []string{"new-value"}, header.Values("New"))
440+
assert.Equal(t, []string{"new-shared-value"}, header.Values("Shared"))
441+
}
442+
411443
func TestRPCInvocation_MergeAttachmentFromContext(t *testing.T) {
412444
invocation := NewRPCInvocationWithOptions()
413445

0 commit comments

Comments
 (0)