mirror of
https://github.com/aykhans/sarin.git
synced 2026-11-30 20:46:17 +00:00
fix(stop): route all stops through StopController, SIGTERM graceful, second Ctrl+C forces exit
This commit is contained in:
5 files changed
+176
-90
No files matched your search
+13
-14
@@ -4,8 +4,6 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
|
||||||
"syscall"
|
|
||||||
|
|
||||||
"charm.land/lipgloss/v2"
|
"charm.land/lipgloss/v2"
|
||||||
"go.aykhans.me/sarin/internal/config"
|
"go.aykhans.me/sarin/internal/config"
|
||||||
@@ -17,19 +15,22 @@ import (
|
|||||||
func main() {
|
func main() {
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
stopCtrl := sarin.NewStopController(cancel)
|
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()
|
combinedConfig.SetDefaults()
|
||||||
|
|
||||||
if *combinedConfig.ShowConfig {
|
if *combinedConfig.ShowConfig {
|
||||||
if !combinedConfig.Print() {
|
if !combinedConfig.Print(ctx, stopCtrl) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_ = utilsErr.MustHandle(combinedConfig.Validate(),
|
_ = utilsErr.MustHandle(combinedConfig.Validate(ctx),
|
||||||
utilsErr.OnType(func(err types.FieldValidationErrors) error {
|
utilsErr.OnType(func(err types.FieldValidationErrors) error {
|
||||||
for _, fieldErr := range err.Errors {
|
for _, fieldErr := range err.Errors {
|
||||||
if fieldErr.Value == "" {
|
if fieldErr.Value == "" {
|
||||||
@@ -46,6 +47,9 @@ func main() {
|
|||||||
return nil
|
return nil
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
srn, err := sarin.NewSarin(
|
srn, err := sarin.NewSarin(
|
||||||
ctx,
|
ctx,
|
||||||
@@ -58,6 +62,9 @@ func main() {
|
|||||||
*combinedConfig.DryRun, *combinedConfig.LogLevel, *combinedConfig.LogFile,
|
*combinedConfig.DryRun, *combinedConfig.LogLevel, *combinedConfig.LogFile,
|
||||||
combinedConfig.Lua, combinedConfig.Js,
|
combinedConfig.Lua, combinedConfig.Js,
|
||||||
)
|
)
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
_ = utilsErr.MustHandle(err,
|
_ = utilsErr.MustHandle(err,
|
||||||
utilsErr.OnType(func(err types.ProxyDialError) error {
|
utilsErr.OnType(func(err types.ProxyDialError) error {
|
||||||
fmt.Fprint(os.Stderr, lipgloss.Sprintln(config.StyleRed.Render("[PROXY] ")+err.Error()))
|
fmt.Fprint(os.Stderr, lipgloss.Sprintln(config.StyleRed.Render("[PROXY] ")+err.Error()))
|
||||||
@@ -89,11 +96,3 @@ func main() {
|
|||||||
srn.GetResponses().PrintTable()
|
srn.GetResponses().PrintTable()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func listenForTermination(stop func()) {
|
|
||||||
sigChan := make(chan os.Signal, 4)
|
|
||||||
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
|
|
||||||
for range sigChan {
|
|
||||||
stop()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+28
-16
@@ -251,7 +251,8 @@ func (config Config) MarshalYAML() (any, error) {
|
|||||||
return root, nil
|
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)
|
configYAML, err := yaml.Marshal(config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprint(os.Stderr, lipgloss.Sprintln(StyleRed.Render("Error marshaling config to yaml: "+err.Error())))
|
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(
|
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 {
|
if err != nil {
|
||||||
fmt.Fprint(os.Stderr, lipgloss.Sprintln(StyleRed.Render(err.Error())))
|
fmt.Fprint(os.Stderr, lipgloss.Sprintln(StyleRed.Render(err.Error())))
|
||||||
os.Exit(1)
|
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) {
|
func (config *Config) Merge(newConfig *Config) {
|
||||||
@@ -426,7 +430,7 @@ func (config *Config) SetDefaults() {
|
|||||||
// Validate validates the config fields.
|
// Validate validates the config fields.
|
||||||
// It can return the following errors:
|
// It can return the following errors:
|
||||||
// - types.FieldValidationErrors
|
// - types.FieldValidationErrors
|
||||||
func (config Config) Validate() error {
|
func (config Config) Validate(ctx context.Context) error {
|
||||||
validationErrors := make([]types.FieldValidationError, 0)
|
validationErrors := make([]types.FieldValidationError, 0)
|
||||||
|
|
||||||
if len(config.Methods) == 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)
|
// 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()
|
defer scriptCancel()
|
||||||
|
|
||||||
for i, scriptSrc := range config.Lua {
|
for i, scriptSrc := range config.Lua {
|
||||||
@@ -580,8 +584,8 @@ func (config Config) Validate() error {
|
|||||||
)
|
)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// Validate script syntax
|
// Validate script syntax, ignoring fetches aborted by a stop
|
||||||
if err := script.ValidateScript(scriptCtx, scriptSrc, script.EngineTypeLua); err != nil {
|
if err := script.ValidateScript(scriptCtx, scriptSrc, script.EngineTypeLua); err != nil && !errors.Is(err, context.Canceled) {
|
||||||
validationErrors = append(
|
validationErrors = append(
|
||||||
validationErrors,
|
validationErrors,
|
||||||
types.NewFieldValidationError(fmt.Sprintf("Lua[%d]", i), scriptSrc, err),
|
types.NewFieldValidationError(fmt.Sprintf("Lua[%d]", i), scriptSrc, err),
|
||||||
@@ -597,8 +601,8 @@ func (config Config) Validate() error {
|
|||||||
)
|
)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// Validate script syntax
|
// Validate script syntax, ignoring fetches aborted by a stop
|
||||||
if err := script.ValidateScript(scriptCtx, scriptSrc, script.EngineTypeJavaScript); err != nil {
|
if err := script.ValidateScript(scriptCtx, scriptSrc, script.EngineTypeJavaScript); err != nil && !errors.Is(err, context.Canceled) {
|
||||||
validationErrors = append(
|
validationErrors = append(
|
||||||
validationErrors,
|
validationErrors,
|
||||||
types.NewFieldValidationError(fmt.Sprintf("Js[%d]", i), scriptSrc, err),
|
types.NewFieldValidationError(fmt.Sprintf("Js[%d]", i), scriptSrc, err),
|
||||||
@@ -616,7 +620,8 @@ func (config Config) Validate() error {
|
|||||||
return nil
|
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")
|
envParser := NewConfigENVParser("SARIN")
|
||||||
envConfig, err := envParser.Parse()
|
envConfig, err := envParser.Parse()
|
||||||
_ = utilsErr.MustHandle(err,
|
_ = utilsErr.MustHandle(err,
|
||||||
@@ -651,7 +656,10 @@ func ReadAllConfigs() *Config {
|
|||||||
)
|
)
|
||||||
|
|
||||||
for _, configFile := range append(envConfig.Files, cliConf.Files...) {
|
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.
|
// A nested configFile fails under its own name, not the one given on the command line.
|
||||||
path := configFile.Path()
|
path := configFile.Path()
|
||||||
@@ -700,9 +708,9 @@ func ReadAllConfigs() *Config {
|
|||||||
// - types.ConfigFileReadError
|
// - types.ConfigFileReadError
|
||||||
// - types.UnmarshalError
|
// - types.UnmarshalError
|
||||||
// - types.FieldParseErrors
|
// - 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)
|
configFileParser := NewConfigFileParser(configFile)
|
||||||
fileConfig, err := configFileParser.Parse()
|
fileConfig, err := configFileParser.ParseContext(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, types.NewConfigFileError(configFile.Path(), err)
|
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 {
|
for _, c := range fileConfig.Files {
|
||||||
innerFileConfig, err := parseConfigFile(c, maxDepth-1)
|
innerFileConfig, err := parseConfigFile(ctx, c, maxDepth-1)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -817,6 +825,7 @@ type printConfigModel struct {
|
|||||||
statusMsg string
|
statusMsg string
|
||||||
ready bool
|
ready bool
|
||||||
start bool
|
start bool
|
||||||
|
stop func()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m printConfigModel) Init() tea.Cmd { return nil }
|
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) {
|
switch msg := msg.(type) {
|
||||||
case tea.KeyPressMsg:
|
case tea.KeyPressMsg:
|
||||||
switch msg.String() {
|
switch msg.String() {
|
||||||
case "ctrl+c", "esc":
|
case "ctrl+c":
|
||||||
|
m.stop()
|
||||||
|
return m, tea.Quit
|
||||||
|
case "esc":
|
||||||
return m, tea.Quit
|
return m, tea.Quit
|
||||||
case "ctrl+s":
|
case "ctrl+s":
|
||||||
return m.saveContent()
|
return m.saveContent()
|
||||||
|
|||||||
@@ -35,7 +35,13 @@ func NewConfigFileParser(configFile types.ConfigFile) *ConfigFileParser {
|
|||||||
// - types.UnmarshalError
|
// - types.UnmarshalError
|
||||||
// - types.FieldParseErrors
|
// - types.FieldParseErrors
|
||||||
func (parser ConfigFileParser) Parse() (*Config, error) {
|
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()
|
defer cancel()
|
||||||
|
|
||||||
configFileData, err := fetchFile(ctx, parser.configFile.Path())
|
configFileData, err := fetchFile(ctx, parser.configFile.Path())
|
||||||
|
|||||||
+99
-25
@@ -3,39 +3,78 @@ package sarin
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
"os/signal"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
tea "charm.land/bubbletea/v2"
|
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.
|
// StopController is the single place a run is stopped from.
|
||||||
//
|
// The first Stop drains the run, the second exits at once.
|
||||||
// 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.
|
|
||||||
type StopController struct {
|
type StopController struct {
|
||||||
count atomic.Int32
|
count atomic.Int32
|
||||||
cancel func()
|
cancel func()
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
program *tea.Program
|
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 {
|
func NewStopController(cancel func()) *StopController {
|
||||||
return &StopController{cancel: cancel}
|
return &StopController{cancel: cancel}
|
||||||
}
|
}
|
||||||
|
|
||||||
// AttachProgram registers the active bubbletea program so the terminal state
|
// RunProgram runs p so a forced exit can quit it and wait for it.
|
||||||
// can be restored before os.Exit on the forced shutdown path. Pass nil to
|
func (s *StopController) RunProgram(p *tea.Program) (tea.Model, error) {
|
||||||
// detach once the program has finished.
|
var ttyState *term.State
|
||||||
func (s *StopController) AttachProgram(program *tea.Program) {
|
if term.IsTerminal(os.Stdin.Fd()) {
|
||||||
|
ttyState, _ = term.GetState(os.Stdin.Fd())
|
||||||
|
}
|
||||||
|
|
||||||
|
done := make(chan struct{})
|
||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
s.program = program
|
s.program, s.programDone, s.ttyState = p, done, ttyState
|
||||||
s.mu.Unlock()
|
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() {
|
func (s *StopController) Stop() {
|
||||||
@@ -43,13 +82,48 @@ func (s *StopController) Stop() {
|
|||||||
case 1:
|
case 1:
|
||||||
s.cancel()
|
s.cancel()
|
||||||
case 2:
|
case 2:
|
||||||
s.mu.Lock()
|
go s.forceExit()
|
||||||
p := s.program
|
|
||||||
s.mu.Unlock()
|
|
||||||
if p != nil {
|
|
||||||
_ = p.ReleaseTerminal()
|
|
||||||
}
|
|
||||||
fmt.Fprintln(os.Stderr, "killing...")
|
|
||||||
os.Exit(forceExitCode)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
}
|
||||||
+29
-34
@@ -2,6 +2,8 @@ package sarin
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
"slices"
|
"slices"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -68,23 +70,22 @@ func renderLogBox(logs []string) string {
|
|||||||
return logChannelStyle.Render(b.String())
|
return logChannelStyle.Render(b.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
func helpLine(cancelling bool) string {
|
func helpLine(stopping bool) string {
|
||||||
if cancelling {
|
if stopping {
|
||||||
return helpStyle.Render("Stopping... (Ctrl+C again to force)")
|
return helpStyle.Render("Stopping... (Ctrl+C again to force)")
|
||||||
}
|
}
|
||||||
return helpStyle.Render("Press Ctrl+C to quit")
|
return helpStyle.Render("Press Ctrl+C to quit")
|
||||||
}
|
}
|
||||||
|
|
||||||
type progressModel struct {
|
type progressModel struct {
|
||||||
progress progress.Model
|
progress progress.Model
|
||||||
startTime time.Time
|
startTime time.Time
|
||||||
logs []string
|
logs []string
|
||||||
counter *atomic.Uint64
|
counter *atomic.Uint64
|
||||||
maxValue uint64
|
maxValue uint64
|
||||||
showBar bool
|
showBar bool
|
||||||
ctx context.Context //nolint:containedctx
|
ctx context.Context //nolint:containedctx
|
||||||
stop func()
|
stopCtrl *StopController
|
||||||
cancelling bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m progressModel) Init() tea.Cmd {
|
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) {
|
switch msg := msg.(type) {
|
||||||
case tea.KeyPressMsg:
|
case tea.KeyPressMsg:
|
||||||
if msg.String() == "ctrl+c" {
|
if msg.String() == "ctrl+c" {
|
||||||
m.cancelling = true
|
m.stopCtrl.Stop()
|
||||||
m.stop()
|
|
||||||
}
|
}
|
||||||
return m, nil
|
return m, nil
|
||||||
|
|
||||||
@@ -150,7 +150,7 @@ func (m progressModel) View() tea.View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
b.WriteString("\n\n ")
|
b.WriteString("\n\n ")
|
||||||
b.WriteString(helpLine(m.cancelling))
|
b.WriteString(helpLine(m.stopCtrl.Stopping()))
|
||||||
return tea.NewView(b.String())
|
return tea.NewView(b.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -163,15 +163,14 @@ func progressTickCmd() tea.Cmd {
|
|||||||
var infiniteProgressStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#00D4FF"))
|
var infiniteProgressStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#00D4FF"))
|
||||||
|
|
||||||
type infiniteProgressModel struct {
|
type infiniteProgressModel struct {
|
||||||
spinner spinner.Model
|
spinner spinner.Model
|
||||||
startTime time.Time
|
startTime time.Time
|
||||||
counter *atomic.Uint64
|
counter *atomic.Uint64
|
||||||
logs []string
|
logs []string
|
||||||
showBar bool
|
showBar bool
|
||||||
ctx context.Context //nolint:containedctx
|
ctx context.Context //nolint:containedctx
|
||||||
quit bool
|
quit bool
|
||||||
stop func()
|
stopCtrl *StopController
|
||||||
cancelling bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m infiniteProgressModel) Init() tea.Cmd {
|
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) {
|
switch msg := msg.(type) {
|
||||||
case tea.KeyPressMsg:
|
case tea.KeyPressMsg:
|
||||||
if msg.String() == "ctrl+c" {
|
if msg.String() == "ctrl+c" {
|
||||||
m.cancelling = true
|
m.stopCtrl.Stop()
|
||||||
m.stop()
|
|
||||||
}
|
}
|
||||||
return m, nil
|
return m, nil
|
||||||
|
|
||||||
@@ -219,7 +217,7 @@ func (m infiniteProgressModel) View() tea.View {
|
|||||||
if !m.showBar {
|
if !m.showBar {
|
||||||
if !m.quit {
|
if !m.quit {
|
||||||
b.WriteString("\n\n ")
|
b.WriteString("\n\n ")
|
||||||
b.WriteString(helpLine(m.cancelling))
|
b.WriteString(helpLine(m.stopCtrl.Stopping()))
|
||||||
}
|
}
|
||||||
return tea.NewView(b.String())
|
return tea.NewView(b.String())
|
||||||
}
|
}
|
||||||
@@ -240,7 +238,7 @@ func (m infiniteProgressModel) View() tea.View {
|
|||||||
b.WriteString(" ")
|
b.WriteString(" ")
|
||||||
b.WriteString(time.Since(m.startTime).Round(time.Second / 10).String())
|
b.WriteString(time.Since(m.startTime).Round(time.Second / 10).String())
|
||||||
b.WriteString("\n\n ")
|
b.WriteString("\n\n ")
|
||||||
b.WriteString(helpLine(m.cancelling))
|
b.WriteString(helpLine(m.stopCtrl.Stopping()))
|
||||||
}
|
}
|
||||||
return tea.NewView(b.String())
|
return tea.NewView(b.String())
|
||||||
}
|
}
|
||||||
@@ -267,7 +265,7 @@ func (s sarin) streamProgress(
|
|||||||
maxValue: total,
|
maxValue: total,
|
||||||
showBar: showBar,
|
showBar: showBar,
|
||||||
ctx: ctx,
|
ctx: ctx,
|
||||||
stop: stopCtrl.Stop,
|
stopCtrl: stopCtrl,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sarin handles SIGINT/SIGTERM itself.
|
// Sarin handles SIGINT/SIGTERM itself.
|
||||||
@@ -297,7 +295,7 @@ func (s sarin) streamProgress(
|
|||||||
logs: make([]string, logBoxLines),
|
logs: make([]string, logBoxLines),
|
||||||
showBar: showBar,
|
showBar: showBar,
|
||||||
ctx: ctx,
|
ctx: ctx,
|
||||||
stop: stopCtrl.Stop,
|
stopCtrl: stopCtrl,
|
||||||
quit: false,
|
quit: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -305,9 +303,6 @@ func (s sarin) streamProgress(
|
|||||||
program = tea.NewProgram(model, tea.WithoutSignalHandler())
|
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
|
// 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.
|
// wait on the terminal. Send only what the box shows, on a fixed cadence.
|
||||||
go func() {
|
go func() {
|
||||||
@@ -340,8 +335,8 @@ func (s sarin) streamProgress(
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
if _, err := program.Run(); err != nil {
|
if _, err := stopCtrl.RunProgram(program); err != nil {
|
||||||
panic(err)
|
fmt.Fprintln(os.Stderr, "progress display: "+err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
done <- struct{}{}
|
done <- struct{}{}
|
||||||
|
|||||||
Reference in new issue
Block a user