Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ReadTimeoutHandler and ReadTimeout to connection #10

Merged
merged 3 commits into from
Jun 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@ Following options are supported:

* SendTimeout - sets the timeout for a Send operation
* IdleTime - sets the period of inactivity (no messages sent) after which a ping message will be sent to the server
* ReadTimeout - sets the period of time to wait between reads before calling ReadTimeoutHandler
* PingHandler - called when no message was sent during idle time. It should be safe for concurrent use.
* InboundMessageHandler - called when a message from the server is received or no matching request for the message was found. InboundMessageHandler must be safe to be called concurrenty.
* ReadTimeoutHandler - called when no messages have been received during specified ReadTimeout wait time. It should be safe for concurrent use.
* ConnectionClosedHandler - is called when connection is closed by server or there were errors during network read/write that led to connection closure

If you want to override default options, you can do this when creating instance of a client or setting it separately using `SetOptions(options...)` method.
Expand Down
36 changes: 30 additions & 6 deletions connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,12 @@ type MessageLengthWriter func(w io.Writer, length int) (int, error)
// Connection represents an ISO 8583 Connection. Connection may be used
// by multiple goroutines simultaneously.
type Connection struct {
addr string
Opts Options
conn io.ReadWriteCloser
requestsCh chan request
done chan struct{}
addr string
Opts Options
conn io.ReadWriteCloser
requestsCh chan request
readResponseCh chan []byte
done chan struct{}

// spec that will be used to unpack received messages
spec *iso8583.MessageSpec
Expand Down Expand Up @@ -74,6 +75,7 @@ func New(addr string, spec *iso8583.MessageSpec, mlReader MessageLengthReader, m
addr: addr,
Opts: opts,
requestsCh: make(chan request),
readResponseCh: make(chan []byte),
done: make(chan struct{}),
respMap: make(map[string]response),
spec: spec,
Expand Down Expand Up @@ -137,6 +139,7 @@ func (c *Connection) Connect() error {
func (c *Connection) run() {
go c.writeLoop()
go c.readLoop()
go c.readResponseLoop()
}

func (c *Connection) handleConnectionError(err error) {
Expand Down Expand Up @@ -486,7 +489,28 @@ func (c *Connection) readLoop() {
break
}

go c.handleResponse(rawMessage)
c.readResponseCh <- rawMessage
}

c.handleConnectionError(err)
}

func (c *Connection) readResponseLoop() {
var err error

for err == nil {
for {
select {
case mess := <-c.readResponseCh:
go c.handleResponse(mess)
case <-time.After(c.Opts.ReadTimeout):
if c.Opts.ReadTimeoutHandler != nil {
go c.Opts.ReadTimeoutHandler(c)
}
mhargrove marked this conversation as resolved.
Show resolved Hide resolved
case <-c.done:
return
}
}
}

c.handleConnectionError(err)
Expand Down
41 changes: 41 additions & 0 deletions connection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,47 @@ func TestClient_Send(t *testing.T) {
_, err = c.Send(message)
require.Equal(t, connection.ErrConnectionClosed, err)
})

t.Run("ReadTimeoutHandler called after ReadTimeout elapses", func(t *testing.T) {
server, err := NewTestServer()
require.NoError(t, err)
defer server.Close()

readTimeoutHandler := func(c *connection.Connection) {
// send a ping message on timeout
pingMessage := iso8583.NewMessage(testSpec)
err := pingMessage.Marshal(baseFields{
MTI: field.NewStringValue("0800"),
TestCaseCode: field.NewStringValue(TestCasePingCounter),
STAN: field.NewStringValue(getSTAN()),
})
require.NoError(t, err)

response, err := c.Send(pingMessage)
require.NoError(t, err)

mti, err := response.GetMTI()
require.NoError(t, err)
require.Equal(t, "0810", mti)
}

c, err := connection.New(server.Addr, testSpec, readMessageLength, writeMessageLength,
connection.ReadTimeout(50*time.Millisecond),
connection.ReadTimeoutHandler(readTimeoutHandler),
)
require.NoError(t, err)

err = c.Connect()
require.NoError(t, err)
defer c.Close()

// less than 50 ms timeout, should not have any pings
require.Equal(t, 0, server.ReceivedPings())

time.Sleep(100 * time.Millisecond)
// time elapsed is greater than timeout, expect one ping
require.True(t, server.ReceivedPings() > 0)
})
}

func TestClient_Options(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion makefile
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ ifeq ($(OS),Windows_NT)
else
@wget -O lint-project.sh https://raw.githubusercontent.com/moov-io/infra/master/go/lint-project.sh
@chmod +x ./lint-project.sh
GOTEST_FLAGS="-v" GOLANGCI_LINTERS=gosec COVER_THRESHOLD=80.0 ./lint-project.sh
GOTEST_FLAGS="-v" GOLANGCI_LINTERS=gosec COVER_THRESHOLD=80.0 DISABLE_GITLEAKS="1" ./lint-project.sh
endif

.PHONY: clean
Expand Down
25 changes: 25 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,18 @@ type Options struct {
// message to the server
IdleTime time.Duration

// ReadTimeout is the maximum time between read events before the
// ReadTimeoutHandler is called
ReadTimeout time.Duration
Copy link
Member

@adamdecaf adamdecaf Jun 14, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we need a default value for this, otherwise <-time.After(0*time.Second) would fire endlessly.

See: https://go.dev/play/p/gOlaqNI-UqT

Note: The Go playground hardcodes time to a static value.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This does fire endlessly when ran locally:

when: 2022-06-14 16:38:50.354385 -0500 CDT m=+1.800189243
when: 2022-06-14 16:38:50.354388 -0500 CDT m=+1.800192336
when: 2022-06-14 16:38:50.354392 -0500 CDT m=+1.800196537
when: 2022-06-14 16:38:50.354394 -0500 CDT m=+1.800199192
when: 2022-06-14 16:38:50.354398 -0500 CDT m=+1.800203148
when: 2022-06-14 16:38:50.354401 -0500 CDT m=+1.800205735
when: 2022-06-14 16:38:50.354405 -0500 CDT m=+1.800209760
when: 2022-06-14 16:38:50.354425 -0500 CDT m=+1.800229379
when: 2022-06-14 16:38:50.354427 -0500 CDT m=+1.800231794
when: 2022-06-14 16:38:50.354429 -0500 CDT m=+1.800234150
when: 2022-06-14 16:38:50.354455 -0500 CDT m=+1.800259537
when: 2022-06-14 16:38:50.359297 -0500 CDT m=+1.805102074

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good call

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I set it to 60 seconds, which is longer than the 45 seconds we'll use in our implementation.


// PingHandler is called when no message was sent during idle time
// it should be safe for concurrent use
PingHandler func(c *Connection)

// ReadTimeoutHandler is called when no message has been received within
// the ReadTimeout interval
ReadTimeoutHandler func(c *Connection)

// InboundMessageHandler is called when a message from the server is
// received and no matching request for it was found.
// InboundMessageHandler should be safe for concurrent use. Use it
Expand All @@ -43,6 +51,7 @@ func GetDefaultOptions() Options {
return Options{
SendTimeout: 30 * time.Second,
IdleTime: 5 * time.Second,
ReadTimeout: 60 * time.Second,
PingHandler: nil,
TLSConfig: nil,
}
Expand All @@ -64,6 +73,22 @@ func SendTimeout(d time.Duration) Option {
}
}

// ReadTimeout sets an ReadTimeout option
func ReadTimeout(d time.Duration) Option {
return func(o *Options) error {
o.ReadTimeout = d
return nil
}
}

// ReadTimeoutHandler sets a ReadTimeoutHandler option
func ReadTimeoutHandler(handler func(c *Connection)) Option {
return func(o *Options) error {
o.ReadTimeoutHandler = handler
return nil
}
}

// PingHandler sets a PingHandler option
func PingHandler(handler func(c *Connection)) Option {
return func(o *Options) error {
Expand Down