package mygrpc

import (
	"context"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/peer"
	"net"
)

const (
	DefaultReadBufferSize  = 256 * 1024 // 256kb
	DefaultWriteBufferSize = 256 * 1024

	// DefaultWindowSize 滑动窗口 16mb 手动设置滑动窗口大小, 尝试提升吞吐量, 减少动态计算可能导致的cpu波动
	DefaultWindowSize = 16 * 1024 * 1024
)

const (
	ServicePrefix = "grpc@"
	ExposeHttpTag = "expose-http"
)

const (
	HeaderClientIP    = "grpc-client-ip"
	HeaderServiceName = "grpc-service-name"
)

func ClientIP(ctx context.Context) string {
	// 先从自定义的header获取
	md, ok := metadata.FromIncomingContext(ctx)
	if ok {
		if v := md.Get(HeaderClientIP); len(v) > 0 {
			return v[0]
		}
	}

	p, ok := peer.FromContext(ctx)
	if ok {
		switch v := p.Addr.(type) {
		case *net.TCPAddr:
			return v.IP.String()
		}
	}

	return ""
}
