2023-02-03 15:22:00 +03:00
|
|
|
package client
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"google.golang.org/grpc"
|
2023-06-13 01:33:53 +03:00
|
|
|
"google.golang.org/protobuf/proto"
|
2023-02-03 15:22:00 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type streamWrapper struct {
|
|
|
|
grpc.ClientStream
|
|
|
|
timeout time.Duration
|
|
|
|
cancel context.CancelFunc
|
|
|
|
}
|
|
|
|
|
2023-06-13 01:33:53 +03:00
|
|
|
func (w streamWrapper) ReadMessage(m proto.Message) error {
|
|
|
|
return w.withTimeout(func() error {
|
|
|
|
return w.ClientStream.RecvMsg(m)
|
2023-02-03 15:22:00 +03:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-06-13 01:33:53 +03:00
|
|
|
func (w streamWrapper) WriteMessage(m proto.Message) error {
|
2023-02-03 15:22:00 +03:00
|
|
|
return w.withTimeout(func() error {
|
2023-06-13 01:33:53 +03:00
|
|
|
return w.ClientStream.SendMsg(m)
|
2023-02-03 15:22:00 +03:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *streamWrapper) Close() error {
|
|
|
|
return w.withTimeout(w.ClientStream.CloseSend)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *streamWrapper) withTimeout(closure func() error) error {
|
|
|
|
ch := make(chan error, 1)
|
|
|
|
go func() {
|
|
|
|
ch <- closure()
|
|
|
|
close(ch)
|
|
|
|
}()
|
|
|
|
|
|
|
|
tt := time.NewTimer(w.timeout)
|
|
|
|
|
|
|
|
select {
|
|
|
|
case err := <-ch:
|
|
|
|
tt.Stop()
|
|
|
|
return err
|
|
|
|
case <-tt.C:
|
|
|
|
w.cancel()
|
|
|
|
return context.DeadlineExceeded
|
|
|
|
}
|
|
|
|
}
|