8000 cyclic: make task startup and stop asynchronous by tomrford · Pull Request #87 · tomrford/gocan · GitHub
[go: up one dir, main page]

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
62 changes: 35 additions & 27 deletions cyclic/cyclic.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,15 @@ type Config struct {

// Task repeatedly sends fixed or generated complete raw CAN frames.
//
// A Task sends immediately when started, then retains that schedule's original
// phase. If transmission falls behind, missed occurrences are skipped rather
// than sent as a burst. For fixed frames, Update replaces the complete frame
// atomically; a send observes either the old frame or the new frame.
// A Task attempts its first send asynchronously without an initial delay, then
// retains the schedule's original phase. If transmission falls behind, missed
// occurrences are skipped rather than sent as a burst. For fixed frames, Update
// replaces the complete frame atomically; a send observes either the old frame
// or the new frame.
//
// Any generation, validation, or send error stops the Task. Stop is idempotent
// and waits for any active callback or send to finish. Err reports the terminal
// error, or nil after Stop.
// Any generation, validation, or send error stops the Task, including on the
// first attempt. Stop requests cancellation; Done closes after all callbacks
// and sends finish. Err then reports the terminal error, or nil if Stop ended it.
type Task struct {
bus gocan.Bus
period time.Duration
Expand All @@ -53,21 +54,25 @@ type Task struct {
stopping bool
}

// Start sends frame once, then starts recurring transmission every period.
// It returns only after the first send has been accepted by bus.
// Start starts recurring transmission of frame and returns without waiting for
// the first send. It returns an error only for invalid arguments; transmission
// failures are reported through Task.Done and Task.Err.
func Start(ctx context.Context, bus gocan.Bus, frame gocan.Frame, config Config) (*Task, error) {
return start(ctx, bus, frame, nil, config)
}

// StartFunc calls generate before each send, validates the returned frame, and
// sends it every period. It returns only after the first frame has been generated
// and accepted by bus. A failure before then returns a nil Task and the error.
// sends it every period. It returns without waiting for the first callback or
// send. It returns an error only for invalid arguments; generation, validation,
// and transmission failures are reported through Task.Done and Task.Err.
//
// Calls to generate and Send are serial; missed periods do not call generate.
// The schedule starts before the first call to generate. Callbacks must return
// promptly, since cancellation and Stop cannot interrupt them. Callers must
// synchronise any state shared with the callback. A callback must not call Stop
// on its own Task, since Stop waits for the callback to return.
// synchronise any state shared with the callback, which may run before StartFunc
// returns. A callback may call Stop, but must not wait on its own Task's Done.
// If the callback uses the returned Task, synchronise its publication (for
// example, through a channel) before accessing it.
func StartFunc(ctx context.Context, bus gocan.Bus, generate func() (gocan.Frame, error), config Config) (*Task, error) {
if generate == nil {
return nil, errors.New("cyclic task requires a frame callback")
Expand All @@ -82,6 +87,9 @@ func start(ctx context.Context, bus gocan.Bus, frame gocan.Frame, generate func(
if config.Period <= 0 {
return nil, fmt.Errorf("cyclic task period must be positive: %s", config.Period)
}
if config.TransmitRetryTimeout < 0 {
return nil, errors.New("CAN transmit retry timeout must not be negative")
}
if generate == nil {
if err := frame.Validate(); err != nil {
return nil, err
Expand All @@ -98,16 +106,12 @@ func start(ctx context.Context, bus gocan.Bus, frame gocan.Frame, generate func(
cancel: cancel,
done: make(chan struct{}),
}
anchor := time.Now()
if err := task.send(anchor); err != nil {
cancel(err)
return nil, err
}
go task.run(anchor)
go task.run(time.Now())
return task, nil
}

// Update atomically replaces the complete frame used by later sends.
// It may replace the initial frame before the first send snapshots it.
// It returns an error for a Task created with StartFunc.
func (task *Task) Update(frame gocan.Frame) error {
if err := frame.Validate(); err != nil {
Expand All @@ -130,34 +134,34 @@ func (task *Task) Update(frame gocan.Frame) error {
// The returned value can be passed to a semantic codec, then replaced with
// Update without retaining the frame originally passed to Start.
// For a Task created with StartFunc, Frame returns the last valid generated
// frame, even if its send failed.
// frame, even if its send failed, or the zero frame before one is generated.
func (task *Task) Frame() gocan.Frame {
task.mu.Lock()
defer task.mu.Unlock()
return task.frame
}

// Stop stops recurring transmission and waits for any active callback or send
// to finish. A callback's result is not sent if Stop was requested while it ran.
// A native send already in progress is allowed to reach its definite result
// before Stop returns.
// Stop requests cancellation and returns without waiting for an active callback
// or send. It is idempotent. To wait for completion, receive from Done after Stop.
// A callback's result is not sent if Stop was requested while it ran. A native
// send already in progress finishes with its definite result before Done closes.
func (task *Task) Stop() {
task.mu.Lock()
if !task.stopping {
task.stopping = true
task.cancel(errStopRequested)
}
task.mu.Unlock()
<-task.done
}

// Done is closed when recurring transmission stops.
// Done is closed when the Task has finished all callbacks and sends.
func (task *Task) Done() <-chan struct{} {
return task.done
}

// Err returns the error that stopped the Task. It returns nil before the Task
// stops and when an explicit Stop ended it.
// stops and when an explicit Stop ended it. A nil error before Done closes does
// not imply that any send has succeeded.
func (task *Task) Err() error {
task.mu.Lock()
defer task.mu.Unlock()
Expand All @@ -168,6 +172,10 @@ func (task *Task) run(anchor time.Time) {
var runErr error
defer func() { task.finish(runErr) }()

if runErr = task.send(anchor); runErr != nil {
return
}

timer := time.NewTimer(time.Until(nextDeadline(anchor, task.period, time.Now())))
defer timer.Stop()

Expand Down
149 changes: 78 additions & 71 deletions cyclic/cyclic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"testing"
"testing/synctest"
"time"

"github.com/tomrford/gocan"
Expand Down Expand Up @@ -34,7 +35,10 @@ func TestTaskLifecycle(t *testing.T) {
if err != nil {
t.Fatalf("Start: %v", err)
}
t.Cleanup(task.Stop)
t.Cleanup(func() {
task.Stop()
<-task.Done()
})

key := gocan.FrameKey{
Bus: bus.ID(),
Expand Down Expand Up @@ -70,6 +74,7 @@ func TestTaskLifecycle(t *testing.T) {
}

task.Stop()
<-task.Done()
if err := task.Err(); err != nil {
t.Fatalf("Err after Stop = %v, want nil", err)
}
Expand All @@ -84,79 +89,81 @@ func TestTaskLifecycle(t *testing.T) {
}
}

func TestStopWaitsForSendInProgress(t *testing.T) {
bus := &blockingBus{
sendStarted: make(chan struct{}, 1),
releaseSend: make(chan struct{}),
}
t.Cleanup(func() {
select {
case <-bus.releaseSend:
default:
close(bus.releaseSend)
}
})
frame, err := gocan.NewFrame(0x123, []byte{1}, 0)
if err != nil {
t.Fatalf("NewFrame: %v", err)
func TestStopDuringSend(t *testing.T) {
for name, blockedSend := range map[string]int{"first": 1, "later": 2} {
t.Run(name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
started, release := make(chan struct{}), make(chan struct{})
sends := 0
bus := &callbackBus{send: func(context.Context, gocan.Frame) error {
sends++
if sends == blockedSend {
close(started)
<-release
}
return nil
}}
task, err := cyclic.Start(context.Background(), bus, gocan.Frame{ID: 1}, cyclic.Config{Period: time.Millisecond})
if err != nil {
t.Fatal(err)
}
<-started
task.Stop()
task.Stop()
if err := task.Update(gocan.Frame{ID: 2}); !errors.Is(err, cyclic.ErrStopped) {
t.Fatalf("Update after Stop = %v, want ErrStopped", err)
}
select {
case <-task.Done():
t.Fatal("Done closed while Send was still in progress")
default:
}
close(release)
<-task.Done()
if task.Err() != nil || sends != blockedSend {
t.Fatalf("Err = %v, sends = %d; want nil, %d", task.Err(), sends, blockedSend)
}
})
})
}
task, err := cyclic.Start(context.Background(), bus, frame, cyclic.Config{Period: time.Millisecond})
if err != nil {
t.Fatalf("Start: %v", err)
}

select {
case <-bus.sendStarted:
case <-time.After(time.Second):
t.Fatal("recurring send did not start")
}

stopped := make(chan struct{})
go func() {
task.Stop()
close(stopped)
}()
select {
case <-stopped:
t.Fatal("Stop returned while Send was still in progress")
case <-time.After(10 * time.Millisecond):
}

close(bus.releaseSend)
select {
case <-stopped:
case <-time.After(time.Second):
t.Fatal("Stop did not return after Send completed")
}
if err := task.Err(); err != nil {
t.Fatalf("Err after Stop = %v, want nil", err)
}
}

type blockingBus struct {
sends int
sendStarted chan struct{}
releaseSend chan struct{}
}

func (bus *blockingBus) ID() gocan.BusID { return 1 }

func (bus *blockingBus) Name() string { return "blocking" }

func (bus *blockingBus) Capture() *gocan.Capture { return nil }

func (bus *blockingBus) Send(context.Context, gocan.Frame) error {
bus.sends++
if bus.sends == 1 {
func TestStartValidation(t *testing.T) {
ctx := context.Background()
bus := &callbackBus{send: func(context.Context, gocan.Frame) error {
t.Error("invalid startup sent a frame")
return nil
}}
config := cyclic.Config{Period: time.Second}
for name, start := range map[string]func() (*cyclic.Task, error){
"bus": func() (*cyclic.Task, error) {
return cyclic.Start(ctx, nil, gocan.Frame{}, config)
},
"period": func() (*cyclic.Task, error) {
return cyclic.Start(ctx, bus, gocan.Frame{}, cyclic.Config{})
},
"frame": func() (*cyclic.Task, error) {
return cyclic.Start(ctx, bus, gocan.Frame{ID: gocan.MaxStandardID + 1}, config)
},
"callback": func() (*cyclic.Task, error) {
return cyclic.StartFunc(ctx, bus, nil, config)
},
"retry timeout": func() (*cyclic.Task, error) {
return cyclic.StartFunc(ctx, bus, func() (gocan.Frame, error) {
t.Error("invalid startup called the generator")
return gocan.Frame{}, nil
}, cyclic.Config{Period: time.Second, TransmitRetryTimeout: -time.Second})
},
} {
t.Run(name, func(t *testing.T) {
task, err := start()
if task != nil {
task.Stop()
<-task.Done()
}
if task != nil || err == nil {
t.Fatalf("Start = %v, %v; want nil Task and argument error", task, err)
}
})
}
bus.sendStarted <- struct{}{}
<-bus.releaseSend
return nil
}

func (bus *blockingBus) Done() <-chan struct{} { return nil }

func (bus *blockingBus) Err() error { return nil }

func (bus *blockingBus) Close() error { return nil }
Loading
Loading
0