package net

import (
	"net"
	"syscall"
	"time"

	"golang.org/x/sys/unix"
)

func newDefaultDialer() net.Dialer {
	// From `grpc.WithContextDialer` comment:
	//
	// Note: All supported releases of Go (as of December 2023) override the OS
	// defaults for TCP keepalive time and interval to 15s. To enable TCP keepalive
	// with OS defaults for keepalive time and interval, use a net.Dialer that sets
	// the KeepAlive field to a negative value, and sets the SO_KEEPALIVE socket
	// option to true from the Control field. For a concrete example of how to do
	// this, see internal.NetDialerWithTCPKeepalive().
	//
	// https://github.com/grpc/grpc-go/blob/830135e6c5a351abf75f0c9cfdf978e5df8daeba/dialoptions.go#L432
	//
	// From `internal.NetDialerWithTCPKeepalive` comment:
	//
	// TODO: Once https://github.com/golang/go/issues/62254 lands, and the
	// appropriate Go version becomes less than our least supported Go version, we
	// should look into using the new API to make things more straightforward.
	return net.Dialer{
		KeepAlive: time.Duration(-1),
		Control: func(_, _ string, c syscall.RawConn) error {
			return c.Control(func(fd uintptr) {
				_ = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_KEEPALIVE, 1)
			})
		},
	}
}