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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ task in parallel only after some initial timeout has elapsed:

```go
// An example task that will wait for a random amount of time before returning
task := func(ctx context.Context) (interface{}, error) {
task := func(ctx context.Context) (string, error) {
delay := time.Duration(float64(250*time.Millisecond) * rand.Float64())
select {
case <-time.After(delay):
Expand Down
3 changes: 1 addition & 2 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,13 @@ func Example() {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()

result, err := speculatively.Do(ctx, patience, func(ctx context.Context) (interface{}, error) {
successfulCall, err := speculatively.Do(ctx, patience, func(ctx context.Context) (interface{}, error) {
return expensiveTask.Execute(ctx)
})
if err != nil {
fmt.Printf("unexpected error: %s\n", err)
return
}
successfulCall := result.(int)
fmt.Printf("succeeded on call number %d\n", successfulCall)

// Output:
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module github.com/mccutchen/speculatively

go 1.12
go 1.18
17 changes: 9 additions & 8 deletions speculatively.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,18 @@ import (
)

// Thunk is a computation to be speculatively executed
type Thunk func(context.Context) (interface{}, error)
type Thunk[T any] func(context.Context) (T, error)

// Do speculatively executes a Thunk one or more times in parallel, waiting for
// the given patience duration between subsequent executions.
//
// Note that for Do to respect context cancelations, the given Thunk must
// respect them.
func Do(ctx context.Context, patience time.Duration, thunk Thunk) (interface{}, error) {
func Do[T any](ctx context.Context, patience time.Duration, thunk Thunk[T]) (T, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()

out := make(chan result)
out := make(chan result[T])
go runThunk(ctx, thunk, out)

ticker := time.NewTicker(patience)
Expand All @@ -32,20 +32,21 @@ func Do(ctx context.Context, patience time.Duration, thunk Thunk) (interface{},
case r := <-out:
return r.val, r.err
case <-ctx.Done():
return nil, ctx.Err()
var zero T
return zero, ctx.Err()
case <-ticker.C:
go runThunk(ctx, thunk, out)
}
}
}

type result struct {
val interface{}
type result[T any] struct {
val T
err error
}

func runThunk(ctx context.Context, thunk Thunk, out chan result) {
var r result
func runThunk[T any](ctx context.Context, thunk Thunk[T], out chan result[T]) {
var r result[T]
r.val, r.err = thunk(ctx)
select {
case out <- r:
Expand Down
31 changes: 13 additions & 18 deletions speculatively_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
)

type testThunk struct {
results []result
results []result[int]
delays []time.Duration
count int
mu sync.Mutex
Expand All @@ -22,7 +22,7 @@ func (t *testThunk) callCount() int {
return t.count
}

func (t *testThunk) call(ctx context.Context) (interface{}, error) {
func (t *testThunk) call(ctx context.Context) (int, error) {
t.mu.Lock()
id := t.count
d := t.delays[id%len(t.delays)]
Expand All @@ -34,19 +34,19 @@ func (t *testThunk) call(ctx context.Context) (interface{}, error) {
case <-time.After(d):
return r.val, r.err
case <-ctx.Done():
return nil, ctx.Err()
return 0, ctx.Err()
}
}

func newTestThunk(results []result, delays []time.Duration) *testThunk {
func newTestThunk(results []result[int], delays []time.Duration) *testThunk {
return &testThunk{
results: results,
delays: delays,
}
}

func newSimpleTestThunk(val interface{}, err error, delay time.Duration) *testThunk {
results := []result{
func newSimpleTestThunk(val int, err error, delay time.Duration) *testThunk {
results := []result[int]{
{val: val, err: err},
}
delays := []time.Duration{delay}
Expand All @@ -59,11 +59,10 @@ func TestSingleThunk(t *testing.T) {
thunk := newSimpleTestThunk(1, nil, 5*time.Millisecond)
patience := 20 * time.Millisecond

result, err := Do(context.Background(), patience, thunk.call)
val, err := Do(context.Background(), patience, thunk.call)
if err != nil {
t.Errorf("unexpected error: %s", err)
}
val := result.(int)
if val != 1 {
t.Errorf("expected val = %d, got %d", 1, val)
}
Expand All @@ -82,11 +81,10 @@ func TestSpeculativeThunkStarted(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()

result, err := Do(ctx, patience, thunk.call)
val, err := Do(ctx, patience, thunk.call)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
val := result.(int)
if val != 1 {
t.Errorf("expected val = %d, got %d", 1, val)
}
Expand All @@ -98,7 +96,7 @@ func TestSpeculativeThunkStarted(t *testing.T) {
func TestSpeculativeThunkFinishesFirst(t *testing.T) {
t.Parallel()

results := []result{
results := []result[int]{
{val: 1, err: nil},
{val: 2, err: nil},
}
Expand All @@ -118,11 +116,10 @@ func TestSpeculativeThunkFinishesFirst(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()

result, err := Do(ctx, patience, thunk.call)
val, err := Do(ctx, patience, thunk.call)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
val := result.(int)
if val != expectedValue {
t.Errorf("expected val = %d, got %d", expectedValue, val)
}
Expand All @@ -135,7 +132,7 @@ func TestSpeculativeErrors(t *testing.T) {
t.Run("first task finishes first with error", func(t *testing.T) {
t.Parallel()

results := []result{
results := []result[int]{
{val: 1, err: errors.New("error")},
{val: 2, err: nil},
}
Expand All @@ -162,7 +159,7 @@ func TestSpeculativeErrors(t *testing.T) {
t.Run("first task finishes second with error", func(t *testing.T) {
t.Parallel()

results := []result{
results := []result[int]{
{val: 0, err: errors.New("error")},
{val: 2, err: nil},
}
Expand All @@ -182,12 +179,10 @@ func TestSpeculativeErrors(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()

result, err := Do(ctx, patience, thunk.call)
val, err := Do(ctx, patience, thunk.call)
if err != nil {
t.Fatalf("unexpected error: %q", err)
}

val := result.(int)
if val != expectedVal {
t.Errorf("expected val = %#v, got %#v", expectedVal, val)
}
Expand Down