Skip to content
Open
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
12 changes: 12 additions & 0 deletions client/native/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ type Options struct {

// Logger provides a logger which should be used for this client.
Logger *slog.Logger

// RequestTimeout limits the complete lifetime of an ARI REST request.
// The package RequestTimeout value is used when this is not positive.
RequestTimeout time.Duration

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

A far more flexible solution to this problem would instead be to accept a custom http.Client, which would then be able to handle all manner of other types of options.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I agree

}

// ConnectWithContext creates and connects a new Client to Asterisk ARI.
Expand Down Expand Up @@ -143,9 +147,17 @@ func New(opts *Options) *Client {
&slog.HandlerOptions{Level: slog.LevelError}))
}

requestTimeout := opts.RequestTimeout
if requestTimeout <= 0 {
requestTimeout = RequestTimeout
}

return &Client{
appName: opts.Application,
Options: opts,
httpClient: http.Client{
Timeout: requestTimeout,
},
}
}

Expand Down
39 changes: 39 additions & 0 deletions client/native/request_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package native

import (
"net"
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/stretchr/testify/require"
)

func TestRequestStopsAtConfiguredTimeout(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) {
<-request.Context().Done()
}))
defer server.Close()

client := New(&Options{
URL: server.URL,
RequestTimeout: 25 * time.Millisecond,
})

startedAt := time.Now()
err := client.get("/channels", nil)

require.Error(t, err)
require.Less(t, time.Since(startedAt), 500*time.Millisecond)

var networkError net.Error
require.ErrorAs(t, err, &networkError)
require.True(t, networkError.Timeout())
}

func TestRequestUsesPackageDefaultTimeout(t *testing.T) {
client := New(&Options{})

require.Equal(t, RequestTimeout, client.httpClient.Timeout)
}