package pluginsocket
import (
"context"
"os"
"path/filepath"
"sync"
"testing"
"time"
"go.ate.dev/substrate/api/objectstore/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/health"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/status"
)
type slowControl struct {
objectstore.UnimplementedControlProviderServer
delay time.Duration
once sync.Once
started chan struct{}
}
func newSlowControl(delay time.Duration) *slowControl {
return &slowControl{delay: delay, started: make(chan struct{})}
}
func (c *slowControl) CleanupSnapshot(ctx context.Context, _ *objectstore.CleanupSnapshotRequest) (*objectstore.CleanupSnapshotResponse, error) {
c.once.Do(func() { close(c.started) })
select {
case <-time.After(c.delay):
return &objectstore.CleanupSnapshotResponse{}, nil
case <-ctx.Done():
return nil, status.FromContextError(ctx.Err()).Err()
}
}
type sidecar struct {
t *testing.T
path string
control objectstore.ControlProviderServer
mu sync.Mutex
srv *grpc.Server
}
func newSidecar(t *testing.T, control objectstore.ControlProviderServer) *sidecar {
t.Helper()
dir, err := os.MkdirTemp("", "snapplug")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(dir) })
s := &sidecar{t: t, path: filepath.Join(dir, "plugin.sock"), control: control}
t.Cleanup(s.stop)
return s
}
func (s *sidecar) start() {
lis, err := Listen(s.path)
if err != nil {
s.t.Errorf("Listen: %v", err)
return
}
srv := grpc.NewServer()
objectstore.RegisterControlProviderServer(srv, s.control)
healthpb.RegisterHealthServer(srv, health.NewServer())
go srv.Serve(lis)
s.mu.Lock()
s.srv = srv
s.mu.Unlock()
}
func (s *sidecar) stop() {
s.mu.Lock()
srv := s.srv
s.srv = nil
s.mu.Unlock()
if srv != nil {
srv.Stop()
}
}
func (s *sidecar) dialReady(wait time.Duration) (*grpc.ClientConn, objectstore.ControlProviderClient) {
s.t.Helper()
conn, err := Dial(s.path, wait)
if err != nil {
s.t.Fatal(err)
}
s.t.Cleanup(func() { conn.Close() })
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := WaitReady(ctx, conn); err != nil {
s.t.Fatalf("WaitReady = %v", err)
}
return conn, objectstore.NewControlProviderClient(conn)
}
func (s *sidecar) lose(conn *grpc.ClientConn) {
s.t.Helper()
s.stop()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
for conn.GetState() == connectivity.Ready {
if !conn.WaitForStateChange(ctx, connectivity.Ready) {
s.t.Fatal("connection still ready 10s after the plugin stopped")
}
}
}
var cleanupReq = &objectstore.CleanupSnapshotRequest{SnapshotUri: "gs://bucket/root/snap1"}
func TestCallFailsPromptlyAfterPluginLoss(t *testing.T) {
const wait = 300 * time.Millisecond
s := newSidecar(t, newSlowControl(0))
s.start()
conn, client := s.dialReady(wait)
s.lose(conn)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
start := time.Now()
_, err := client.CleanupSnapshot(ctx, cleanupReq)
elapsed := time.Since(start)
if status.Code(err) != codes.Unavailable {
t.Fatalf("CleanupSnapshot after plugin loss = %v, want %s", err, codes.Unavailable)
}
if elapsed > 5*time.Second {
t.Errorf("CleanupSnapshot failed after %s, want about %s, well before the caller's 10s deadline", elapsed, wait)
}
}
func TestCallWaitEndsWithCallerContext(t *testing.T) {
s := newSidecar(t, newSlowControl(0))
s.start()
conn, client := s.dialReady(time.Minute)
s.lose(conn)
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
_, err := client.CleanupSnapshot(ctx, cleanupReq)
if status.Code(err) != codes.DeadlineExceeded {
t.Errorf("CleanupSnapshot = %v, want %s", err, codes.DeadlineExceeded)
}
}
func TestSlowCallOutlastsReadyWait(t *testing.T) {
const wait = 100 * time.Millisecond
s := newSidecar(t, newSlowControl(10*wait))
s.start()
_, client := s.dialReady(wait)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if _, err := client.CleanupSnapshot(ctx, cleanupReq); err != nil {
t.Errorf("CleanupSnapshot on a slow, healthy plugin = %v, want success", err)
}
}
func TestCallRidesThroughPluginRestart(t *testing.T) {
s := newSidecar(t, newSlowControl(0))
s.start()
conn, client := s.dialReady(10 * time.Second)
s.lose(conn)
restarted := make(chan struct{})
go func() {
defer close(restarted)
time.Sleep(time.Second)
s.start()
}()
defer func() { <-restarted }()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if _, err := client.CleanupSnapshot(ctx, cleanupReq); err != nil {
t.Errorf("CleanupSnapshot across a plugin restart = %v, want success", err)
}
}
func TestInFlightCallFailsWhenPluginDies(t *testing.T) {
control := newSlowControl(time.Minute)
s := newSidecar(t, control)
s.start()
_, client := s.dialReady(time.Minute)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
errc := make(chan error, 1)
go func() {
_, err := client.CleanupSnapshot(ctx, cleanupReq)
errc <- err
}()
<-control.started
start := time.Now()
s.stop()
err := <-errc
if status.Code(err) != codes.Unavailable {
t.Fatalf("in-flight CleanupSnapshot = %v, want %s", err, codes.Unavailable)
}
if elapsed := time.Since(start); elapsed > 5*time.Second {
t.Errorf("in-flight CleanupSnapshot failed %s after the plugin died, want promptly", elapsed)
}
}
func TestWaitReadyOutlastsReadyWait(t *testing.T) {
const wait = 100 * time.Millisecond
s := newSidecar(t, newSlowControl(0))
conn, err := Dial(s.path, wait)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
started := make(chan struct{})
go func() {
defer close(started)
time.Sleep(10 * wait)
s.start()
}()
defer func() { <-started }()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := WaitReady(ctx, conn); err != nil {
t.Errorf("WaitReady for a plugin that starts after the ready wait = %v, want success", err)
}
}
func TestWaitReadyEndsWithContext(t *testing.T) {
conn, err := Dial(filepath.Join(t.TempDir(), "missing.sock"), ReadyWait)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
err = WaitReady(ctx, conn)
if status.Code(err) != codes.DeadlineExceeded {
t.Errorf("WaitReady against a missing socket = %v, want %s", err, codes.DeadlineExceeded)
}
}