From 814059a101333887f94ac3200b40b8329d0cb232 Mon Sep 17 00:00:00 2001 From: Burkhard Pauli Date: Wed, 4 Nov 2026 09:46:39 +0100 Subject: [PATCH] perf(cmd): build the command parser once per process execute checked the command table, attached the tree and ran kong.New on every call. That build is almost the whole cost of a run that stops in Validate (12.5 ms without -race, 73 ms with it), and the internal/cmd tests run about 6000 such calls. execute now keeps one idle parser in a one-slot channel and reuses it. Each call sets the writers, the exit function and the version text of its run. A concurrent call that finds the slot empty builds its own parser. Kong's Parse zeroes every flag and positional before it applies the args, but it keeps Value.Set, Active and Flag.Negated, which the required-flag check, the existingfile mapper and the negatable bool read in the next Parse. parserSet.reset clears them before each reuse. make test with -race on 16 cores: 356 s before, 69 s after. --- internal/cmd/root.go | 107 +++++++++++++++++------ internal/cmd/root_test.go | 171 ++++++++++++++++++++++++++++++++++++- internal/cmd/table_test.go | 3 +- 3 files changed, 249 insertions(+), 32 deletions(-) diff --git a/internal/cmd/root.go b/internal/cmd/root.go index dde6b665..3acfa1fc 100644 --- a/internal/cmd/root.go +++ b/internal/cmd/root.go @@ -38,17 +38,67 @@ type CLI struct { // versionFlag replaces kong.VersionFlag, which reads the version from // kong.Vars. The tree passes no kong.Vars: for every flag and argument, // kong.New copies the Vars and interpolates each entry, which slows the -// many parsers the tests build. +// build. The bound pointer lets each execute set the version of its run +// on the reused parser. type versionFlag bool type versionText string -func (versionFlag) BeforeReset(app *kong.Kong, v versionText) error { - _, _ = fmt.Fprintln(app.Stdout, v) +func (versionFlag) BeforeReset(app *kong.Kong, v *versionText) error { + _, _ = fmt.Fprintln(app.Stdout, *v) app.Exit(0) return nil } +// parserSet is a built Kong parser with its command tree. execute keeps one +// idle set, so a process that runs many commands, such as the test suite, +// builds the tree once instead of once per command. +type parserSet struct { + cli CLI + parser *kong.Kong + version versionText +} + +var idleParser = make(chan *parserSet, 1) + +// reset clears what a Parse leaves in the model. Parse zeroes every flag +// and positional of every command before it applies the args (kong v1.16.1 +// context.go Reset), but it keeps Set, Active and Negated, which the +// required-flag check, the existingfile mapper and the negatable bool +// read in the next Parse. +func (p *parserSet) reset() { + _ = kong.Visit(p.parser.Model.Node, func(node kong.Visitable, next kong.Next) error { + switch n := node.(type) { + case *kong.Node: + n.Active = false + case *kong.Flag: + n.Negated = false + case *kong.Value: + n.Set, n.Active = false, false + } + return next(nil) + }) +} + +func newParserSet() (*parserSet, error) { + p := &parserSet{cli: CLI{Plugins: attach(commands)}} + parser, err := kong.New(&p.cli, + kong.Name("gccli"), + kong.Description("Garmin Connect CLI"), + kong.UsageOnError(), + kong.ConfigureHelp(kong.HelpOptions{ + Compact: true, + }), + kong.Help(colorHelpPrinter), + kong.Bind(&p.version), + ) + if err != nil { + return nil, err + } + p.parser = parser + return p, nil +} + var commands = []Node{ authGroup, activitiesGroup, @@ -96,38 +146,39 @@ func Execute(args []string, version, commit, date string) int { } func execute(args []string, version, commit, date string, stdout, stderr io.Writer) int { - versionStr := fmt.Sprintf("gccli %s (%s) built %s", version, commit, date) - - if errs := checkTable(commands); len(errs) > 0 { - for _, err := range errs { - _, _ = fmt.Fprintf(stderr, "gccli: command table: %s\n", err) + // Concurrent calls each build their own set, and the idle slot keeps + // one of them for the next call. + var p *parserSet + select { + case p = <-idleParser: + p.reset() + default: + if errs := checkTable(commands); len(errs) > 0 { + for _, err := range errs { + _, _ = fmt.Fprintf(stderr, "gccli: command table: %s\n", err) + } + return 1 + } + var err error + if p, err = newParserSet(); err != nil { + _, _ = fmt.Fprintf(stderr, "gccli: %s\n", err) + return 1 } - return 1 - } - - cli := CLI{Plugins: attach(commands)} - parser, err := kong.New(&cli, - kong.Name("gccli"), - kong.Description("Garmin Connect CLI"), - kong.UsageOnError(), - kong.Writers(stdout, stderr), - kong.ConfigureHelp(kong.HelpOptions{ - Compact: true, - }), - kong.Help(colorHelpPrinter), - kong.Bind(versionText(versionStr)), - ) - if err != nil { - _, _ = fmt.Fprintf(stderr, "gccli: %s\n", err) - return 1 } + p.version = versionText(fmt.Sprintf("gccli %s (%s) built %s", version, commit, date)) + p.parser.Stdout, p.parser.Stderr = stdout, stderr // Override Exit to avoid os.Exit during --help and --version. - parser.Exit = func(code int) { + p.parser.Exit = func(code int) { panic(exitSignal{code: code}) } - return run(parser, &cli, args, stdout, stderr) + code := run(p.parser, &p.cli, args, stdout, stderr) + select { + case idleParser <- p: + default: + } + return code } func run(parser *kong.Kong, cli *CLI, args []string, stdout, stderr io.Writer) (code int) { diff --git a/internal/cmd/root_test.go b/internal/cmd/root_test.go index 0b41ef03..79905238 100644 --- a/internal/cmd/root_test.go +++ b/internal/cmd/root_test.go @@ -9,11 +9,14 @@ import ( "net/http" "net/http/httptest" "os" + "reflect" "strconv" "strings" "sync" "testing" + "github.com/alecthomas/kong" + "github.com/bpauli/gccli/internal/garminapi" "github.com/bpauli/gccli/internal/units" ) @@ -362,10 +365,27 @@ func TestExecute_JSONModePrintsErrorObject(t *testing.T) { } } -func TestExecuteRejectsBadTable(t *testing.T) { +// swapCommands replaces the command table for the test and drops the idle +// parser, which execute built from the table before the swap. +func swapCommands(t *testing.T, nodes []Node) { + t.Helper() saved := commands - t.Cleanup(func() { commands = saved }) - commands = []Node{Leaf{Name: "nope", Help: "Nope.", Endpoint: "nope.nope", Output: JSON{}}} + drop := func() { + select { + case <-idleParser: + default: + } + } + commands = nodes + drop() + t.Cleanup(func() { + commands = saved + drop() + }) +} + +func TestExecuteRejectsBadTable(t *testing.T) { + swapCommands(t, []Node{Leaf{Name: "nope", Help: "Nope.", Endpoint: "nope.nope", Output: JSON{}}}) var stdout, stderr bytes.Buffer code := execute([]string{"--help"}, "test", "none", "never", &stdout, &stderr) if code != 1 { @@ -425,6 +445,151 @@ func TestExecuteRunsAreIsolated(t *testing.T) { } } +// TestExecuteResetsFlagsBetweenRuns runs three commands in one process on +// the reused parser. The first run gives pointer, list and negated flags, +// the second run leaves them out, so its request must not carry them, and +// the third run gives the bool flag in its positive form, which the negated +// form of the first run must not flip. +func TestExecuteResetsFlagsBetweenRuns(t *testing.T) { + const log = "/periodichealth-service/menstrualcycle/dailylog/2026-10-01" + saved := `{"calendarDate":"2026-10-01","flow":"LIGHT","notes":"x","ovulationDay":true}` + h := newHarness(t, harnessInput{routes: map[string]mockReply{ + "GET " + log: {body: saved}, + "POST " + log: {body: saved}, + }}) + for _, args := range [][]string{ + {"wellness", "menstrual-log", "set", "2026-10-01", "--flow", "heavy", "--symptoms", "acne,cramps", "--no-ovulation", "--notes", "y"}, + {"wellness", "menstrual-log", "set", "2026-10-01", "--moods", "happy"}, + {"wellness", "menstrual-log", "set", "2026-10-01", "--ovulation"}, + } { + if _, stderr, code := h.run(nil, args); code != 0 { + t.Fatalf("%v: exit %d: %s", args, code, stderr) + } + } + reqs := h.requests() + if len(reqs) != 6 { + t.Fatalf("got %d requests, want 6", len(reqs)) + } + body := func(fields string) string { + return "POST " + log + "\n {\n \"calendarDate\": \"2026-10-01\",\n \"flow\": \"LIGHT\",\n" + fields + + " \"notes\": \"x\",\n \"ovulationDay\": true,\n \"reportTimestamp\": \"2026-10-15T09:30:00.000\"\n }" + } + for i, want := range map[int]string{ + 3: body(" \"moods\": [\n \"HAPPY\"\n ],\n"), + 5: body(""), + } { + if got := strings.TrimRight(reqs[i].entry, "\n"); got != want { + t.Errorf("request %d:\n%s\nwant:\n%s", i, got, want) + } + } +} + +// TestExecuteResetsParseChecksBetweenRuns covers the checks that read what +// the Parse before left in the Kong model: a required flag the first run +// gave and the second run leaves out, and a file positional the first run +// gave and the second run points at a missing file. --help stops the first +// run after the trace, before a request. +func TestExecuteResetsParseChecksBetweenRuns(t *testing.T) { + h := newHarness(t, harnessInput{files: map[string]string{"workout.json": "{}"}}) + for _, tt := range []struct { + name string + first, second []string + wantErr string + }{ + { + name: "required flag", + first: []string{"health", "progress", "summary", "--start", "2026-01-01", "--end", "2026-01-02", "--metric", "distance", "--help"}, + second: []string{"health", "progress", "summary", "--start", "2026-01-01", "--end", "2026-01-02"}, + wantErr: "gccli: error: missing flags: --metric=METRIC,...", + }, + { + name: "existing file", + first: []string{"workouts", "upload", "workout.json", "--help"}, + second: []string{"workouts", "upload", "missing.json"}, + wantErr: "/missing.json: no such file or directory", + }, + } { + t.Run(tt.name, func(t *testing.T) { + if _, stderr, code := h.run(nil, tt.first); code != 0 { + t.Fatalf("first run: exit %d: %s", code, stderr) + } + _, stderr, code := h.run(nil, tt.second) + if code != kindUsage.exit { + t.Errorf("second run: exit %d, want %d", code, kindUsage.exit) + } + if !strings.Contains(stderr, tt.wantErr) { + t.Errorf("second run stderr:\n%s\nwant a line %q", stderr, tt.wantErr) + } + }) + } + if reqs := h.requests(); len(reqs) != 0 { + t.Errorf("sent %d requests, want none", len(reqs)) + } +} + +// TestCommandStateIsResetByParse lists every field of the command tree that +// Kong does not reset in Parse: an unexported field or a kong:"-" field. +// execute reuses the command structs, so such a field keeps its value from +// the run before. Each one must be set on every run before Run reads it, or +// never change after attach. Add a field here after you check that. +func TestCommandStateIsResetByParse(t *testing.T) { + known := map[string]bool{ + "cmd.ChallengesAdhocCreateCmd.first": true, + "cmd.ChallengesAdhocCreateCmd.last": true, + "cmd.GroupsLeaderboardCmd.first": true, + "cmd.GroupsLeaderboardCmd.last": true, + "cmd.specLeafG.leaf": true, + } + used := map[string]bool{} + seen := map[reflect.Type]bool{} + var walk func(typ reflect.Type) + walk = func(typ reflect.Type) { + for typ.Kind() == reflect.Pointer { + typ = typ.Elem() + } + if typ.Kind() != reflect.Struct || seen[typ] || typ.PkgPath() != reflect.TypeFor[CLI]().PkgPath() { + return + } + seen[typ] = true + typeName, _, _ := strings.Cut(typ.String(), "[") + for i := range typ.NumField() { + f := typ.Field(i) + name := typeName + "." + f.Name + switch { + case f.Anonymous: + walk(f.Type) + case !f.IsExported(), f.Tag.Get("kong") == "-": + if !known[name] { + t.Errorf("%s is not reset by Parse and is not in the known list", name) + } + used[name] = true + default: + walk(f.Type) + } + } + } + for _, p := range flatten(attach(commands)) { + walk(reflect.TypeOf(p).Elem().Field(0).Type) + } + for name := range known { + if !used[name] { + t.Errorf("%s is in the known list but not in the command tree", name) + } + } +} + +func flatten(plugins kong.Plugins) []any { + var out []any + for _, p := range plugins { + if g, ok := reflect.ValueOf(p).Elem().Field(0).Interface().(group); ok { + out = append(out, flatten(g.Plugins)...) + continue + } + out = append(out, p) + } + return out +} + func TestUnitsEnumListsEveryPreference(t *testing.T) { for _, flag := range newTestParser(t).Model.Flags { if flag.Name == "units" { diff --git a/internal/cmd/table_test.go b/internal/cmd/table_test.go index c2813a7d..2f2432c6 100644 --- a/internal/cmd/table_test.go +++ b/internal/cmd/table_test.go @@ -217,6 +217,7 @@ type handGearUnlink struct { // printed as the binary prints it. func newParserFor(t *testing.T, cli any, stdout, stderr io.Writer) *kong.Kong { t.Helper() + version := versionText("test") parser, err := kong.New(cli, kong.Name("gccli"), kong.Description("Garmin Connect CLI"), @@ -225,7 +226,7 @@ func newParserFor(t *testing.T, cli any, stdout, stderr io.Writer) *kong.Kong { kong.Exit(func(int) {}), kong.ConfigureHelp(kong.HelpOptions{Compact: true}), kong.Help(colorHelpPrinter), - kong.Bind(versionText("test")), + kong.Bind(&version), ) if err != nil { t.Fatalf("kong.New: %v", err)