Skip to content

Commit

Permalink
Avoid writing to the config file if not necessary
Browse files Browse the repository at this point in the history
Writing to the config file to update the server list has a cost of
about 0.65 seconds on my M1 Mac, making the startup jump from around
0.35 seconds to 1 second. This may be due to writing to a file but also
could be a delay in obtaining the config lock.

Updating the server list does not actually need to be done all the time.
Instead, this commit checks if there is actually any missing servers
by comparing the list of contexts with the list of servers, and only if
there are missing servers will it trigger the update.

This reduces by 65% the execution time for commands that don't access
the backend; this means that shell completion for commands and flags
becomes noticeably more responsive.

Signed-off-by: Marc Khouzam <[email protected]>
  • Loading branch information
marckhouzam committed Oct 4, 2024
1 parent e7127fc commit 40995ae
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion pkg/config/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/pkg/errors"

"github.com/vmware-tanzu/tanzu-plugin-runtime/config"
"github.com/vmware-tanzu/tanzu-plugin-runtime/config/types"
)

// SyncContextsAndServers populate or sync contexts and servers
Expand All @@ -16,7 +17,11 @@ func SyncContextsAndServers() error {
return errors.Wrap(err, "failed to get client config")
}

config.PopulateContexts(cfg)
hasChanged := config.PopulateContexts(cfg)
needsSync := doServersNeedUpdate(cfg)
if !hasChanged && !needsSync {
return nil
}

// Now write the context to the configuration file. This will also create any missing server for its corresponding context
for _, c := range cfg.KnownContexts {
Expand All @@ -36,3 +41,22 @@ func SyncContextsAndServers() error {
}
return nil
}

func doServersNeedUpdate(cfg *types.ClientConfig) bool {
if cfg == nil {
return false
}

for _, c := range cfg.KnownContexts {
if c.ContextType == types.ContextTypeTanzu || cfg.HasServer(c.Name) {

Check failure on line 51 in pkg/config/context.go

View workflow job for this annotation

GitHub Actions / Build

SA1019: cfg.HasServer is deprecated: This API is deprecated. Use HasContext instead. (staticcheck)
// context of type "tanzu" don't get synched
// or context already present in servers; skip
continue
}
// Found a context that is not in the servers. We need to update
// the servers section
return true
}

return false
}

0 comments on commit 40995ae

Please sign in to comment.