github.com/m3db/m3@v1.5.0/src/dbnode/network/server/tchannelthrift/context.go (about) 1 // Copyright (c) 2016 Uber Technologies, Inc. 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a copy 4 // of this software and associated documentation files (the "Software"), to deal 5 // in the Software without restriction, including without limitation the rights 6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 // copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in 11 // all copies or substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 // THE SOFTWARE. 20 21 package tchannelthrift 22 23 import ( 24 stdctx "context" 25 "time" 26 27 "github.com/m3db/m3/src/x/context" 28 29 apachethrift "github.com/apache/thrift/lib/go/thrift" 30 "github.com/uber/tchannel-go" 31 "github.com/uber/tchannel-go/thrift" 32 ) 33 34 const ( 35 contextKey = "m3dbcontext" 36 ) 37 38 // RegisterServer will register a tchannel thrift server and create and close M3DB contexts per request 39 func RegisterServer(channel *tchannel.Channel, service thrift.TChanServer, contextPool context.Pool) { 40 server := thrift.NewServer(channel) 41 server.Register(service, thrift.OptPostResponse(postResponseFn)) 42 server.SetContextFn(func(ctx stdctx.Context, method string, headers map[string]string) thrift.Context { 43 xCtx := contextPool.Get() 44 xCtx.SetGoContext(ctx) 45 ctxWithValue := stdctx.WithValue(ctx, contextKey, xCtx) //nolint: staticcheck 46 return thrift.WithHeaders(ctxWithValue, headers) 47 }) 48 } 49 50 // NewContext returns a new thrift context and cancel func with embedded M3DB context 51 func NewContext(timeout time.Duration) (thrift.Context, stdctx.CancelFunc) { 52 tctx, cancel := thrift.NewContext(timeout) 53 xCtx := context.NewWithGoContext(tctx) 54 ctxWithValue := stdctx.WithValue(tctx, contextKey, xCtx) //nolint: staticcheck 55 return thrift.WithHeaders(ctxWithValue, nil), cancel 56 } 57 58 // Context returns an M3DB context from the thrift context 59 func Context(ctx thrift.Context) context.Context { 60 return ctx.Value(contextKey).(context.Context) 61 } 62 63 func postResponseFn(ctx stdctx.Context, method string, response apachethrift.TStruct) { 64 value := ctx.Value(contextKey) 65 inner := value.(context.Context) 66 inner.Close() 67 }