Propagate cancellation and preserve resumable state
This commit is contained in:
@@ -3,6 +3,8 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"go.maximumdirect.net/commandkit"
|
||||
|
||||
@@ -10,6 +12,11 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
outcome := app.Execute(context.Background(), os.Args[1:], commandkit.Streams{Out: os.Stdout, Err: os.Stderr})
|
||||
os.Exit(outcome.Status)
|
||||
os.Exit(runProcess(os.Args[1:], commandkit.Streams{Out: os.Stdout, Err: os.Stderr}, app.Execute))
|
||||
}
|
||||
|
||||
func runProcess(args []string, streams commandkit.Streams, execute func(context.Context, []string, commandkit.Streams) commandkit.Outcome) int {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
return execute(ctx, args, streams).Status
|
||||
}
|
||||
|
||||
56
cmd/narratio/main_test.go
Normal file
56
cmd/narratio/main_test.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.maximumdirect.net/commandkit"
|
||||
)
|
||||
|
||||
func TestProcessSignalsCancelInvocation(t *testing.T) {
|
||||
if os.Getenv("NARRATIO_TEST_SIGNAL_CHILD") == "1" {
|
||||
os.Exit(runProcess(nil, commandkit.Streams{Out: os.Stdout, Err: os.Stderr}, func(ctx context.Context, _ []string, streams commandkit.Streams) commandkit.Outcome {
|
||||
fmt.Fprintln(streams.Out, "ready")
|
||||
<-ctx.Done()
|
||||
return commandkit.Failure("interrupted").WithCause(ctx.Err())
|
||||
}))
|
||||
}
|
||||
for _, sig := range []os.Signal{os.Interrupt, syscall.SIGTERM} {
|
||||
t.Run(sig.String(), func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
child := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestProcessSignalsCancelInvocation$")
|
||||
child.Env = append(os.Environ(), "NARRATIO_TEST_SIGNAL_CHILD=1")
|
||||
out, err := child.StdoutPipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
child.Stderr = os.Stderr
|
||||
if err := child.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
scanner := bufio.NewScanner(out)
|
||||
if !scanner.Scan() || scanner.Text() != "ready" {
|
||||
_ = child.Process.Kill()
|
||||
_ = child.Wait()
|
||||
t.Fatal("child failed to register its signal context")
|
||||
}
|
||||
if err := child.Process.Signal(sig); err != nil {
|
||||
_ = child.Process.Kill()
|
||||
_ = child.Wait()
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = child.Wait()
|
||||
exit, ok := err.(*exec.ExitError)
|
||||
if !ok || exit.ExitCode() != 1 {
|
||||
t.Fatalf("child result=%v, want operational exit 1", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user