From f84644c688de75d700a6393f56fef614723de03e Mon Sep 17 00:00:00 2001 From: Aykhan Shahsuvarov Date: Tue, 20 Oct 2026 13:30:43 +0400 Subject: [PATCH] fix(stop): route all stops through StopController, SIGTERM graceful, second Ctrl+C forces exit --- cmd/cli/main.go | 27 ++++----- internal/config/config.go | 44 +++++++++----- internal/config/file.go | 8 ++- internal/sarin/stop.go | 124 ++++++++++++++++++++++++++++++-------- internal/sarin/tui.go | 63 +++++++++---------- 5 files changed, 176 insertions(+), 90 deletions(-) diff --git a/cmd/cli/main.go b/cmd/cli/main.go index 0f4390d..c62cb0d 100644 --- a/cmd/cli/main.go +++ b/cmd/cli/main.go @@ -4,8 +4,6 @@ import ( "context" "fmt" "os" - "os/signal" - "syscall" "charm.land/lipgloss/v2" "go.aykhans.me/sarin/internal/config" @@ -17,19 +15,22 @@ import ( func main() { ctx, cancel := context.WithCancel(context.Background()) stopCtrl := sarin.NewStopController(cancel) - go listenForTermination(stopCtrl.Stop) + go stopCtrl.ListenSignals() - combinedConfig := config.ReadAllConfigs() + combinedConfig := config.ReadAllConfigs(ctx) + if ctx.Err() != nil { + return + } combinedConfig.SetDefaults() if *combinedConfig.ShowConfig { - if !combinedConfig.Print() { + if !combinedConfig.Print(ctx, stopCtrl) { return } } - _ = utilsErr.MustHandle(combinedConfig.Validate(), + _ = utilsErr.MustHandle(combinedConfig.Validate(ctx), utilsErr.OnType(func(err types.FieldValidationErrors) error { for _, fieldErr := range err.Errors { if fieldErr.Value == "" { @@ -46,6 +47,9 @@ func main() { return nil }), ) + if ctx.Err() != nil { + return + } srn, err := sarin.NewSarin( ctx, @@ -58,6 +62,9 @@ func main() { *combinedConfig.DryRun, *combinedConfig.LogLevel, *combinedConfig.LogFile, combinedConfig.Lua, combinedConfig.Js, ) + if ctx.Err() != nil { + return + } _ = utilsErr.MustHandle(err, utilsErr.OnType(func(err types.ProxyDialError) error { fmt.Fprint(os.Stderr, lipgloss.Sprintln(config.StyleRed.Render("[PROXY] ")+err.Error())) @@ -89,11 +96,3 @@ func main() { srn.GetResponses().PrintTable() } } - -func listenForTermination(stop func()) { - sigChan := make(chan os.Signal, 4) - signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) - for range sigChan { - stop() - } -} diff --git a/internal/config/config.go b/internal/config/config.go index 8406e33..bb80e09 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -251,7 +251,8 @@ func (config Config) MarshalYAML() (any, error) { return root, nil } -func (config Config) Print() bool { +// Print shows the final config and reports whether to start the run. +func (config Config) Print(ctx context.Context, stopCtrl *sarin.StopController) bool { configYAML, err := yaml.Marshal(config) if err != nil { fmt.Fprint(os.Stderr, lipgloss.Sprintln(StyleRed.Render("Error marshaling config to yaml: "+err.Error()))) @@ -284,16 +285,19 @@ func (config Config) Print() bool { } p := tea.NewProgram( - printConfigModel{content: strings.Trim(content, "\n"), rawContent: configYAML}, + printConfigModel{content: strings.Trim(content, "\n"), rawContent: configYAML, stop: stopCtrl.Stop}, + tea.WithoutSignalHandler(), ) - m, err := p.Run() + stopQuit := context.AfterFunc(ctx, p.Quit) + m, err := stopCtrl.RunProgram(p) + stopQuit() if err != nil { fmt.Fprint(os.Stderr, lipgloss.Sprintln(StyleRed.Render(err.Error()))) os.Exit(1) } - return m.(printConfigModel).start //nolint:forcetypeassert // m is guaranteed to be of type printConfigModel as it was the only model passed to tea.NewProgram + return m.(printConfigModel).start && ctx.Err() == nil //nolint:forcetypeassert // m is guaranteed to be of type printConfigModel as it was the only model passed to tea.NewProgram } func (config *Config) Merge(newConfig *Config) { @@ -426,7 +430,7 @@ func (config *Config) SetDefaults() { // Validate validates the config fields. // It can return the following errors: // - types.FieldValidationErrors -func (config Config) Validate() error { +func (config Config) Validate(ctx context.Context) error { validationErrors := make([]types.FieldValidationError, 0) if len(config.Methods) == 0 { @@ -569,7 +573,7 @@ func (config Config) Validate() error { } // Create a context with timeout for script validation (loading from URLs) - scriptCtx, scriptCancel := context.WithTimeout(context.Background(), 30*time.Second) + scriptCtx, scriptCancel := context.WithTimeout(ctx, 30*time.Second) defer scriptCancel() for i, scriptSrc := range config.Lua { @@ -580,8 +584,8 @@ func (config Config) Validate() error { ) continue } - // Validate script syntax - if err := script.ValidateScript(scriptCtx, scriptSrc, script.EngineTypeLua); err != nil { + // Validate script syntax, ignoring fetches aborted by a stop + if err := script.ValidateScript(scriptCtx, scriptSrc, script.EngineTypeLua); err != nil && !errors.Is(err, context.Canceled) { validationErrors = append( validationErrors, types.NewFieldValidationError(fmt.Sprintf("Lua[%d]", i), scriptSrc, err), @@ -597,8 +601,8 @@ func (config Config) Validate() error { ) continue } - // Validate script syntax - if err := script.ValidateScript(scriptCtx, scriptSrc, script.EngineTypeJavaScript); err != nil { + // Validate script syntax, ignoring fetches aborted by a stop + if err := script.ValidateScript(scriptCtx, scriptSrc, script.EngineTypeJavaScript); err != nil && !errors.Is(err, context.Canceled) { validationErrors = append( validationErrors, types.NewFieldValidationError(fmt.Sprintf("Js[%d]", i), scriptSrc, err), @@ -616,7 +620,8 @@ func (config Config) Validate() error { return nil } -func ReadAllConfigs() *Config { +// ReadAllConfigs reads all config sources and returns early if ctx is cancelled. +func ReadAllConfigs(ctx context.Context) *Config { envParser := NewConfigENVParser("SARIN") envConfig, err := envParser.Parse() _ = utilsErr.MustHandle(err, @@ -651,7 +656,10 @@ func ReadAllConfigs() *Config { ) for _, configFile := range append(envConfig.Files, cliConf.Files...) { - fileConfig, err := parseConfigFile(configFile, 10) + fileConfig, err := parseConfigFile(ctx, configFile, 10) + if err != nil && ctx.Err() != nil { + return envConfig + } // A nested configFile fails under its own name, not the one given on the command line. path := configFile.Path() @@ -700,9 +708,9 @@ func ReadAllConfigs() *Config { // - types.ConfigFileReadError // - types.UnmarshalError // - types.FieldParseErrors -func parseConfigFile(configFile types.ConfigFile, maxDepth int) (*Config, error) { +func parseConfigFile(ctx context.Context, configFile types.ConfigFile, maxDepth int) (*Config, error) { configFileParser := NewConfigFileParser(configFile) - fileConfig, err := configFileParser.Parse() + fileConfig, err := configFileParser.ParseContext(ctx) if err != nil { return nil, types.NewConfigFileError(configFile.Path(), err) } @@ -712,7 +720,7 @@ func parseConfigFile(configFile types.ConfigFile, maxDepth int) (*Config, error) } for _, c := range fileConfig.Files { - innerFileConfig, err := parseConfigFile(c, maxDepth-1) + innerFileConfig, err := parseConfigFile(ctx, c, maxDepth-1) if err != nil { return nil, err } @@ -817,6 +825,7 @@ type printConfigModel struct { statusMsg string ready bool start bool + stop func() } func (m printConfigModel) Init() tea.Cmd { return nil } @@ -827,7 +836,10 @@ func (m printConfigModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.KeyPressMsg: switch msg.String() { - case "ctrl+c", "esc": + case "ctrl+c": + m.stop() + return m, tea.Quit + case "esc": return m, tea.Quit case "ctrl+s": return m.saveContent() diff --git a/internal/config/file.go b/internal/config/file.go index dd3a902..3f87479 100644 --- a/internal/config/file.go +++ b/internal/config/file.go @@ -35,7 +35,13 @@ func NewConfigFileParser(configFile types.ConfigFile) *ConfigFileParser { // - types.UnmarshalError // - types.FieldParseErrors func (parser ConfigFileParser) Parse() (*Config, error) { - ctx, cancel := context.WithTimeout(context.Background(), time.Second*30) + return parser.ParseContext(context.Background()) +} + +// ParseContext is Parse with a parent context for remote fetches. +// It can return the same errors as Parse. +func (parser ConfigFileParser) ParseContext(parent context.Context) (*Config, error) { + ctx, cancel := context.WithTimeout(parent, time.Second*30) defer cancel() configFileData, err := fetchFile(ctx, parser.configFile.Path()) diff --git a/internal/sarin/stop.go b/internal/sarin/stop.go index 3a563a4..628aed3 100644 --- a/internal/sarin/stop.go +++ b/internal/sarin/stop.go @@ -3,39 +3,78 @@ package sarin import ( "fmt" "os" + "os/signal" "sync" "sync/atomic" + "syscall" + "time" tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/term" ) -const forceExitCode = 130 +const ( + forceExitCode = 130 + // forceExitWait bounds the wait for the program to restore the terminal. + forceExitWait = 2 * time.Second + // killingWait bounds the "killing..." write, which a stuck terminal blocks. + killingWait = 100 * time.Millisecond +) -// StopController coordinates a two-stage shutdown. -// -// The first Stop call cancels the supplied context so workers and the job -// loop can drain. The second Stop call restores the terminal (if a bubbletea -// program has been attached) and calls os.Exit(forceExitCode), bypassing any -// in-flight captcha polls, Lua/JS scripts, or HTTP requests that would -// otherwise keep the process alive. +// StopController is the single place a run is stopped from. +// The first Stop drains the run, the second exits at once. type StopController struct { - count atomic.Int32 - cancel func() - mu sync.Mutex - program *tea.Program + count atomic.Int32 + cancel func() + mu sync.Mutex + program *tea.Program + programDone chan struct{} // closed when Run returns + ttyState *term.State // stdin before the program made it raw } func NewStopController(cancel func()) *StopController { return &StopController{cancel: cancel} } -// AttachProgram registers the active bubbletea program so the terminal state -// can be restored before os.Exit on the forced shutdown path. Pass nil to -// detach once the program has finished. -func (s *StopController) AttachProgram(program *tea.Program) { +// RunProgram runs p so a forced exit can quit it and wait for it. +func (s *StopController) RunProgram(p *tea.Program) (tea.Model, error) { + var ttyState *term.State + if term.IsTerminal(os.Stdin.Fd()) { + ttyState, _ = term.GetState(os.Stdin.Fd()) + } + + done := make(chan struct{}) s.mu.Lock() - s.program = program + s.program, s.programDone, s.ttyState = p, done, ttyState s.mu.Unlock() + + defer func() { + s.mu.Lock() + s.program, s.programDone, s.ttyState = nil, nil, nil + s.mu.Unlock() + close(done) + }() + + return p.Run() +} + +// ListenSignals routes SIGINT to Stop. SIGTERM comes from programs like timeout, +// which may send it twice, so it only ever stops gracefully. +func (s *StopController) ListenSignals() { + sigChan := make(chan os.Signal, 4) + signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) + for sig := range sigChan { + if sig == syscall.SIGTERM { + s.stopGracefully() + continue + } + s.Stop() + } +} + +// Stopping reports whether a stop has been requested. +func (s *StopController) Stopping() bool { + return s.count.Load() > 0 } func (s *StopController) Stop() { @@ -43,13 +82,48 @@ func (s *StopController) Stop() { case 1: s.cancel() case 2: - s.mu.Lock() - p := s.program - s.mu.Unlock() - if p != nil { - _ = p.ReleaseTerminal() - } - fmt.Fprintln(os.Stderr, "killing...") - os.Exit(forceExitCode) + go s.forceExit() } } + +// stopGracefully starts the graceful stop unless a stop has already started. +func (s *StopController) stopGracefully() { + if s.count.CompareAndSwap(0, 1) { + s.cancel() + } +} + +// forceExit quits the program, waits up to forceExitWait for it, then exits. +func (s *StopController) forceExit() { + s.mu.Lock() + p, programDone, ttyState := s.program, s.programDone, s.ttyState + s.mu.Unlock() + + quit := make(chan struct{}) + go func() { + if p != nil { + p.Quit() + <-programDone + } + close(quit) + }() + + select { + case <-quit: + case <-time.After(forceExitWait): + if ttyState != nil { + _ = term.Restore(os.Stdin.Fd(), ttyState) + } + } + + printed := make(chan struct{}) + go func() { + fmt.Fprintln(os.Stderr, "killing...") + close(printed) + }() + select { + case <-printed: + case <-time.After(killingWait): + } + os.Exit(forceExitCode) +} diff --git a/internal/sarin/tui.go b/internal/sarin/tui.go index 0ad0a51..da7b26f 100644 --- a/internal/sarin/tui.go +++ b/internal/sarin/tui.go @@ -2,6 +2,8 @@ package sarin import ( "context" + "fmt" + "os" "slices" "strconv" "strings" @@ -68,23 +70,22 @@ func renderLogBox(logs []string) string { return logChannelStyle.Render(b.String()) } -func helpLine(cancelling bool) string { - if cancelling { +func helpLine(stopping bool) string { + if stopping { return helpStyle.Render("Stopping... (Ctrl+C again to force)") } return helpStyle.Render("Press Ctrl+C to quit") } type progressModel struct { - progress progress.Model - startTime time.Time - logs []string - counter *atomic.Uint64 - maxValue uint64 - showBar bool - ctx context.Context //nolint:containedctx - stop func() - cancelling bool + progress progress.Model + startTime time.Time + logs []string + counter *atomic.Uint64 + maxValue uint64 + showBar bool + ctx context.Context //nolint:containedctx + stopCtrl *StopController } func (m progressModel) Init() tea.Cmd { @@ -95,8 +96,7 @@ func (m progressModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.KeyPressMsg: if msg.String() == "ctrl+c" { - m.cancelling = true - m.stop() + m.stopCtrl.Stop() } return m, nil @@ -150,7 +150,7 @@ func (m progressModel) View() tea.View { } b.WriteString("\n\n ") - b.WriteString(helpLine(m.cancelling)) + b.WriteString(helpLine(m.stopCtrl.Stopping())) return tea.NewView(b.String()) } @@ -163,15 +163,14 @@ func progressTickCmd() tea.Cmd { var infiniteProgressStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#00D4FF")) type infiniteProgressModel struct { - spinner spinner.Model - startTime time.Time - counter *atomic.Uint64 - logs []string - showBar bool - ctx context.Context //nolint:containedctx - quit bool - stop func() - cancelling bool + spinner spinner.Model + startTime time.Time + counter *atomic.Uint64 + logs []string + showBar bool + ctx context.Context //nolint:containedctx + quit bool + stopCtrl *StopController } func (m infiniteProgressModel) Init() tea.Cmd { @@ -182,8 +181,7 @@ func (m infiniteProgressModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.KeyPressMsg: if msg.String() == "ctrl+c" { - m.cancelling = true - m.stop() + m.stopCtrl.Stop() } return m, nil @@ -219,7 +217,7 @@ func (m infiniteProgressModel) View() tea.View { if !m.showBar { if !m.quit { b.WriteString("\n\n ") - b.WriteString(helpLine(m.cancelling)) + b.WriteString(helpLine(m.stopCtrl.Stopping())) } return tea.NewView(b.String()) } @@ -240,7 +238,7 @@ func (m infiniteProgressModel) View() tea.View { b.WriteString(" ") b.WriteString(time.Since(m.startTime).Round(time.Second / 10).String()) b.WriteString("\n\n ") - b.WriteString(helpLine(m.cancelling)) + b.WriteString(helpLine(m.stopCtrl.Stopping())) } return tea.NewView(b.String()) } @@ -267,7 +265,7 @@ func (s sarin) streamProgress( maxValue: total, showBar: showBar, ctx: ctx, - stop: stopCtrl.Stop, + stopCtrl: stopCtrl, } // Sarin handles SIGINT/SIGTERM itself. @@ -297,7 +295,7 @@ func (s sarin) streamProgress( logs: make([]string, logBoxLines), showBar: showBar, ctx: ctx, - stop: stopCtrl.Stop, + stopCtrl: stopCtrl, quit: false, } @@ -305,9 +303,6 @@ func (s sarin) streamProgress( program = tea.NewProgram(model, tea.WithoutSignalHandler()) } - stopCtrl.AttachProgram(program) - defer stopCtrl.AttachProgram(nil) - // Bubble Tea repaints once per message, so forwarding every log made the run // wait on the terminal. Send only what the box shows, on a fixed cadence. go func() { @@ -340,8 +335,8 @@ func (s sarin) streamProgress( } }() - if _, err := program.Run(); err != nil { - panic(err) + if _, err := stopCtrl.RunProgram(program); err != nil { + fmt.Fprintln(os.Stderr, "progress display: "+err.Error()) } done <- struct{}{}