2016-09-12 07:09:02 +03:00
|
|
|
package endpoint
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2018-10-11 00:25:40 +03:00
|
|
|
"github.com/tidwall/tile38/internal/hservice"
|
2018-04-19 19:25:39 +03:00
|
|
|
"golang.org/x/net/context"
|
2016-09-12 07:09:02 +03:00
|
|
|
"google.golang.org/grpc"
|
|
|
|
)
|
|
|
|
|
2019-10-30 20:17:59 +03:00
|
|
|
const grpcExpiresAfter = time.Second * 30
|
2016-09-12 07:09:02 +03:00
|
|
|
|
2018-04-19 19:25:39 +03:00
|
|
|
// GRPCConn is an endpoint connection
|
|
|
|
type GRPCConn struct {
|
2016-09-12 07:09:02 +03:00
|
|
|
mu sync.Mutex
|
|
|
|
ep Endpoint
|
|
|
|
ex bool
|
|
|
|
t time.Time
|
|
|
|
conn *grpc.ClientConn
|
|
|
|
sconn hservice.HookServiceClient
|
|
|
|
}
|
|
|
|
|
2018-04-19 19:25:39 +03:00
|
|
|
func newGRPCConn(ep Endpoint) *GRPCConn {
|
|
|
|
return &GRPCConn{
|
2016-09-12 07:09:02 +03:00
|
|
|
ep: ep,
|
|
|
|
t: time.Now(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-19 19:25:39 +03:00
|
|
|
// Expired returns true if the connection has expired
|
|
|
|
func (conn *GRPCConn) Expired() bool {
|
2016-09-12 07:09:02 +03:00
|
|
|
conn.mu.Lock()
|
|
|
|
defer conn.mu.Unlock()
|
|
|
|
if !conn.ex {
|
2021-03-31 18:13:44 +03:00
|
|
|
if time.Since(conn.t) > grpcExpiresAfter {
|
2022-09-25 16:28:17 +03:00
|
|
|
conn.close()
|
2016-09-12 07:09:02 +03:00
|
|
|
conn.ex = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return conn.ex
|
|
|
|
}
|
2022-09-25 16:28:17 +03:00
|
|
|
|
|
|
|
// ExpireNow forces the connection to expire
|
|
|
|
func (conn *GRPCConn) ExpireNow() {
|
|
|
|
conn.mu.Lock()
|
|
|
|
defer conn.mu.Unlock()
|
|
|
|
conn.close()
|
|
|
|
conn.ex = true
|
|
|
|
}
|
|
|
|
|
2018-04-19 19:25:39 +03:00
|
|
|
func (conn *GRPCConn) close() {
|
2016-09-12 07:09:02 +03:00
|
|
|
if conn.conn != nil {
|
|
|
|
conn.conn.Close()
|
|
|
|
conn.conn = nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-19 19:25:39 +03:00
|
|
|
// Send sends a message
|
|
|
|
func (conn *GRPCConn) Send(msg string) error {
|
2016-09-12 07:09:02 +03:00
|
|
|
conn.mu.Lock()
|
|
|
|
defer conn.mu.Unlock()
|
|
|
|
if conn.ex {
|
2017-02-10 15:27:02 +03:00
|
|
|
return errExpired
|
2016-09-12 07:09:02 +03:00
|
|
|
}
|
|
|
|
conn.t = time.Now()
|
|
|
|
if conn.conn == nil {
|
|
|
|
addr := fmt.Sprintf("%s:%d", conn.ep.GRPC.Host, conn.ep.GRPC.Port)
|
|
|
|
var err error
|
|
|
|
conn.conn, err = grpc.Dial(addr, grpc.WithInsecure())
|
|
|
|
if err != nil {
|
|
|
|
conn.close()
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
conn.sconn = hservice.NewHookServiceClient(conn.conn)
|
|
|
|
}
|
2018-04-19 19:25:39 +03:00
|
|
|
r, err := conn.sconn.Send(context.Background(), &hservice.MessageRequest{Value: msg})
|
2016-09-12 07:09:02 +03:00
|
|
|
if err != nil {
|
|
|
|
conn.close()
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if !r.Ok {
|
|
|
|
conn.close()
|
|
|
|
return errors.New("invalid grpc reply")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|