diff --git a/cmd/execution/results.go b/cmd/execution/results.go index 71bb842..2201f5d 100644 --- a/cmd/execution/results.go +++ b/cmd/execution/results.go @@ -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 } } @@ -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) { @@ -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) diff --git a/cmd/query/helpers.go b/cmd/query/helpers.go index 6c4bde5..73dd0d6 100644 --- a/cmd/query/helpers.go +++ b/cmd/query/helpers.go @@ -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" @@ -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" { diff --git a/cmd/query/run_sql_test.go b/cmd/query/run_sql_test.go index d1428e0..c19cb31 100644 --- a/cmd/query/run_sql_test.go +++ b/cmd/query/run_sql_test.go @@ -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" @@ -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 @@ -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 @@ -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 @@ -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 @@ -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 @@ -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 @@ -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) +} diff --git a/cmd/query/run_test.go b/cmd/query/run_test.go index ad02a53..511a4fa 100644 --- a/cmd/query/run_test.go +++ b/cmd/query/run_test.go @@ -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" @@ -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 @@ -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 @@ -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 @@ -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 @@ -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 @@ -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") +} diff --git a/cmd/query/testutil_test.go b/cmd/query/testutil_test.go index a89200e..1920403 100644 --- a/cmd/query/testutil_test.go +++ b/cmd/query/testutil_test.go @@ -3,7 +3,6 @@ package query_test import ( "bytes" "context" - "time" "github.com/duneanalytics/cli/cmd/query" "github.com/duneanalytics/cli/cmdutil" @@ -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 }