// OnewayProcedure builds a Procedure from the given JSON handler. handler must be
// a function with a signature similar to,
//
// 	f(ctx context.Context, body $reqBody) error
//
// Where $reqBody is a map[string]interface{} or pointer to a struct.
432078
func OnewayProcedure(name string, handler interface{}) []transport.Procedure {
	return []transport.Procedure{
		{
			Name: name,
			HandlerSpec: transport.NewOnewayHandlerSpec(
				wrapOnewayHandler(name, handler)),
			Encoding: Encoding,
		},
	}
}
559232
func HandlerProcess(_ *logrus.Entry, _ *CustomFormatter) (interface{}, error) {
	return os.Getpid(), nil
}
571286
func InstallHandlers(r *router.Router, base router.MiddlewareChain) {
	// Pprof native routing structure is not supported by julienschmidt/httprouter
	// since it mixes prefix matches and direct matches. So we'll have to do some
	// manual routing for paths under /debug/pprof :(
	r.GET("/debug/pprof/*path", base, func(c *router.Context) {
		// Validate the token generated through the portal page.
		tok := c.Request.FormValue("tok")
		if tok == "" {
			sendError(c.Writer, "Missing 'tok' query parameter with a pprof token", http.StatusBadRequest)
			return
		}
		switch err := checkToken(c.Context, tok); {
		case transient.Tag.In(err):
			sendError(c.Writer, fmt.Sprintf("Transient error, please retry: %s", err), http.StatusInternalServerError)
			return
		case err != nil:
			sendError(c.Writer, fmt.Sprintf("Bad pprof token: %s", err), http.StatusBadRequest)
			return
		}

		// Manually route. See init() in go/src/net/http/pprof/pprof.go.
		h := pprofRoutes[c.Params.ByName("path")]
		if h == nil {
			h = internal.Index
		}
		h(c.Writer, c.Request)
	})
}
73986
func (c *Client) Unregister(procedure string) error {
	var (
		procedureID ID
		found       bool
	)
	for id, p := range c.procedures {
		if p.name == procedure {
			procedureID = id
			found = true
		}
	}
	if !found {
		return fmt.Errorf("Procedure %s is not registered with this client.", procedure)
	}
	id := NewID()
	c.registerListener(id)
	unregister := &Unregister{
		Request:      id,
		Registration: procedureID,
	}
	if err := c.Send(unregister); err != nil {
		return err
	}

	// wait to receive UNREGISTERED message
	msg, err := c.waitOnListener(id)
	if err != nil {
		return err
	} else if e, ok := msg.(*Error); ok {
		return fmt.Errorf("error unregister to procedure '%v': %v", procedure, e.Error)
	} else if _, ok := msg.(*Unregistered); !ok {
		return fmt.Errorf(formatUnexpectedMessage(msg, UNREGISTERED))
	}
	// register the event handler with this unregistration
	delete(c.procedures, procedureID)
	return nil
}
770018
func (s *Server) handlerWithGlobalMiddlewares(handler httputils.APIFunc) httputils.APIFunc {
	next := handler

	for _, m := range s.middlewares {
		next = m.WrapHandler(next)
	}

	if s.cfg.Logging && logrus.GetLevel() == logrus.DebugLevel {
		next = middleware.DebugRequestMiddleware(next)
	}

	return next
}
91900
func IsUnrecognizedProcedureError(err error) bool {
	return yarpcerrors.FromError(err).Code() == yarpcerrors.CodeUnimplemented
}
2644
func HandlerPath(h interface{}) string {
	v := reflect.ValueOf(h)
	t := v.Type()
	switch t.Kind() {
	case reflect.Func:
		return runtime.FuncForPC(v.Pointer()).Name()
	case reflect.Ptr:
		t = t.Elem()
		fallthrough
	case reflect.Struct:
		return t.PkgPath() + `.` + t.Name()
	}
	return ``
}
103611
func (r Routes) PathForHandler(handler string, params Params) (string, error) {
	route, ok := r.RouteForHandler(handler)
	if !ok {
		return "", fmt.Errorf("No route exists for handler %", handler)
	}
	return route.PathWithParams(params)
}
471548
func newCallBackHandler() (raw.OnewayHandler, <-chan []byte) {
	serverCalledBack := make(chan []byte)
	return func(ctx context.Context, body []byte) error {
		serverCalledBack <- body
		return nil
	}, serverCalledBack
}
200958
func handleRequestForwarding(core *vault.Core, handler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// If we are a performance standby we can handle the request.
		if core.PerfStandby() {
			ns, err := namespace.FromContext(r.Context())
			if err != nil {
				respondError(w, http.StatusBadRequest, err)
				return
			}
			path := ns.TrimmedPath(r.URL.Path[len("/v1/"):])
			switch {
			case !perfStandbyAlwaysForwardPaths.HasPath(path):
				handler.ServeHTTP(w, r)
				return
			case strings.HasPrefix(path, "auth/token/create/"):
				isBatch, err := core.IsBatchTokenCreationRequest(r.Context(), path)
				if err == nil && isBatch {
					handler.ServeHTTP(w, r)
					return
				}
			}
		}

		// Note: in an HA setup, this call will also ensure that connections to
		// the leader are set up, as that happens once the advertised cluster
		// values are read during this function
		isLeader, leaderAddr, _, err := core.Leader()
		if err != nil {
			if err == vault.ErrHANotEnabled {
				// Standalone node, serve request normally
				handler.ServeHTTP(w, r)
				return
			}
			// Some internal error occurred
			respondError(w, http.StatusInternalServerError, err)
			return
		}
		if isLeader {
			// No forwarding needed, we're leader
			handler.ServeHTTP(w, r)
			return
		}
		if leaderAddr == "" {
			respondError(w, http.StatusInternalServerError, fmt.Errorf("local node not active but active cluster node not found"))
			return
		}

		forwardRequest(core, w, r)
		return
	})
}
1272096
func Procedure(name string, handler UnaryHandler) []transport.Procedure {
	return []transport.Procedure{
		{
			Name:        name,
			HandlerSpec: transport.NewUnaryHandlerSpec(rawUnaryHandler{handler}),
		},
	}
}
860920
func NewRequestForwardingHandler(c *Core, fws *http2.Server, perfStandbySlots chan struct{}, perfStandbyRepCluster *replication.Cluster, perfStandbyCache *cache.Cache) (*requestForwardingHandler, error) {
	// Resolve locally to avoid races
	ha := c.ha != nil

	fwRPCServer := grpc.NewServer(
		grpc.KeepaliveParams(keepalive.ServerParameters{
			Time: 2 * cluster.HeartbeatInterval,
		}),
		grpc.MaxRecvMsgSize(math.MaxInt32),
		grpc.MaxSendMsgSize(math.MaxInt32),
	)

	if ha && c.clusterHandler != nil {
		RegisterRequestForwardingServer(fwRPCServer, &forwardedRequestRPCServer{
			core:                  c,
			handler:               c.clusterHandler,
			perfStandbySlots:      perfStandbySlots,
			perfStandbyRepCluster: perfStandbyRepCluster,
			perfStandbyCache:      perfStandbyCache,
		})
	}

	return &requestForwardingHandler{
		fws:         fws,
		fwRPCServer: fwRPCServer,
		ha:          ha,
		logger:      c.logger.Named("request-forward"),
		core:        c,
		stopCh:      make(chan struct{}),
	}, nil
}
853418
func (o *MultiAuthExampleAPI) HandlerFor(method, path string) (http.Handler, bool) {
	if o.handlers == nil {
		return nil, false
	}
	um := strings.ToUpper(method)
	if _, ok := o.handlers[um]; !ok {
		return nil, false
	}
	if path == "/" {
		path = ""
	}
	h, ok := o.handlers[um][path]
	return h, ok
}
537708
func Start() {
	httpTransport := http.NewTransport()
	inbounds := []transport.Inbound{httpTransport.NewInbound(":8084")}

	dispatcher = yarpc.NewDispatcher(yarpc.Config{
		Name:     "oneway-server",
		Inbounds: inbounds,
	})

	// Echo procedures make an RPC back to the caller with the same context,
	// and body over http/raw
	h := &onewayHandler{http.NewTransport()}
	dispatcher.Register(raw.OnewayProcedure("echo/raw", h.EchoRaw))
	dispatcher.Register(json.OnewayProcedure("echo/json", h.EchoJSON))
	dispatcher.Register(onewayserver.New(&thriftHandler{h}))
	dispatcher.Register(crossdockpb.BuildOnewayYARPCProcedures(&protoHandler{h}))

	if err := dispatcher.Start(); err != nil {
		log.Println("oneway server dispatcher failed to load:", err.Error())
	}
}
954268
func (s *Server) processGatewayInfoFromRoute(info *Info, routeSrvID string, route *client) {
	switch info.GatewayCmd {
	case gatewayCmdGossip:
		s.processImplicitGateway(info)
	default:
		s.Errorf("Unknown command %d from server %v", info.GatewayCmd, routeSrvID)
	}
}
1266040
func SetupJSONV1Paths(r *mux.Router, handler http.Handler) {
	SetupJSONByPaths(r, handler, "/datapoint")
	SetupJSONByPaths(r, handler, "/v1/datapoint")
}
247380
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)
}