52 lines
1.7 KiB
Go
52 lines
1.7 KiB
Go
package servicekit
|
|
|
|
import (
|
|
"context"
|
|
"net"
|
|
"time"
|
|
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/keepalive"
|
|
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/telemetry"
|
|
)
|
|
|
|
// maxConcurrentStreams caps the calls one connection holds open at once, so a
|
|
// single client cannot pin unbounded server memory. It is far above what a
|
|
// service's own clients open: a few watches plus in-flight calls.
|
|
const maxConcurrentStreams = 256
|
|
|
|
// ServerLimits bounds what one peer can hold on a service's gRPC server: open
|
|
// streams per connection, the handshake, and a dead peer's streams, which the
|
|
// server's keepalive pings detect and release instead of holding them until
|
|
// the OS gives up on the socket.
|
|
func ServerLimits() []grpc.ServerOption {
|
|
return []grpc.ServerOption{
|
|
telemetry.ServerOption(),
|
|
grpc.MaxConcurrentStreams(maxConcurrentStreams),
|
|
grpc.ConnectionTimeout(10 * time.Second),
|
|
grpc.KeepaliveParams(keepalive.ServerParameters{
|
|
Time: time.Minute,
|
|
Timeout: 20 * time.Second,
|
|
}),
|
|
}
|
|
}
|
|
|
|
// Serve serves server on listener until ctx ends, then drains in-flight calls
|
|
// for up to 10 seconds before cancelling them: a streaming call can stay open
|
|
// indefinitely and would otherwise hold shutdown. A listener failure is
|
|
// returned, so the process exits rather than staying up with nothing serving.
|
|
func Serve(ctx context.Context, server *grpc.Server, listener net.Listener) error {
|
|
serveErr := make(chan error, 1)
|
|
go func() { serveErr <- server.Serve(listener) }()
|
|
select {
|
|
case <-ctx.Done():
|
|
timer := time.AfterFunc(10*time.Second, server.Stop)
|
|
server.GracefulStop()
|
|
timer.Stop()
|
|
return nil
|
|
case err := <-serveErr:
|
|
return err
|
|
}
|
|
}
|