Skip to content
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
23 changes: 13 additions & 10 deletions cmd/execution/results.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,8 @@ func runResults(cmd *cobra.Command, args []string) error {

if !noWait {
timeout, _ := cmd.Flags().GetInt("timeout")
if err := waitForExecution(client, cmd.ErrOrStderr(), executionID, timeout); err != nil {
if err := WaitForExecution(func() (*models.StatusResponse, error) { return client.QueryStatus(executionID) },
cmd.ErrOrStderr(), executionID, timeout); err != nil {
return err
}
}
Expand Down Expand Up @@ -149,16 +150,18 @@ func handleResultsResponse(cmd *cobra.Command, executionID string, resp *models.
}
}

// waitForExecution polls the execution's status, without downloading rows, until
// it stops running, and fails when it is still running at the timeout. It retries
// a failed status call that may succeed later, with a note on stderr, until the
// timeout; a client error such as an unknown execution ID or a bad API key fails
// at once.
func waitForExecution(client dune.DuneClient, stderr io.Writer, executionID string, timeout int) error {
// WaitForExecution polls an execution's status with status, without downloading
// rows, until it stops running, and fails when it is still running at the timeout.
// It retries a failed status call that may succeed later, with a note on stderr,
// until the timeout; a client error such as an unknown execution ID or a bad API
// key fails at once.
func WaitForExecution(
status func() (*models.StatusResponse, error), stderr io.Writer, executionID string, timeout int,
) error {
deadline := time.Now().Add(time.Duration(timeout) * time.Second)
for {
status, err := client.QueryStatus(executionID)
if err == nil && status.State != "QUERY_STATE_PENDING" && status.State != "QUERY_STATE_EXECUTING" {
st, err := status()
if err == nil && st.State != "QUERY_STATE_PENDING" && st.State != "QUERY_STATE_EXECUTING" {
return nil
}
if err != nil && !retryable(err) {
Expand All @@ -169,7 +172,7 @@ func waitForExecution(client dune.DuneClient, stderr io.Writer, executionID stri
return fmt.Errorf("%w: %w", dune.ErrorRetriesExhausted, err)
}
return fmt.Errorf("execution %s is still %s after %ds; rerun with a longer --timeout or --no-wait",
executionID, strings.TrimPrefix(status.State, "QUERY_STATE_"), timeout)
executionID, strings.TrimPrefix(st.State, "QUERY_STATE_"), timeout)
}
if err != nil {
fmt.Fprintf(stderr, "checking the execution status failed, retrying: %v\n", err)
Expand Down
13 changes: 7 additions & 6 deletions cmd/query/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import (
"errors"
"fmt"
"strconv"
"time"

"github.com/duneanalytics/cli/cmd/execution"
"github.com/duneanalytics/cli/output"
"github.com/duneanalytics/duneapi-client-go/dune"
"github.com/duneanalytics/duneapi-client-go/models"
Expand Down Expand Up @@ -35,14 +35,15 @@ func parsePerformance(cmd *cobra.Command) (string, error) {
}
}

// waitAndDisplay waits up to timeout seconds for the execution to finish, then
// prints its results.
func waitAndDisplay(cmd *cobra.Command, exec dune.Execution, timeout int) error {
maxRetries := timeout / 2
if maxRetries < 1 {
maxRetries = 1
if err := execution.WaitForExecution(exec.GetStatus, cmd.ErrOrStderr(), exec.GetID(), timeout); err != nil {
return err
}
resp, err := exec.WaitGetResults(2*time.Second, maxRetries)
resp, err := exec.GetResults()
if err != nil {
return err
return fmt.Errorf("fetching results of execution %s: %w", exec.GetID(), err)
}

if resp.State != "QUERY_STATE_COMPLETED" {
Expand Down
42 changes: 36 additions & 6 deletions cmd/query/run_sql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"testing"
"time"

"github.com/duneanalytics/cli/cmd/execution"
"github.com/duneanalytics/duneapi-client-go/dune"
"github.com/duneanalytics/duneapi-client-go/models"
"github.com/stretchr/testify/assert"
Expand All @@ -18,7 +19,7 @@ func newSQLWaitMock(t *testing.T, resp *models.ResultsResponse, respErr error) *
runSQLFn: func(req models.ExecuteSQLRequest) (dune.Execution, error) {
return &mockExecution{
id: "01ABC",
waitGetResultsFn: func(_ time.Duration, _ int) (*models.ResultsResponse, error) {
getResultsFn: func() (*models.ResultsResponse, error) {
return resp, respErr
},
}, nil
Expand Down Expand Up @@ -76,7 +77,7 @@ func TestRunSQLWithParams(t *testing.T) {
captured = req
return &mockExecution{
id: "01ABC",
waitGetResultsFn: func(_ time.Duration, _ int) (*models.ResultsResponse, error) {
getResultsFn: func() (*models.ResultsResponse, error) {
return testResultsResponse, nil
},
}, nil
Expand All @@ -98,7 +99,7 @@ func TestRunSQLDefaultPerformance(t *testing.T) {
captured = req
return &mockExecution{
id: "01ABC",
waitGetResultsFn: func(_ time.Duration, _ int) (*models.ResultsResponse, error) {
getResultsFn: func() (*models.ResultsResponse, error) {
return testResultsResponse, nil
},
}, nil
Expand All @@ -119,7 +120,7 @@ func TestRunSQLWithPerformance(t *testing.T) {
captured = req
return &mockExecution{
id: "01ABC",
waitGetResultsFn: func(_ time.Duration, _ int) (*models.ResultsResponse, error) {
getResultsFn: func() (*models.ResultsResponse, error) {
return testResultsResponse, nil
},
}, nil
Expand All @@ -140,7 +141,7 @@ func TestRunSQLWithPerformanceSmall(t *testing.T) {
captured = req
return &mockExecution{
id: "01ABC",
waitGetResultsFn: func(_ time.Duration, _ int) (*models.ResultsResponse, error) {
getResultsFn: func() (*models.ResultsResponse, error) {
return testResultsResponse, nil
},
}, nil
Expand Down Expand Up @@ -264,7 +265,7 @@ func TestRunSQLAcceptsLegacyFreePerformance(t *testing.T) {
captured = req
return &mockExecution{
id: "01ABC",
waitGetResultsFn: func(_ time.Duration, _ int) (*models.ResultsResponse, error) {
getResultsFn: func() (*models.ResultsResponse, error) {
return testResultsResponse, nil
},
}, nil
Expand All @@ -285,3 +286,32 @@ func TestRunSQLInvalidParam(t *testing.T) {
require.Error(t, err)
assert.Contains(t, err.Error(), "expected key=value")
}

// A query that keeps running stops the wait at --timeout with an error,
// without downloading any rows.
func TestRunSQLStopsAtTheTimeout(t *testing.T) {
original := execution.PollInterval
execution.PollInterval = 100 * time.Millisecond
t.Cleanup(func() { execution.PollInterval = original })

statusCalls := 0
mock := &mockClient{
runSQLFn: func(models.ExecuteSQLRequest) (dune.Execution, error) {
return &mockExecution{
id: "01ABC",
getStatusFn: func() (*models.StatusResponse, error) {
statusCalls++
return &models.StatusResponse{State: "QUERY_STATE_EXECUTING"}, nil
},
}, nil
},
}

root, _ := newTestRoot(mock)
root.SetArgs([]string{"query", "run-sql", "--sql", "SELECT 1", "--timeout", "1"})
start := time.Now()
err := root.Execute()
assert.EqualError(t, err, "execution 01ABC is still EXECUTING after 1s; rerun with a longer --timeout or --no-wait")
assert.Less(t, time.Since(start), 3*time.Second)
assert.Greater(t, statusCalls, 1)
}
51 changes: 46 additions & 5 deletions cmd/query/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"testing"
"time"

"github.com/duneanalytics/cli/cmd/execution"
"github.com/duneanalytics/duneapi-client-go/dune"
"github.com/duneanalytics/duneapi-client-go/models"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -33,7 +34,7 @@ func newWaitMock(t *testing.T, resp *models.ResultsResponse, respErr error) *moc
runQueryFn: func(req models.ExecuteRequest) (dune.Execution, error) {
return &mockExecution{
id: "01ABC",
waitGetResultsFn: func(_ time.Duration, _ int) (*models.ResultsResponse, error) {
getResultsFn: func() (*models.ResultsResponse, error) {
return resp, respErr
},
}, nil
Expand Down Expand Up @@ -91,7 +92,7 @@ func TestRunWithParams(t *testing.T) {
captured = req
return &mockExecution{
id: "01ABC",
waitGetResultsFn: func(_ time.Duration, _ int) (*models.ResultsResponse, error) {
getResultsFn: func() (*models.ResultsResponse, error) {
return testResultsResponse, nil
},
}, nil
Expand All @@ -113,7 +114,7 @@ func TestRunDefaultPerformance(t *testing.T) {
captured = req
return &mockExecution{
id: "01ABC",
waitGetResultsFn: func(_ time.Duration, _ int) (*models.ResultsResponse, error) {
getResultsFn: func() (*models.ResultsResponse, error) {
return testResultsResponse, nil
},
}, nil
Expand All @@ -134,7 +135,7 @@ func TestRunWithPerformance(t *testing.T) {
captured = req
return &mockExecution{
id: "01ABC",
waitGetResultsFn: func(_ time.Duration, _ int) (*models.ResultsResponse, error) {
getResultsFn: func() (*models.ResultsResponse, error) {
return testResultsResponse, nil
},
}, nil
Expand Down Expand Up @@ -282,7 +283,7 @@ func TestRunAcceptsLegacyFreePerformance(t *testing.T) {
captured = req
return &mockExecution{
id: "01ABC",
waitGetResultsFn: func(_ time.Duration, _ int) (*models.ResultsResponse, error) {
getResultsFn: func() (*models.ResultsResponse, error) {
return testResultsResponse, nil
},
}, nil
Expand All @@ -295,3 +296,43 @@ func TestRunAcceptsLegacyFreePerformance(t *testing.T) {

assert.Equal(t, "free", captured.Performance)
}

// A query that keeps running stops the wait at --timeout with an error,
// without downloading any rows.
func TestRunStopsAtTheTimeout(t *testing.T) {
original := execution.PollInterval
execution.PollInterval = 100 * time.Millisecond
t.Cleanup(func() { execution.PollInterval = original })

statusCalls := 0
mock := &mockClient{
runQueryFn: func(models.ExecuteRequest) (dune.Execution, error) {
return &mockExecution{
id: "01ABC",
getStatusFn: func() (*models.StatusResponse, error) {
statusCalls++
return &models.StatusResponse{State: "QUERY_STATE_EXECUTING"}, nil
},
}, nil
},
}

root, _ := newTestRoot(mock)
root.SetArgs([]string{"query", "run", "4125432", "--timeout", "1"})
start := time.Now()
err := root.Execute()
assert.EqualError(t, err, "execution 01ABC is still EXECUTING after 1s; rerun with a longer --timeout or --no-wait")
assert.Less(t, time.Since(start), 3*time.Second)
assert.Greater(t, statusCalls, 1)
}

// A failed results download after the query finished names the execution, so
// the user can fetch the results later with dune execution results.
func TestRunResultsErrorNamesTheExecution(t *testing.T) {
mock := newWaitMock(t, nil, errors.New("503 Service Unavailable"))

root, _ := newTestRoot(mock)
root.SetArgs([]string{"query", "run", "4125432"})
err := root.Execute()
assert.EqualError(t, err, "fetching results of execution 01ABC: 503 Service Unavailable")
}
20 changes: 14 additions & 6 deletions cmd/query/testutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package query_test
import (
"bytes"
"context"
"time"

"github.com/duneanalytics/cli/cmd/query"
"github.com/duneanalytics/cli/cmdutil"
Expand All @@ -13,15 +12,24 @@ import (
"github.com/spf13/cobra"
)

// mockExecution implements dune.Execution for testing.
// mockExecution implements dune.Execution for testing. Its status is
// completed unless getStatusFn is set.
type mockExecution struct {
dune.Execution
id string
waitGetResultsFn func(time.Duration, int) (*models.ResultsResponse, error)
id string
getStatusFn func() (*models.StatusResponse, error)
getResultsFn func() (*models.ResultsResponse, error)
}

func (m *mockExecution) WaitGetResults(poll time.Duration, maxRetries int) (*models.ResultsResponse, error) {
return m.waitGetResultsFn(poll, maxRetries)
func (m *mockExecution) GetStatus() (*models.StatusResponse, error) {
if m.getStatusFn == nil {
return &models.StatusResponse{State: "QUERY_STATE_COMPLETED"}, nil
}
return m.getStatusFn()
}

func (m *mockExecution) GetResults() (*models.ResultsResponse, error) {
return m.getResultsFn()
}

func (m *mockExecution) GetID() string { return m.id }
Expand Down
Loading