_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q10600
GetRoutingDelegate
train
func (v *RPC) GetRoutingDelegate() (o string) { if v != nil && v.RoutingDelegate != nil { return *v.RoutingDelegate } return }
go
{ "resource": "" }
q10601
GetBody
train
func (v *RPC) GetBody() (o []byte) { if v != nil && v.Body != nil { return v.Body } return }
go
{ "resource": "" }
q10602
New
train
func New(transport peer.Transport, opts ...ListOption) *List { cfg := defaultListConfig for _, o := range opts { o(&cfg) } plOpts := []peerlist.ListOption{ peerlist.Capacity(cfg.capacity), peerlist.Seed(cfg.seed), } if !cfg.shuffle { plOpts = append(plOpts, peerlist.NoShuffle()) } return &List{ List: peerlist.New( "roundrobin", transport, newPeerRing(), plOpts..., ), } }
go
{ "resource": "" }
q10603
decodeRequest
train
func decodeRequest( // call is an inboundCall populated from the transport request and context. call *encodingapi.InboundCall, // buf is a byte buffer from the buffer pool, that will be released back to // the buffer pool by the caller after it is finished with the decoded // request payload. Thrift requests read sets, maps, and lists lazilly. buf *bufferpool.Buffer, treq *transport.Request, // reqEnvelopeType indicates the expected envelope type, if an envelope is // present. reqEnvelopeType wire.EnvelopeType, // proto is the encoding protocol (e.g., Binary) or an // EnvelopeAgnosticProtocol (e.g., EnvelopeAgnosticBinary) proto protocol.Protocol, // enveloping indicates that requests must be enveloped, used only if the // protocol is not envelope agnostic. enveloping bool, ) ( // the wire representation of the decoded request. // decodeRequest does not surface the envelope. wire.Value, // how to encode the response, with the enveloping // strategy corresponding to the request. It is not used for oneway handlers. protocol.Responder, error, ) { if err := errors.ExpectEncodings(treq, Encoding); err != nil { return wire.Value{}, nil, err } if err := call.ReadFromRequest(treq); err != nil { // not reachable return wire.Value{}, nil, err } if _, err := buf.ReadFrom(treq.Body); err != nil { return wire.Value{}, nil, err } reader := bytes.NewReader(buf.Bytes()) // Discover or choose the appropriate envelope if agnosticProto, ok := proto.(protocol.EnvelopeAgnosticProtocol); ok { return agnosticProto.DecodeRequest(reqEnvelopeType, reader) } if enveloping { return decodeEnvelopedRequest(treq, reqEnvelopeType, proto, reader) } return decodeUnenvelopedRequest(proto, reader) }
go
{ "resource": "" }
q10604
wrapUnaryHandler
train
func wrapUnaryHandler(name string, handler interface{}) transport.UnaryHandler { reqBodyType := verifyUnarySignature(name, reflect.TypeOf(handler)) return newJSONHandler(reqBodyType, handler) }
go
{ "resource": "" }
q10605
wrapOnewayHandler
train
func wrapOnewayHandler(name string, handler interface{}) transport.OnewayHandler { reqBodyType := verifyOnewaySignature(name, reflect.TypeOf(handler)) return newJSONHandler(reqBodyType, handler) }
go
{ "resource": "" }
q10606
verifyUnarySignature
train
func verifyUnarySignature(n string, t reflect.Type) reflect.Type { reqBodyType := verifyInputSignature(n, t) if t.NumOut() != 2 { panic(fmt.Sprintf( "expected handler for %q to have 2 results but it had %v", n, t.NumOut(), )) } if t.Out(1) != _errorType { panic(fmt.Sprintf( "handler for %q must return error as its second reuslt, not %v", n, t.Out(1), )) } resBodyType := t.Out(0) if !isValidReqResType(resBodyType) { panic(fmt.Sprintf( "the first result of the handler for %q must be "+ "a struct pointer, a map[string]interface{}, or interface{], and not: %v", n, resBodyType, )) } return reqBodyType }
go
{ "resource": "" }
q10607
verifyOnewaySignature
train
func verifyOnewaySignature(n string, t reflect.Type) reflect.Type { reqBodyType := verifyInputSignature(n, t) if t.NumOut() != 1 { panic(fmt.Sprintf( "expected handler for %q to have 1 result but it had %v", n, t.NumOut(), )) } if t.Out(0) != _errorType { panic(fmt.Sprintf( "the result of the handler for %q must be of type error, and not: %v", n, t.Out(0), )) } return reqBodyType }
go
{ "resource": "" }
q10608
verifyInputSignature
train
func verifyInputSignature(n string, t reflect.Type) reflect.Type { if t.Kind() != reflect.Func { panic(fmt.Sprintf( "handler for %q is not a function but a %v", n, t.Kind(), )) } if t.NumIn() != 2 { panic(fmt.Sprintf( "expected handler for %q to have 2 arguments but it had %v", n, t.NumIn(), )) } if t.In(0) != _ctxType { panic(fmt.Sprintf( "the first argument of the handler for %q must be of type "+ "context.Context, and not: %v", n, t.In(0), )) } reqBodyType := t.In(1) if !isValidReqResType(reqBodyType) { panic(fmt.Sprintf( "the second argument of the handler for %q must be "+ "a struct pointer, a map[string]interface{}, or interface{}, and not: %v", n, reqBodyType, )) } return reqBodyType }
go
{ "resource": "" }
q10609
newInbound
train
func newInbound(t *Transport, listener net.Listener, options ...InboundOption) *Inbound { return &Inbound{ once: lifecycle.NewOnce(), t: t, listener: listener, options: newInboundOptions(options), } }
go
{ "resource": "" }
q10610
Addr
train
func (i *Inbound) Addr() net.Addr { i.lock.RLock() defer i.lock.RUnlock() // i.server is set in start, so checking against nil checks // if Start has been called // we check if i.listener is nil just for safety if i.server == nil || i.listener == nil { return nil } return i.listener.Addr() }
go
{ "resource": "" }
q10611
newTransportOptions
train
func newTransportOptions() transportOptions { return transportOptions{ tracer: opentracing.GlobalTracer(), connTimeout: defaultConnTimeout, connBackoffStrategy: backoff.DefaultExponential, } }
go
{ "resource": "" }
q10612
Tracer
train
func Tracer(tracer opentracing.Tracer) TransportOption { return func(t *transportOptions) { t.tracer = tracer } }
go
{ "resource": "" }
q10613
ConnTimeout
train
func ConnTimeout(d time.Duration) TransportOption { return func(options *transportOptions) { options.connTimeout = d } }
go
{ "resource": "" }
q10614
ConnBackoff
train
func ConnBackoff(s backoffapi.Strategy) TransportOption { return func(options *transportOptions) { options.connBackoffStrategy = s } }
go
{ "resource": "" }
q10615
CreateDispatcherForTransport
train
func CreateDispatcherForTransport(t crossdock.T, trans string) *yarpc.Dispatcher { fatals := crossdock.Fatals(t) server := t.Param(params.Server) fatals.NotEmpty(server, "server is required") var unaryOutbound transport.UnaryOutbound if trans == "" { trans = t.Param(params.Transport) } switch trans { case "http": httpTransport := http.NewTransport() unaryOutbound = httpTransport.NewSingleOutbound(fmt.Sprintf("http://%s:8081", server)) case "tchannel": tchannelTransport, err := tchannel.NewChannelTransport(tchannel.ServiceName("client")) fatals.NoError(err, "Failed to build ChannelTransport") unaryOutbound = tchannelTransport.NewSingleOutbound(server + ":8082") case "grpc": unaryOutbound = grpc.NewTransport().NewSingleOutbound(server + ":8089") default: fatals.Fail("", "unknown transport %q", trans) } return yarpc.NewDispatcher(yarpc.Config{ Name: "client", Outbounds: yarpc.Outbounds{ "yarpc-test": { Unary: unaryOutbound, }, }, }) }
go
{ "resource": "" }
q10616
New
train
func New() *Digester { d := _digesterPool.Get().(*Digester) d.bs = d.bs[:0] return d }
go
{ "resource": "" }
q10617
Add
train
func (d *Digester) Add(s string) { if len(d.bs) > 0 { // separate labels with a null byte d.bs = append(d.bs, '\x00') } d.bs = append(d.bs, s...) }
go
{ "resource": "" }
q10618
loadFile
train
func (r *registry) loadFile(file *descriptor.FileDescriptorProto) { pkg := &GoPackage{ Path: r.goPackagePath(file), Name: defaultGoPackageName(file), } if err := r.ReserveGoPackageAlias(pkg.Name, pkg.Path); err != nil { for i := 0; ; i++ { alias := fmt.Sprintf("%s_%d", pkg.Name, i) if err := r.ReserveGoPackageAlias(alias, pkg.Path); err == nil { pkg.Alias = alias break } } } f := &File{ FileDescriptorProto: file, GoPackage: pkg, } r.files[file.GetName()] = f r.registerMsg(f, nil, file.GetMessageType()) r.registerEnum(f, nil, file.GetEnumType()) }
go
{ "resource": "" }
q10619
loadTransitiveFileDependencies
train
func (r *registry) loadTransitiveFileDependencies(file *File) error { seen := make(map[string]struct{}) files, err := r.loadTransitiveFileDependenciesRecurse(file, seen) if err != nil { return err } file.TransitiveDependencies = files return nil }
go
{ "resource": "" }
q10620
NewInbound
train
func (t *Transport) NewInbound() *Inbound { return &Inbound{ once: lifecycle.NewOnce(), transport: t, } }
go
{ "resource": "" }
q10621
String
train
func (v *KeyValue_SetValue_Args) String() string { if v == nil { return "<nil>" } var fields [2]string i := 0 if v.Key != nil { fields[i] = fmt.Sprintf("Key: %v", *(v.Key)) i++ } if v.Value != nil { fields[i] = fmt.Sprintf("Value: %v", *(v.Value)) i++ } return fmt.Sprintf("KeyValue_SetValue_Args{%v}", strings.Join(fields[:i], ", ")) }
go
{ "resource": "" }
q10622
Equals
train
func (v *KeyValue_SetValue_Args) Equals(rhs *KeyValue_SetValue_Args) bool { if v == nil { return rhs == nil } else if rhs == nil { return false } if !_String_EqualsPtr(v.Key, rhs.Key) { return false } if !_String_EqualsPtr(v.Value, rhs.Value) { return false } return true }
go
{ "resource": "" }
q10623
MarshalLogObject
train
func (v *KeyValue_SetValue_Args) MarshalLogObject(enc zapcore.ObjectEncoder) (err error) { if v == nil { return nil } if v.Key != nil { enc.AddString("key", *v.Key) } if v.Value != nil { enc.AddString("value", *v.Value) } return err }
go
{ "resource": "" }
q10624
GetValue
train
func (v *KeyValue_SetValue_Args) GetValue() (o string) { if v != nil && v.Value != nil { return *v.Value } return }
go
{ "resource": "" }
q10625
Equals
train
func (v *KeyValue_SetValue_Result) Equals(rhs *KeyValue_SetValue_Result) bool { if v == nil { return rhs == nil } else if rhs == nil { return false } return true }
go
{ "resource": "" }
q10626
Do
train
func (c *CreateOpenTracingSpan) Do( ctx context.Context, req *Request, ) (context.Context, opentracing.Span) { var parent opentracing.SpanContext if parentSpan := opentracing.SpanFromContext(ctx); parentSpan != nil { parent = parentSpan.Context() } tags := opentracing.Tags{ "rpc.caller": req.Caller, "rpc.service": req.Service, "rpc.encoding": req.Encoding, "rpc.transport": c.TransportName, } for k, v := range c.ExtraTags { tags[k] = v } span := c.Tracer.StartSpan( req.Procedure, opentracing.StartTime(c.StartTime), opentracing.ChildOf(parent), tags, ) ext.PeerService.Set(span, req.Service) ext.SpanKindRPCClient.Set(span) ctx = opentracing.ContextWithSpan(ctx, span) return ctx, span }
go
{ "resource": "" }
q10627
Do
train
func (e *ExtractOpenTracingSpan) Do( ctx context.Context, req *Request, ) (context.Context, opentracing.Span) { tags := opentracing.Tags{ "rpc.caller": req.Caller, "rpc.service": req.Service, "rpc.encoding": req.Encoding, "rpc.transport": e.TransportName, } for k, v := range e.ExtraTags { tags[k] = v } span := e.Tracer.StartSpan( req.Procedure, opentracing.StartTime(e.StartTime), tags, // parentSpanCtx may be nil // this implies ChildOf ext.RPCServerOption(e.ParentSpanContext), ) ext.PeerService.Set(span, req.Caller) ext.SpanKindRPCServer.Set(span) ctx = opentracing.ContextWithSpan(ctx, span) return ctx, span }
go
{ "resource": "" }
q10628
UpdateSpanWithErr
train
func UpdateSpanWithErr(span opentracing.Span, err error) error { if err != nil { span.SetTag("error", true) span.LogFields(opentracinglog.String("event", err.Error())) } return err }
go
{ "resource": "" }
q10629
begin
train
func (g *graph) begin(ctx context.Context, rpcType transport.Type, direction directionName, req *transport.Request) call { now := _timeNow() d := digester.New() d.Add(req.Caller) d.Add(req.Service) d.Add(req.Transport) d.Add(string(req.Encoding)) d.Add(req.Procedure) d.Add(req.RoutingKey) d.Add(req.RoutingDelegate) d.Add(string(direction)) e := g.getOrCreateEdge(d.Digest(), req, string(direction)) d.Free() return call{ edge: e, extract: g.extract, started: now, ctx: ctx, req: req, rpcType: rpcType, direction: direction, succLevel: g.succLevel, failLevel: g.failLevel, appErrLevel: g.appErrLevel, } }
go
{ "resource": "" }
q10630
FirstBackoff
train
func FirstBackoff(t time.Duration) ExponentialOption { return func(options *exponentialOptions) { options.first = t } }
go
{ "resource": "" }
q10631
MaxBackoff
train
func MaxBackoff(t time.Duration) ExponentialOption { return func(options *exponentialOptions) { options.max = t } }
go
{ "resource": "" }
q10632
randGenerator
train
func randGenerator(newRand func() *rand.Rand) ExponentialOption { return func(options *exponentialOptions) { options.newRand = newRand } }
go
{ "resource": "" }
q10633
Backoff
train
func (e *ExponentialStrategy) Backoff() backoff.Backoff { return &exponentialBackoff{ first: e.opts.first, max: e.opts.max.Nanoseconds(), rand: e.opts.newRand(), } }
go
{ "resource": "" }
q10634
IsEqual
train
func (e *ExponentialStrategy) IsEqual(o *ExponentialStrategy) bool { if e.opts.first != o.opts.first { return false } if e.opts.max != o.opts.max { return false } return true }
go
{ "resource": "" }
q10635
Duration
train
func (e *exponentialBackoff) Duration(attempts uint) time.Duration { spread := (1 << attempts) * e.first.Nanoseconds() if spread <= 0 || spread > e.max { spread = e.max } // Adding 1 to the spread ensures that the upper bound of the range of // possible durations includes the maximum. return time.Duration(e.rand.Int63n(spread + 1)) }
go
{ "resource": "" }
q10636
Equals
train
func (v *SecondService_BlahBlah_Args) Equals(rhs *SecondService_BlahBlah_Args) bool { if v == nil { return rhs == nil } else if rhs == nil { return false } return true }
go
{ "resource": "" }
q10637
Equals
train
func (v *SecondService_BlahBlah_Result) Equals(rhs *SecondService_BlahBlah_Result) bool { if v == nil { return rhs == nil } else if rhs == nil { return false } return true }
go
{ "resource": "" }
q10638
Bind
train
func Bind(chooserList peer.ChooserList, bind peer.Binder) *BoundChooser { return &BoundChooser{ once: lifecycle.NewOnce(), chooserList: chooserList, updater: bind(chooserList), } }
go
{ "resource": "" }
q10639
Choose
train
func (c *BoundChooser) Choose(ctx context.Context, treq *transport.Request) (peer peer.Peer, onFinish func(error), err error) { return c.chooserList.Choose(ctx, treq) }
go
{ "resource": "" }
q10640
IsRunning
train
func (c *BoundChooser) IsRunning() bool { return c.chooserList.IsRunning() && c.updater.IsRunning() }
go
{ "resource": "" }
q10641
Introspect
train
func (c *BoundChooser) Introspect() introspection.ChooserStatus { if ic, ok := c.chooserList.(introspection.IntrospectableChooser); ok { return ic.Introspect() } return introspection.ChooserStatus{} }
go
{ "resource": "" }
q10642
UnaryChain
train
func UnaryChain(mw ...middleware.UnaryOutbound) middleware.UnaryOutbound { unchained := make([]middleware.UnaryOutbound, 0, len(mw)) for _, m := range mw { if m == nil { continue } if c, ok := m.(unaryChain); ok { unchained = append(unchained, c...) continue } unchained = append(unchained, m) } switch len(unchained) { case 0: return middleware.NopUnaryOutbound case 1: return unchained[0] default: return unaryChain(unchained) } }
go
{ "resource": "" }
q10643
OnewayChain
train
func OnewayChain(mw ...middleware.OnewayOutbound) middleware.OnewayOutbound { unchained := make([]middleware.OnewayOutbound, 0, len(mw)) for _, m := range mw { if m == nil { continue } if c, ok := m.(onewayChain); ok { unchained = append(unchained, c...) continue } unchained = append(unchained, m) } switch len(unchained) { case 0: return middleware.NopOnewayOutbound case 1: return unchained[0] default: return onewayChain(unchained) } }
go
{ "resource": "" }
q10644
StreamChain
train
func StreamChain(mw ...middleware.StreamOutbound) middleware.StreamOutbound { unchained := make([]middleware.StreamOutbound, 0, len(mw)) for _, m := range mw { if m == nil { continue } if c, ok := m.(streamChain); ok { unchained = append(unchained, c...) continue } unchained = append(unchained, m) } switch len(unchained) { case 0: return middleware.NopStreamOutbound case 1: return unchained[0] default: return streamChain(unchained) } }
go
{ "resource": "" }
q10645
validateConfigFunc
train
func validateConfigFunc(t reflect.Type, outputType reflect.Type) error { switch { case t.Kind() != reflect.Func: return errors.New("must be a function") case t.NumIn() != 3: return fmt.Errorf("must accept exactly three arguments, found %v", t.NumIn()) case !isDecodable(t.In(0)): return fmt.Errorf("must accept a struct or struct pointer as its first argument, found %v", t.In(0)) case t.In(1) != _typeOfTransport: // TODO: We can make this smarter by making transport.Transport // optional and either the first or the second argument instead of // requiring it as the second argument. return fmt.Errorf("must accept a transport.Transport as its second argument, found %v", t.In(1)) case t.In(2) != _typeOfKit: return fmt.Errorf("must accept a %v as its third argument, found %v", _typeOfKit, t.In(2)) case t.NumOut() != 2: return fmt.Errorf("must return exactly two results, found %v", t.NumOut()) case t.Out(0) != outputType: return fmt.Errorf("must return a %v as its first result, found %v", outputType, t.Out(0)) case t.Out(1) != _typeOfError: return fmt.Errorf("must return an error as its second result, found %v", t.Out(1)) } return nil }
go
{ "resource": "" }
q10646
Build
train
func (c *compiledPeerChooserPreset) Build(t peer.Transport, k *Kit) (peer.Chooser, error) { results := c.factory.Call([]reflect.Value{reflect.ValueOf(t), reflect.ValueOf(k)}) chooser, _ := results[0].Interface().(peer.Chooser) err, _ := results[1].Interface().(error) return chooser, err }
go
{ "resource": "" }
q10647
Decode
train
func (cs *configSpec) Decode(attrs config.AttributeMap, opts ...mapdecode.Option) (*buildable, error) { inputConfig := reflect.New(cs.inputType) if err := attrs.Decode(inputConfig.Interface(), opts...); err != nil { return nil, fmt.Errorf("failed to decode %v: %v", cs.inputType, err) } return &buildable{factory: cs.factory, inputData: inputConfig.Elem()}, nil }
go
{ "resource": "" }
q10648
Build
train
func (cv *buildable) Build(args ...interface{}) (interface{}, error) { // This function roughly translates to, // // return factory(inputData, args...) callArgs := make([]reflect.Value, len(args)+1) callArgs[0] = cv.inputData for i, v := range args { if value, ok := v.(reflect.Value); ok { callArgs[i+1] = value } else { callArgs[i+1] = reflect.ValueOf(v) } } result := cv.factory.Call(callArgs) err, _ := result[1].Interface().(error) return result[0].Interface(), err }
go
{ "resource": "" }
q10649
IntrospectProcedures
train
func IntrospectProcedures(routerProcs []transport.Procedure) []Procedure { procedures := make([]Procedure, 0, len(routerProcs)) for _, p := range routerProcs { procedures = append(procedures, Procedure{ Name: p.Name, Encoding: string(p.Encoding), Signature: p.Signature, RPCType: p.HandlerSpec.Type().String(), }) } return procedures }
go
{ "resource": "" }
q10650
InvokeUnaryHandler
train
func InvokeUnaryHandler( i UnaryInvokeRequest, ) (err error) { defer func() { if r := recover(); r != nil { err = handlePanic(Unary, i.Logger, r, i.Request.ToRequestMeta()) } }() err = i.Handler.Handle(i.Context, i.Request, i.ResponseWriter) // The handler stopped work on context deadline. if err == context.DeadlineExceeded && err == i.Context.Err() { deadline, _ := i.Context.Deadline() err = yarpcerrors.Newf( yarpcerrors.CodeDeadlineExceeded, "call to procedure %q of service %q from caller %q timed out after %v", i.Request.Procedure, i.Request.Service, i.Request.Caller, deadline.Sub(i.StartTime)) } return err }
go
{ "resource": "" }
q10651
InvokeOnewayHandler
train
func InvokeOnewayHandler( i OnewayInvokeRequest, ) (err error) { defer func() { if r := recover(); r != nil { err = handlePanic(Oneway, i.Logger, r, i.Request.ToRequestMeta()) } }() return i.Handler.HandleOneway(i.Context, i.Request) }
go
{ "resource": "" }
q10652
InvokeStreamHandler
train
func InvokeStreamHandler( i StreamInvokeRequest, ) (err error) { defer func() { if r := recover(); r != nil { err = handlePanic(Streaming, i.Logger, r, i.Stream.Request().Meta) } }() return i.Handler.HandleStream(i.Stream) }
go
{ "resource": "" }
q10653
Run
train
func Run(t crossdock.T) { fatals := crossdock.Fatals(t) dispatcher := disp.Create(t) fatals.NoError(dispatcher.Start(), "could not start Dispatcher") defer dispatcher.Stop() t.Tag("transport", t.Param(params.Transport)) t.Tag("server", t.Param(params.Server)) RunGauntlet(t, Config{ Dispatcher: dispatcher, ServerName: serverName, }) }
go
{ "resource": "" }
q10654
Assert
train
func Assert(t crossdock.T, tt TT, desc string, got interface{}, err error) { checks := crossdock.Checks(t) assert := crossdock.Assert(t) if tt.WantError != nil || tt.WantErrorLike != "" { if !checks.Error(err, "%v: expected failure but got: %v", desc, got) { return } if tt.WantError != nil { assert.Equal(tt.WantError, err, "%v: server returned error: %v", desc, err) } if tt.WantErrorLike != "" { assert.Contains(err.Error(), tt.WantErrorLike, "%v: server returned error: %v", desc, err) } } else { if !checks.NoError(err, "%v: call failed", desc) { return } if tt.Want != nil { assert.Equal(tt.Want, got, "%v: server returned: %v", desc, got) } } }
go
{ "resource": "" }
q10655
Run
train
func Run(t crossdock.T) { encoding := t.Param(params.Encoding) f, ok := encodingToRunFunc[encoding] if !ok { crossdock.Fatals(t).Fail("unknown encoding", "%v", encoding) } f(t, "grpc") }
go
{ "resource": "" }
q10656
Call
train
func (o UnaryValidatorOutbound) Call(ctx context.Context, request *transport.Request) (*transport.Response, error) { if err := transport.ValidateRequest(request); err != nil { return nil, err } if err := transport.ValidateRequestContext(ctx); err != nil { return nil, err } return o.UnaryOutbound.Call(ctx, request) }
go
{ "resource": "" }
q10657
CallOneway
train
func (o OnewayValidatorOutbound) CallOneway(ctx context.Context, request *transport.Request) (transport.Ack, error) { if err := transport.ValidateRequest(request); err != nil { return nil, err } if err := transport.ValidateRequestContext(ctx); err != nil { return nil, err } return o.OnewayOutbound.CallOneway(ctx, request) }
go
{ "resource": "" }
q10658
CallStream
train
func (o StreamValidatorOutbound) CallStream(ctx context.Context, request *transport.StreamRequest) (*transport.ClientStream, error) { if err := transport.ValidateRequest(request.Meta.ToRequest()); err != nil { return nil, err } return o.StreamOutbound.CallStream(ctx, request) }
go
{ "resource": "" }
q10659
Render
train
func (s String) Render(resolve VariableResolver) (string, error) { var buff bytes.Buffer if err := s.RenderTo(&buff, resolve); err != nil { return "", err } return buff.String(), nil }
go
{ "resource": "" }
q10660
RenderTo
train
func (s String) RenderTo(w io.Writer, resolve VariableResolver) error { for _, term := range s { var value string switch t := term.(type) { case literal: value = string(t) case variable: if val, ok := resolve(t.Name); ok { value = val } else if t.HasDefault { value = t.Default } else { return errUnknownVariable{Name: t.Name} } } if _, err := io.WriteString(w, value); err != nil { return err } } return nil }
go
{ "resource": "" }
q10661
RemoveVariableMapKeys
train
func RemoveVariableMapKeys(headers map[string]string) { delete(headers, "$tracing$uber-trace-id") delete(headers, tchannel.ServiceHeaderKey) }
go
{ "resource": "" }
q10662
Run
train
func Run(t crossdock.T) { assert := crossdock.Assert(t) fatals := crossdock.Fatals(t) baggage := map[string]string{ "hello": "world", "foo": "bar", } // create handler callBackHandler, serverCalledBack := newCallBackHandler() dispatcher, callBackAddr := dispatcher.CreateOnewayDispatcher(t, callBackHandler) defer dispatcher.Stop() client := raw.New(dispatcher.ClientConfig("oneway-server")) // make call ctx, cancel := context.WithTimeout(newContextWithBaggage(baggage), time.Second) defer cancel() ack, err := client.CallOneway( ctx, "echo/raw", []byte{}, yarpc.WithHeader("callBackAddr", callBackAddr)) fatals.NoError(err, "call to oneway/raw failed: %v", err) fatals.NotNil(ack, "ack is nil") // wait for server to call us back gotBaggage := <-serverCalledBack assert.Equal(baggage, gotBaggage, "server baggage: %s", gotBaggage) }
go
{ "resource": "" }
q10663
newCallBackHandler
train
func newCallBackHandler() (raw.OnewayHandler, <-chan map[string]string) { serverCalledBack := make(chan map[string]string) return func(ctx context.Context, body []byte) error { serverCalledBack <- extractBaggage(ctx) return nil }, serverCalledBack }
go
{ "resource": "" }
q10664
Add
train
func (pr *peerRing) Add(p peer.StatusPeer, _ peer.Identifier) peer.Subscriber { sub := &subscriber{peer: p} newNode := ring.New(1) newNode.Value = sub sub.node = newNode if pr.nextNode == nil { // Empty ring, add the first node pr.nextNode = newNode } else { // Push the node to the ring pushBeforeNode(pr.nextNode, newNode) } return sub }
go
{ "resource": "" }
q10665
Remove
train
func (pr *peerRing) Remove(p peer.StatusPeer, _ peer.Identifier, s peer.Subscriber) { sub, ok := s.(*subscriber) if !ok { // Don't panic. return } node := sub.node if isLastRingNode(node) { pr.nextNode = nil } else { if pr.isNextNode(node) { pr.nextNode = pr.nextNode.Next() } popNodeFromRing(node) } }
go
{ "resource": "" }
q10666
Choose
train
func (pr *peerRing) Choose(_ context.Context, _ *transport.Request) peer.StatusPeer { if pr.nextNode == nil { return nil } p := getPeerForRingNode(pr.nextNode) pr.nextNode = pr.nextNode.Next() return p }
go
{ "resource": "" }
q10667
parseTTL
train
func parseTTL(ctx context.Context, req *transport.Request, ttl string) (_ context.Context, cancel func(), _ error) { if ttl == "" { return ctx, func() {}, nil } ttlms, err := strconv.Atoi(ttl) if err != nil { return ctx, func() {}, newInvalidTTLError( req.Service, req.Procedure, ttl, ) } // negative TTLs are invalid if ttlms < 0 { return ctx, func() {}, newInvalidTTLError( req.Service, req.Procedure, fmt.Sprint(ttlms), ) } ctx, cancel = context.WithTimeout(ctx, time.Duration(ttlms)*time.Millisecond) return ctx, cancel, nil }
go
{ "resource": "" }
q10668
NewSingle
train
func NewSingle(pid peer.Identifier, transport peer.Transport) *Single { s := &Single{ once: lifecycle.NewOnce(), pid: pid, t: transport, } s.boundOnFinish = s.onFinish return s }
go
{ "resource": "" }
q10669
Choose
train
func (s *Single) Choose(ctx context.Context, _ *transport.Request) (peer.Peer, func(error), error) { if err := s.once.WaitUntilRunning(ctx); err != nil { return nil, nil, err } s.p.StartRequest() return s.p, s.boundOnFinish, s.err }
go
{ "resource": "" }
q10670
Introspect
train
func (s *Single) Introspect() introspection.ChooserStatus { if !s.once.IsRunning() { return introspection.ChooserStatus{ Name: "Single", Peers: []introspection.PeerStatus{ { Identifier: s.pid.Identifier(), State: "uninitialized", }, }, } } peerStatus := s.p.Status() peer := introspection.PeerStatus{ Identifier: s.p.Identifier(), State: fmt.Sprintf("%s, %d pending request(s)", peerStatus.ConnectionStatus.String(), peerStatus.PendingRequestCount), } return introspection.ChooserStatus{ Name: "Single", Peers: []introspection.PeerStatus{peer}, } }
go
{ "resource": "" }
q10671
NewDispatcher
train
func NewDispatcher(cfg Config) *Dispatcher { if cfg.Name == "" { panic("yarpc.NewDispatcher expects a service name") } if err := internal.ValidateServiceName(cfg.Name); err != nil { panic("yarpc.NewDispatcher expects a valid service name: " + err.Error()) } logger := cfg.Logging.logger(cfg.Name) extractor := cfg.Logging.extractor() meter, stopMeter := cfg.Metrics.scope(cfg.Name, logger) cfg = addObservingMiddleware(cfg, meter, logger, extractor) return &Dispatcher{ name: cfg.Name, table: middleware.ApplyRouteTable(NewMapRouter(cfg.Name), cfg.RouterMiddleware), inbounds: cfg.Inbounds, outbounds: convertOutbounds(cfg.Outbounds, cfg.OutboundMiddleware), transports: collectTransports(cfg.Inbounds, cfg.Outbounds), inboundMiddleware: cfg.InboundMiddleware, log: logger, meter: meter, stopMeter: stopMeter, once: lifecycle.NewOnce(), } }
go
{ "resource": "" }
q10672
convertOutbounds
train
func convertOutbounds(outbounds Outbounds, mw OutboundMiddleware) Outbounds { outboundSpecs := make(Outbounds, len(outbounds)) for outboundKey, outs := range outbounds { if outs.Unary == nil && outs.Oneway == nil && outs.Stream == nil { panic(fmt.Sprintf("no outbound set for outbound key %q in dispatcher", outboundKey)) } var ( unaryOutbound transport.UnaryOutbound onewayOutbound transport.OnewayOutbound streamOutbound transport.StreamOutbound ) serviceName := outboundKey // apply outbound middleware and create ValidatorOutbounds if outs.Unary != nil { unaryOutbound = middleware.ApplyUnaryOutbound(outs.Unary, mw.Unary) unaryOutbound = request.UnaryValidatorOutbound{UnaryOutbound: unaryOutbound} } if outs.Oneway != nil { onewayOutbound = middleware.ApplyOnewayOutbound(outs.Oneway, mw.Oneway) onewayOutbound = request.OnewayValidatorOutbound{OnewayOutbound: onewayOutbound} } if outs.Stream != nil { streamOutbound = middleware.ApplyStreamOutbound(outs.Stream, mw.Stream) streamOutbound = request.StreamValidatorOutbound{StreamOutbound: streamOutbound} } if outs.ServiceName != "" { serviceName = outs.ServiceName } outboundSpecs[outboundKey] = transport.Outbounds{ ServiceName: serviceName, Unary: unaryOutbound, Oneway: onewayOutbound, Stream: streamOutbound, } } return outboundSpecs }
go
{ "resource": "" }
q10673
collectTransports
train
func collectTransports(inbounds Inbounds, outbounds Outbounds) []transport.Transport { // Collect all unique transports from inbounds and outbounds. transports := make(map[transport.Transport]struct{}) for _, inbound := range inbounds { for _, transport := range inbound.Transports() { transports[transport] = struct{}{} } } for _, outbound := range outbounds { if unary := outbound.Unary; unary != nil { for _, transport := range unary.Transports() { transports[transport] = struct{}{} } } if oneway := outbound.Oneway; oneway != nil { for _, transport := range oneway.Transports() { transports[transport] = struct{}{} } } if stream := outbound.Stream; stream != nil { for _, transport := range stream.Transports() { transports[transport] = struct{}{} } } } keys := make([]transport.Transport, 0, len(transports)) for key := range transports { keys = append(keys, key) } return keys }
go
{ "resource": "" }
q10674
Inbounds
train
func (d *Dispatcher) Inbounds() Inbounds { inbounds := make(Inbounds, len(d.inbounds)) copy(inbounds, d.inbounds) return inbounds }
go
{ "resource": "" }
q10675
Outbounds
train
func (d *Dispatcher) Outbounds() Outbounds { outbounds := make(Outbounds, len(d.outbounds)) for k, v := range d.outbounds { outbounds[k] = v } return outbounds }
go
{ "resource": "" }
q10676
Register
train
func (d *Dispatcher) Register(rs []transport.Procedure) { procedures := make([]transport.Procedure, 0, len(rs)) for _, r := range rs { switch r.HandlerSpec.Type() { case transport.Unary: h := middleware.ApplyUnaryInbound(r.HandlerSpec.Unary(), d.inboundMiddleware.Unary) r.HandlerSpec = transport.NewUnaryHandlerSpec(h) case transport.Oneway: h := middleware.ApplyOnewayInbound(r.HandlerSpec.Oneway(), d.inboundMiddleware.Oneway) r.HandlerSpec = transport.NewOnewayHandlerSpec(h) case transport.Streaming: h := middleware.ApplyStreamInbound(r.HandlerSpec.Stream(), d.inboundMiddleware.Stream) r.HandlerSpec = transport.NewStreamHandlerSpec(h) default: panic(fmt.Sprintf("unknown handler type %q for service %q, procedure %q", r.HandlerSpec.Type(), r.Service, r.Name)) } procedures = append(procedures, r) d.log.Info("Registration succeeded.", zap.Object("registeredProcedure", r)) } d.table.Register(procedures) }
go
{ "resource": "" }
q10677
Stop
train
func (d *Dispatcher) Stop() error { stopper := &PhasedStopper{ dispatcher: d, log: d.log, } return d.once.Stop(func() error { d.log.Info("shutting down dispatcher") return multierr.Combine( stopper.StopInbounds(), stopper.StopOutbounds(), stopper.StopTransports(), ) }) }
go
{ "resource": "" }
q10678
String
train
func (v *Ping) String() string { if v == nil { return "<nil>" } var fields [1]string i := 0 fields[i] = fmt.Sprintf("Beep: %v", v.Beep) i++ return fmt.Sprintf("Ping{%v}", strings.Join(fields[:i], ", ")) }
go
{ "resource": "" }
q10679
Equals
train
func (v *Ping) Equals(rhs *Ping) bool { if v == nil { return rhs == nil } else if rhs == nil { return false } if !(v.Beep == rhs.Beep) { return false } return true }
go
{ "resource": "" }
q10680
MarshalLogObject
train
func (v *Ping) MarshalLogObject(enc zapcore.ObjectEncoder) (err error) { if v == nil { return nil } enc.AddString("beep", v.Beep) return err }
go
{ "resource": "" }
q10681
GetBeep
train
func (v *Ping) GetBeep() (o string) { if v != nil { o = v.Beep } return }
go
{ "resource": "" }
q10682
String
train
func (v *Pong) String() string { if v == nil { return "<nil>" } var fields [1]string i := 0 fields[i] = fmt.Sprintf("Boop: %v", v.Boop) i++ return fmt.Sprintf("Pong{%v}", strings.Join(fields[:i], ", ")) }
go
{ "resource": "" }
q10683
Equals
train
func (v *Pong) Equals(rhs *Pong) bool { if v == nil { return rhs == nil } else if rhs == nil { return false } if !(v.Boop == rhs.Boop) { return false } return true }
go
{ "resource": "" }
q10684
MarshalLogObject
train
func (v *Pong) MarshalLogObject(enc zapcore.ObjectEncoder) (err error) { if v == nil { return nil } enc.AddString("boop", v.Boop) return err }
go
{ "resource": "" }
q10685
GetBoop
train
func (v *Pong) GetBoop() (o string) { if v != nil { o = v.Boop } return }
go
{ "resource": "" }
q10686
remoteTimeout
train
func remoteTimeout(t crossdock.T, dispatcher *yarpc.Dispatcher) { assert := crossdock.Assert(t) token := random.Bytes(5) _, _, err := rawCall(dispatcher, nil, "handlertimeout/raw", token) if skipOnConnRefused(t, err) { return } if !assert.Error(err, "expected an error") { return } if yarpcerrors.FromError(err).Code() == yarpcerrors.CodeInvalidArgument { t.Skipf("handlertimeout/raw procedure not implemented: %v", err) return } assert.Equal(yarpcerrors.CodeDeadlineExceeded, yarpcerrors.FromError(err).Code(), "is an error with code CodeDeadlineExceeded: %v", err) }
go
{ "resource": "" }
q10687
isAvailable
train
func (p *httpPeer) isAvailable() bool { // If there's no open connection, we probe by connecting. dialer := &net.Dialer{Timeout: p.transport.connTimeout} conn, err := dialer.Dial("tcp", p.addr) if conn != nil { conn.Close() } if conn != nil && err == nil { return true } return false }
go
{ "resource": "" }
q10688
MultiOutbound
train
func MultiOutbound(caller, service string, outbounds transport.Outbounds) transport.ClientConfig { return &transport.OutboundConfig{ CallerName: caller, Outbounds: transport.Outbounds{ ServiceName: service, Unary: outbounds.Unary, Oneway: outbounds.Oneway, }, } }
go
{ "resource": "" }
q10689
Start
train
func Start() { ch, err := tchannel.NewChannel("tchannel-server", &tchannel.ChannelOptions{Logger: tchannel.SimpleLogger}) if err != nil { log.WithFields(tchannel.ErrField(err)).Fatal("Couldn't create new channel.") } if err := register(ch); err != nil { log.WithFields(tchannel.ErrField(err)).Fatal("Couldn't register channel.") } if err := ch.ListenAndServe(hostPort); err != nil { log.WithFields( tchannel.LogField{Key: "hostPort", Value: hostPort}, tchannel.ErrField(err), ).Fatal("Couldn't listen.") } }
go
{ "resource": "" }
q10690
register
train
func register(ch *tchannel.Channel) error { ch.Register(raw.Wrap(echoRawHandler{}), "echo/raw") ch.Register(raw.Wrap(handlerTimeoutRawHandler{}), "handlertimeout/raw") if err := json.Register(ch, json.Handlers{"echo": echoJSONHandler}, onError); err != nil { return err } tserver := thrift.NewServer(ch) tserver.Register(echo.NewTChanEchoServer(&echoThriftHandler{})) tserver.Register(gauntlet_tchannel.NewTChanThriftTestServer(&thriftTestHandler{})) tserver.Register(gauntlet_tchannel.NewTChanSecondServiceServer(&secondServiceHandler{})) return nil }
go
{ "resource": "" }
q10691
Start
train
func (o *Once) Start(f func() error) error { if o.state.CAS(int32(Idle), int32(Starting)) { var err error if f != nil { err = f() } // skip forward to error state if err != nil { o.setError(err) o.state.Store(int32(Errored)) close(o.stoppingCh) close(o.stopCh) } else { o.state.Store(int32(Running)) } close(o.startCh) return err } <-o.startCh return o.loadError() }
go
{ "resource": "" }
q10692
WaitUntilRunning
train
func (o *Once) WaitUntilRunning(ctx context.Context) error { state := State(o.state.Load()) if state == Running { return nil } if state > Running { return yarpcerrors.FailedPreconditionErrorf("could not wait for instance to start running: current state is %q", getStateName(state)) } if _, ok := ctx.Deadline(); !ok { return yarpcerrors.InvalidArgumentErrorf("could not wait for instance to start running: deadline required on request context") } select { case <-o.startCh: state := State(o.state.Load()) if state == Running { return nil } return yarpcerrors.FailedPreconditionErrorf("instance did not enter running state, current state is %q", getStateName(state)) case <-ctx.Done(): return yarpcerrors.FailedPreconditionErrorf("context finished while waiting for instance to start: %s", ctx.Err().Error()) } }
go
{ "resource": "" }
q10693
Stop
train
func (o *Once) Stop(f func() error) error { if o.state.CAS(int32(Idle), int32(Stopped)) { close(o.startCh) close(o.stoppingCh) close(o.stopCh) return nil } <-o.startCh if o.state.CAS(int32(Running), int32(Stopping)) { close(o.stoppingCh) var err error if f != nil { err = f() } if err != nil { o.setError(err) o.state.Store(int32(Errored)) } else { o.state.Store(int32(Stopped)) } close(o.stopCh) return err } <-o.stopCh return o.loadError() }
go
{ "resource": "" }
q10694
createEchoT
train
func createEchoT(encoding string, transport string, t crossdock.T) crossdock.T { if transport == "" { transport = t.Param(params.Transport) } t.Tag("transport", transport) t.Tag("encoding", encoding) t.Tag("server", t.Param(params.Server)) return t }
go
{ "resource": "" }
q10695
NewInbound
train
func (t *Transport) NewInbound(listener net.Listener, options ...InboundOption) *Inbound { return newInbound(t, listener, options...) }
go
{ "resource": "" }
q10696
NewOutbound
train
func (t *Transport) NewOutbound(peerChooser peer.Chooser, options ...OutboundOption) *Outbound { return newOutbound(t, peerChooser, options...) }
go
{ "resource": "" }
q10697
Register
train
func Register(d *yarpc.Dispatcher) { ms := &service{d} d.Register(ms.Procedures()) }
go
{ "resource": "" }
q10698
Procedures
train
func (m *service) Procedures() []transport.Procedure { methods := []struct { Name string Handler interface{} Signature string }{ {"yarpc::procedures", m.procs, `procedures() {"service": "...", "procedures": [{"name": "..."}]}`}, {"yarpc::introspect", m.introspect, `introspect() {...}`}, } var r []transport.Procedure for _, m := range methods { p := json.Procedure(m.Name, m.Handler)[0] p.Signature = m.Signature r = append(r, p) } return r }
go
{ "resource": "" }
q10699
NewOutbound
train
func (t *ChannelTransport) NewOutbound() *ChannelOutbound { return &ChannelOutbound{ once: lifecycle.NewOnce(), channel: t.ch, transport: t, } }
go
{ "resource": "" }