Propagate cancellation and preserve resumable state

This commit is contained in:
2026-11-20 05:53:49 +00:00
parent a6c6f1e4ab
commit c7a5ff316d
21 changed files with 356 additions and 27 deletions

View File

@@ -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
View 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)
}
})
}
}