76 lines
1.8 KiB
Go
76 lines
1.8 KiB
Go
package awsserversdk
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
type TaskService struct{ client *Client }
|
|
type TaskListOptions struct {
|
|
Status string
|
|
Limit int
|
|
Offset int
|
|
}
|
|
type WaitOption func(*waitOptions)
|
|
type waitOptions struct{ pollInterval time.Duration }
|
|
|
|
func WithPollInterval(value time.Duration) WaitOption {
|
|
return func(v *waitOptions) {
|
|
if value > 0 {
|
|
v.pollInterval = value
|
|
}
|
|
}
|
|
}
|
|
func (s *TaskService) Get(ctx context.Context, taskID string) (*Task, error) {
|
|
if taskID == "" {
|
|
return nil, errors.New("awsserversdk: empty task ID")
|
|
}
|
|
var result Task
|
|
err := s.client.do(ctx, http.MethodGet, "/tasks/"+escaped(taskID), nil, &result, "")
|
|
return &result, err
|
|
}
|
|
func (s *TaskService) List(ctx context.Context, options TaskListOptions) (*Page[Task], error) {
|
|
values := url.Values{}
|
|
if options.Status != "" {
|
|
values.Set("status", options.Status)
|
|
}
|
|
if options.Limit > 0 {
|
|
values.Set("limit", strconv.Itoa(options.Limit))
|
|
}
|
|
if options.Offset > 0 {
|
|
values.Set("offset", strconv.Itoa(options.Offset))
|
|
}
|
|
path := "/tasks"
|
|
if encoded := values.Encode(); encoded != "" {
|
|
path += "?" + encoded
|
|
}
|
|
var result Page[Task]
|
|
err := s.client.do(ctx, http.MethodGet, path, nil, &result, "")
|
|
return &result, err
|
|
}
|
|
func (s *TaskService) Wait(ctx context.Context, taskID string, options ...WaitOption) (*Task, error) {
|
|
settings := waitOptions{pollInterval: 2 * time.Second}
|
|
for _, option := range options {
|
|
option(&settings)
|
|
}
|
|
for {
|
|
task, err := s.Get(ctx, taskID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
switch task.Status {
|
|
case "succeeded":
|
|
return task, nil
|
|
case "failed", "cancelled", "expired":
|
|
return task, &TaskError{Task: *task}
|
|
}
|
|
if err := sleepContext(ctx, settings.pollInterval); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
}
|