// DecodeGRPCDeleteSessionsByOwnerTokenRequest is a transport/grpc.DecodeRequestFunc that converts a
// gRPC request to a user-domain request.
485965
func DecodeGRPCDeleteSessionsByOwnerTokenRequest(_ context.Context, request interface{}) (interface{}, error) {
	req := request.(*pb.DeleteSessionsByOwnerTokenRequest)
	return deleteSessionsByOwnerTokenRequest{
		OwnerToken: req.OwnerToken,
	}, nil
}
1171384
func ToGRPC(err error) error {
	if err == nil {
		return nil
	}
	userMessage := trace.UserMessage(err)
	if trace.IsNotFound(err) {
		return grpc.Errorf(codes.NotFound, userMessage)
	}
	if trace.IsAlreadyExists(err) {
		return grpc.Errorf(codes.AlreadyExists, userMessage)
	}
	if trace.IsAccessDenied(err) {
		return grpc.Errorf(codes.PermissionDenied, userMessage)
	}
	if trace.IsCompareFailed(err) {
		return grpc.Errorf(codes.FailedPrecondition, userMessage)
	}
	if trace.IsBadParameter(err) || trace.IsOAuth2(err) {
		return grpc.Errorf(codes.InvalidArgument, userMessage)
	}
	if trace.IsLimitExceeded(err) {
		return grpc.Errorf(codes.ResourceExhausted, userMessage)
	}
	if trace.IsConnectionProblem(err) {
		return grpc.Errorf(codes.Unavailable, userMessage)
	}
	if trace.IsNotImplemented(err) {
		return grpc.Errorf(codes.Unimplemented, userMessage)
	}
	return grpc.Errorf(codes.Unknown, userMessage)
}
554557
func FromGRPC(err error) error {
	if err == nil {
		return nil
	}

	var cls error // divide these into error classes, becomes the cause

	switch code(err) {
	case codes.InvalidArgument:
		cls = ErrInvalidArgument
	case codes.AlreadyExists:
		cls = ErrAlreadyExists
	case codes.NotFound:
		cls = ErrNotFound
	case codes.Unavailable:
		cls = ErrUnavailable
	case codes.FailedPrecondition:
		cls = ErrFailedPrecondition
	case codes.Unimplemented:
		cls = ErrNotImplemented
	default:
		cls = ErrUnknown
	}

	msg := rebaseMessage(cls, err)
	if msg != "" {
		err = errors.Wrap(cls, msg)
	} else {
		err = errors.WithStack(cls)
	}

	return err
}
33914
func (service *Service) DecodeRequest(req *http.Request, v interface{}) error {
	body, contentType := req.Body, req.Header.Get("Content-Type")
	defer body.Close()

	if err := service.Decoder.Decode(v, body, contentType); err != nil {
		return fmt.Errorf("failed to decode request body with content type %#v: %s", contentType, err)
	}

	return nil
}
115507
func DecryptRequest(client io.Writer, r *http.Request, bucket, object string, metadata map[string]string) (io.WriteCloser, error) {
	return DecryptRequestWithSequenceNumber(client, r, bucket, object, 0, metadata)
}
23894
func (f WithoutConversionCodecFactory) DecoderToVersion(serializer runtime.Decoder, _ runtime.GroupVersioner) runtime.Decoder {
	return runtime.WithoutVersionDecoder{
		Decoder: serializer,
	}
}
491489
func (s *secureSession) Decrypt(r io.Reader) (io.Reader, error) {
	var buf bytes.Buffer
	for {
		var length uint16
		if err := binary.Read(r, binary.LittleEndian, &length); err != nil {
			if err == io.EOF {
				break
			}
			return nil, err
		}

		if length > PacketLengthMax {
			return nil, fmt.Errorf("Packet size too big %d", length)
		}

		var b = make([]byte, length)
		if err := binary.Read(r, binary.LittleEndian, &b); err != nil {
			return nil, err
		}

		var mac [16]byte
		if err := binary.Read(r, binary.LittleEndian, &mac); err != nil {
			return nil, err
		}

		var nonce [8]byte
		binary.LittleEndian.PutUint64(nonce[:], s.decryptCount)
		s.decryptCount++

		lengthBytes := make([]byte, 2)
		binary.LittleEndian.PutUint16(lengthBytes, uint16(length))

		decrypted, err := chacha20poly1305.DecryptAndVerify(s.decryptKey[:], nonce[:], b, mac, lengthBytes)

		if err != nil {
			return nil, fmt.Errorf("Data encryption failed %s", err)
		}

		buf.Write(decrypted)

		// Finish when all bytes fit in b
		if length < PacketLengthMax {
			break
		}
	}

	return &buf, nil
}
126886
func statusCodeFromGRPCError(err error) int {
	switch status.Code(err) {
	case codes.InvalidArgument: // code 3
		return http.StatusBadRequest
	case codes.NotFound: // code 5
		return http.StatusNotFound
	case codes.AlreadyExists: // code 6
		return http.StatusConflict
	case codes.PermissionDenied: // code 7
		return http.StatusForbidden
	case codes.FailedPrecondition: // code 9
		return http.StatusBadRequest
	case codes.Unauthenticated: // code 16
		return http.StatusUnauthorized
	case codes.OutOfRange: // code 11
		return http.StatusBadRequest
	case codes.Unimplemented: // code 12
		return http.StatusNotImplemented
	case codes.Unavailable: // code 14
		return http.StatusServiceUnavailable
	default:
		if e, ok := err.(causer); ok {
			return statusCodeFromGRPCError(e.Cause())
		}
		// codes.Canceled(1)
		// codes.Unknown(2)
		// codes.DeadlineExceeded(4)
		// codes.ResourceExhausted(8)
		// codes.Aborted(10)
		// codes.Internal(13)
		// codes.DataLoss(15)
		return http.StatusInternalServerError
	}
}
288959
func (gs *GRPCClient) BroadcastSessionBind(uid string) error {
	if gs.bindingStorage == nil {
		return constants.ErrNoBindingStorageModule
	}
	fid, _ := gs.bindingStorage.GetUserFrontendID(uid, gs.server.Type)
	if fid != "" {
		if c, ok := gs.clientMap.Load(fid); ok {
			msg := &protos.BindMsg{
				Uid: uid,
				Fid: gs.server.ID,
			}
			ctxT, done := context.WithTimeout(context.Background(), gs.reqTimeout)
			defer done()
			_, err := c.(protos.PitayaClient).SessionBindRemote(ctxT, msg)
			return err
		}
	}
	return nil
}
862099
func (r *sessionRepository) DeleteByOwnerToken(ctx context.Context, ownerToken string) ([]sessions.Session, error) {
	conn := r.pool.Get()
	defer conn.Close()

	deleted := []sessions.Session{}
	ownerSessionsKey := ownerSessionsKey(ownerToken)
	sessionKeys, err := redigo.Values(conn.Do("HKEYS", ownerSessionsKey))
	if err != nil {
		return nil, errors.Wrap(err, "could not get the ownerToken index")
	}
	if sessionKeys == nil || len(sessionKeys) == 0 {
		return deleted, nil
	}
	vals, err := redigo.ByteSlices(conn.Do("MGET", sessionKeys...))
	if err != nil {
		return nil, errors.Wrap(err, "could not get the sessions by ownerToken")
	}
	for _, val := range vals {
		session := sessions.Session{}
		if err := json.Unmarshal(val, &session); err != nil {
			return nil, errors.Wrap(err, "found session unmarshalling failed")
		}
		deleted = append(deleted, session)
	}
	if _, err := redigo.Int(conn.Do("DEL", append([]interface{}{ownerSessionsKey}, sessionKeys...)...)); err != nil {
		return nil, errors.Wrap(err, "could not delete the sessions by ownerToken")
	}
	return deleted, nil
}
1010715
func (m *Message) urlEncodedRequest(pToken, rToken, endpoint string) (*http.Request, error) {
	return newURLEncodedRequest("POST", endpoint, m.toMap(pToken, rToken))
}
792360
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)
}
237537
func decodeRequest(in []byte) (*Request, error) {
	request := &Request{}

	if err := json.NewDecoder(bytes.NewReader(in)).Decode(request); err != nil {
		return nil, err
	}

	// @step: validate the node request
	if err := validateNodeRegistrationRequest(request); err != nil {
		return nil, err
	}

	return request, nil
}
1110445
func DecodeHTTPDeleteSessionsByOwnerTokenRequest(ctx context.Context, r *http.Request) (interface{}, error) {
	values, ok := r.URL.Query()["ownerToken"]
	if !ok {
		return nil, kitty.WithErrQueryParam(errors.New("ownerToken parameter is required"), "ownerToken")
	}
	return deleteSessionsByOwnerTokenRequest{
		OwnerToken: values[0],
	}, nil
}
1373572
func MakeDeleteSessionByTokenEndpoint(s Service) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		req := request.(deleteSessionByTokenRequest)
		session, err := s.DeleteSessionByToken(ctx, req.Token)
		return deleteSessionByTokenResponse{
			Session: session,
			Err:     err,
		}, nil
	}
}
101142
func MakeGRPCServer(ctx context.Context, endpoints Endpoints, tracer stdopentracing.Tracer, logger log.Logger) pb.SessionManagementServer {
	opts := []grpctransport.ServerOption{
		grpctransport.ServerErrorLogger(logger),
	}
	return &grpcServer{
		createSession: grpctransport.NewServer(
			ctx,
			endpoints.CreateSessionEndpoint,
			DecodeGRPCCreateSessionRequest,
			EncodeGRPCCreateSessionResponse,
			append(
				opts,
				grpctransport.ServerBefore(kitty.FromGRPCRequest(tracer, "Create session", logger)),
				grpctransport.ServerAfter(kitty.GRPCFinish()),
			)...,
		),
		findSessionByToken: grpctransport.NewServer(
			ctx,
			endpoints.FindSessionByTokenEndpoint,
			DecodeGRPCFindSessionByTokenRequest,
			EncodeGRPCFindSessionByTokenResponse,
			append(
				opts,
				grpctransport.ServerBefore(kitty.FromGRPCRequest(tracer, "Find session by token", logger)),
				grpctransport.ServerAfter(kitty.GRPCFinish()),
			)...,
		),
		deleteSessionByToken: grpctransport.NewServer(
			ctx,
			endpoints.DeleteSessionByTokenEndpoint,
			DecodeGRPCDeleteSessionByTokenRequest,
			EncodeGRPCDeleteSessionByTokenResponse,
			append(
				opts,
				grpctransport.ServerBefore(kitty.FromGRPCRequest(tracer, "Delete session by token", logger)),
				grpctransport.ServerAfter(kitty.GRPCFinish()),
			)...,
		),
		deleteSessionsByOwnerToken: grpctransport.NewServer(
			ctx,
			endpoints.DeleteSessionsByOwnerTokenEndpoint,
			DecodeGRPCDeleteSessionsByOwnerTokenRequest,
			EncodeGRPCDeleteSessionsByOwnerTokenResponse,
			append(
				opts,
				grpctransport.ServerBefore(kitty.FromGRPCRequest(tracer, "Delete sessions by owner token", logger)),
				grpctransport.ServerAfter(kitty.GRPCFinish()),
			)...,
		),
	}
}
41149
func DecodeHTTPDeleteSessionByTokenRequest(ctx context.Context, r *http.Request) (interface{}, error) {
	return deleteSessionByTokenRequest{
		Token: chi.URLParam(r, "token"),
	}, nil
}