Skip to content

Commit 2330ac1

Browse files
committed
apply suggestion: set the authToken once in the telemetry.Client
1 parent ef07e5c commit 2330ac1

File tree

14 files changed

+68
-67
lines changed

14 files changed

+68
-67
lines changed

cmd/config.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ func newConfigPathCmd(cfg *env.Env, tel *telemetry.Client) *cobra.Command {
2222
return &cobra.Command{
2323
Use: "path",
2424
Short: "Print the configuration file path",
25-
RunE: commandWithTelemetry("config path", tel, func() string { return cfg.AuthToken }, func(cmd *cobra.Command, args []string) error {
25+
RunE: commandWithTelemetry("config path", tel, func(cmd *cobra.Command, args []string) error {
2626
path, err := cmd.Flags().GetString("config")
2727
if err != nil {
2828
return err

cmd/login.go

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,22 +19,20 @@ func newLoginCmd(cfg *env.Env, tel *telemetry.Client, logger log.Logger) *cobra.
1919
Short: "Manage login",
2020
Long: "Manage login and store credentials in system keyring",
2121
PreRunE: initConfig,
22-
RunE: commandWithTelemetry("login", tel, func() string {
23-
tokenStorage, err := auth.NewTokenStorage(cfg.ForceFileKeyring, logger)
24-
if err != nil {
25-
return cfg.AuthToken
26-
}
27-
token, err := tokenStorage.GetAuthToken()
28-
if err != nil {
29-
return cfg.AuthToken
30-
}
31-
return token
32-
}, func(cmd *cobra.Command, args []string) error {
22+
RunE: commandWithTelemetry("login", tel, func(cmd *cobra.Command, args []string) error {
3323
if !isInteractiveMode(cfg) {
3424
return fmt.Errorf("login requires an interactive terminal")
3525
}
3626
platformClient := api.NewPlatformClient(cfg.APIEndpoint, logger)
37-
return ui.RunLogin(cmd.Context(), version.Version(), platformClient, cfg.AuthToken, cfg.ForceFileKeyring, cfg.WebAppURL, logger)
27+
if err := ui.RunLogin(cmd.Context(), version.Version(), platformClient, cfg.AuthToken, cfg.ForceFileKeyring, cfg.WebAppURL, logger); err != nil {
28+
return err
29+
}
30+
if tokenStorage, err := auth.NewTokenStorage(cfg.ForceFileKeyring, logger); err == nil {
31+
if token, err := tokenStorage.GetAuthToken(); err == nil && token != "" {
32+
tel.SetAuthToken(token)
33+
}
34+
}
35+
return nil
3836
}),
3937
}
4038
}

cmd/logout.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ func newLogoutCmd(cfg *env.Env, tel *telemetry.Client, logger log.Logger) *cobra
2323
Use: "logout",
2424
Short: "Remove stored authentication credentials",
2525
PreRunE: initConfig,
26-
RunE: commandWithTelemetry("logout", tel, func() string { return cfg.AuthToken }, func(cmd *cobra.Command, args []string) error {
26+
RunE: commandWithTelemetry("logout", tel, func(cmd *cobra.Command, args []string) error {
2727
platformClient := api.NewPlatformClient(cfg.APIEndpoint, logger)
2828
appConfig, err := config.Get()
2929
if err != nil {

cmd/logs.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ func newLogsCmd(cfg *env.Env, tel *telemetry.Client) *cobra.Command {
1919
Short: "Show emulator logs",
2020
Long: "Show logs from the emulator. Use --follow to stream in real-time.",
2121
PreRunE: initConfig,
22-
RunE: commandWithTelemetry("logs", tel, func() string { return cfg.AuthToken }, func(cmd *cobra.Command, args []string) error {
22+
RunE: commandWithTelemetry("logs", tel, func(cmd *cobra.Command, args []string) error {
2323
follow, err := cmd.Flags().GetBool("follow")
2424
if err != nil {
2525
return err

cmd/root.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ func Execute(ctx context.Context) error {
8585
}
8686
}
8787
cfg.AuthToken = resolvedToken
88+
tel.SetAuthToken(resolvedToken)
8889

8990
root := NewRootCmd(cfg, tel, logger)
9091
root.SilenceErrors = true
@@ -141,7 +142,7 @@ func runStart(ctx context.Context, cmdFlags *pflag.FlagSet, rt runtime.Runtime,
141142
errorMsg = runErr.Error()
142143
}
143144
tel.Emit(ctx, "lstk_command", telemetry.ToMap(telemetry.CommandEvent{
144-
Environment: tel.GetEnvironment(cfg.AuthToken),
145+
Environment: tel.GetEnvironment(),
145146
Parameters: telemetry.CommandParameters{Command: "start", Flags: flags},
146147
Result: telemetry.CommandResult{
147148
DurationMS: time.Since(startTime).Milliseconds(),
@@ -157,7 +158,7 @@ func runStart(ctx context.Context, cmdFlags *pflag.FlagSet, rt runtime.Runtime,
157158
// emitted after every invocation. Use this for commands that do not emit
158159
// lstk_lifecycle events (i.e. everything except start/stop, which manage their
159160
// own telemetry).
160-
func commandWithTelemetry(name string, tel *telemetry.Client, resolveAuthToken func() string, fn func(*cobra.Command, []string) error) func(*cobra.Command, []string) error {
161+
func commandWithTelemetry(name string, tel *telemetry.Client, fn func(*cobra.Command, []string) error) func(*cobra.Command, []string) error {
161162
return func(cmd *cobra.Command, args []string) error {
162163
startTime := time.Now()
163164
runErr := fn(cmd, args)
@@ -174,7 +175,7 @@ func commandWithTelemetry(name string, tel *telemetry.Client, resolveAuthToken f
174175
errorMsg = runErr.Error()
175176
}
176177
tel.Emit(cmd.Context(), "lstk_command", telemetry.ToMap(telemetry.CommandEvent{
177-
Environment: tel.GetEnvironment(resolveAuthToken()),
178+
Environment: tel.GetEnvironment(),
178179
Parameters: telemetry.CommandParameters{Command: name, Flags: flags},
179180
Result: telemetry.CommandResult{
180181
DurationMS: time.Since(startTime).Milliseconds(),

cmd/status.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ func newStatusCmd(cfg *env.Env, tel *telemetry.Client) *cobra.Command {
2222
Short: "Show emulator status and deployed resources",
2323
Long: "Show the status of a running emulator and its deployed resources",
2424
PreRunE: initConfig,
25-
RunE: commandWithTelemetry("status", tel, func() string { return cfg.AuthToken }, func(cmd *cobra.Command, args []string) error {
25+
RunE: commandWithTelemetry("status", tel, func(cmd *cobra.Command, args []string) error {
2626
rt, err := runtime.NewDockerRuntime(cfg.DockerHost)
2727
if err != nil {
2828
return err

cmd/stop.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ func newStopCmd(cfg *env.Env, tel *telemetry.Client) *cobra.Command {
3535

3636
stopOpts := container.StopOptions{
3737
Telemetry: tel,
38-
AuthToken: cfg.AuthToken,
3938
}
4039

4140
var runErr error
@@ -58,7 +57,7 @@ func newStopCmd(cfg *env.Env, tel *telemetry.Client) *cobra.Command {
5857
flags = append(flags, "--"+f.Name)
5958
})
6059
tel.Emit(cmd.Context(), "lstk_command", telemetry.ToMap(telemetry.CommandEvent{
61-
Environment: tel.GetEnvironment(cfg.AuthToken),
60+
Environment: tel.GetEnvironment(),
6261
Parameters: telemetry.CommandParameters{Command: "stop", Flags: flags},
6362
Result: telemetry.CommandResult{
6463
DurationMS: time.Since(startTime).Milliseconds(),

cmd/update.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ func newUpdateCmd(cfg *env.Env, tel *telemetry.Client) *cobra.Command {
1919
Short: "Update lstk to the latest version",
2020
Long: "Check for and apply updates to the lstk CLI. Respects the original installation method (Homebrew, npm, or direct binary).",
2121
PreRunE: initConfig,
22-
RunE: commandWithTelemetry("update", tel, func() string { return cfg.AuthToken }, func(cmd *cobra.Command, args []string) error {
22+
RunE: commandWithTelemetry("update", tel, func(cmd *cobra.Command, args []string) error {
2323
if isInteractiveMode(cfg) {
2424
return ui.RunUpdate(cmd.Context(), checkOnly, cfg.GitHubToken)
2525
}

internal/container/start.go

Lines changed: 24 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -41,33 +41,27 @@ type StartOptions struct {
4141
Telemetry *telemetry.Client
4242
}
4343

44-
// telCtx carries telemetry context for emitting per-container lifecycle events.
45-
type telCtx struct {
46-
tel *telemetry.Client
47-
authToken string
48-
}
49-
50-
func (t telCtx) emitEmulatorStartError(ctx context.Context, c runtime.ContainerConfig, errorCode, errorMsg string) {
51-
if t.tel == nil {
44+
func emitEmulatorStartError(ctx context.Context, tel *telemetry.Client, c runtime.ContainerConfig, errorCode, errorMsg string) {
45+
if tel == nil {
5246
return
5347
}
54-
t.tel.Emit(ctx, "lstk_lifecycle", telemetry.ToMap(telemetry.LifecycleEvent{
48+
tel.Emit(ctx, "lstk_lifecycle", telemetry.ToMap(telemetry.LifecycleEvent{
5549
EventType: telemetry.LifecycleStartError,
56-
Environment: t.tel.GetEnvironment(t.authToken),
50+
Environment: tel.GetEnvironment(),
5751
Emulator: c.EmulatorType,
5852
Image: c.Image,
5953
ErrorCode: errorCode,
6054
ErrorMsg: errorMsg,
6155
}))
6256
}
6357

64-
func (t telCtx) emitEmulatorStartSuccess(ctx context.Context, c runtime.ContainerConfig, containerID string, durationMS int64, info *telemetry.LocalStackInfo) {
65-
if t.tel == nil {
58+
func emitEmulatorStartSuccess(ctx context.Context, tel *telemetry.Client, c runtime.ContainerConfig, containerID string, durationMS int64, info *telemetry.LocalStackInfo) {
59+
if tel == nil {
6660
return
6761
}
68-
t.tel.Emit(ctx, "lstk_lifecycle", telemetry.ToMap(telemetry.LifecycleEvent{
62+
tel.Emit(ctx, "lstk_lifecycle", telemetry.ToMap(telemetry.LifecycleEvent{
6963
EventType: telemetry.LifecycleStartSuccess,
70-
Environment: t.tel.GetEnvironment(t.authToken),
64+
Environment: tel.GetEnvironment(),
7165
Emulator: c.EmulatorType,
7266
Image: c.Image,
7367
ContainerID: containerID,
@@ -94,14 +88,15 @@ func Start(ctx context.Context, rt runtime.Runtime, sink output.Sink, opts Start
9488
return err
9589
}
9690

91+
if opts.Telemetry != nil {
92+
opts.Telemetry.SetAuthToken(token)
93+
}
94+
9795
if hasDuplicateContainerTypes(opts.Containers) {
9896
output.EmitWarning(sink, "Multiple emulators of the same type are defined in your config; this setup is not supported yet")
9997
}
10098

101-
tel := telCtx{
102-
tel: opts.Telemetry,
103-
authToken: token,
104-
}
99+
tel := opts.Telemetry
105100

106101
containers := make([]runtime.ContainerConfig, len(opts.Containers))
107102
for i, c := range opts.Containers {
@@ -232,7 +227,7 @@ func emitPostStartPointers(sink output.Sink, resolvedHost, webAppURL string) {
232227
output.EmitSecondary(sink, tips[rand.IntN(len(tips))])
233228
}
234229

235-
func pullImages(ctx context.Context, rt runtime.Runtime, sink output.Sink, tel telCtx, containers []runtime.ContainerConfig) error {
230+
func pullImages(ctx context.Context, rt runtime.Runtime, sink output.Sink, tel *telemetry.Client, containers []runtime.ContainerConfig) error {
236231
for _, c := range containers {
237232
// Remove any existing stopped container with the same name
238233
if err := rt.Remove(ctx, c.Name); err != nil && !errdefs.IsNotFound(err) {
@@ -253,7 +248,7 @@ func pullImages(ctx context.Context, rt runtime.Runtime, sink output.Sink, tel t
253248
Title: fmt.Sprintf("Failed to pull %s", c.Image),
254249
Summary: err.Error(),
255250
})
256-
tel.emitEmulatorStartError(ctx, c, telemetry.ErrCodeImagePullFailed, err.Error())
251+
emitEmulatorStartError(ctx, tel, c, telemetry.ErrCodeImagePullFailed, err.Error())
257252
return output.NewSilentError(fmt.Errorf("failed to pull image %s: %w", c.Image, err))
258253
}
259254
output.EmitSpinnerStop(sink)
@@ -262,7 +257,7 @@ func pullImages(ctx context.Context, rt runtime.Runtime, sink output.Sink, tel t
262257
return nil
263258
}
264259

265-
func validateLicenses(ctx context.Context, rt runtime.Runtime, sink output.Sink, opts StartOptions, tel telCtx, containers []runtime.ContainerConfig, token string) error {
260+
func validateLicenses(ctx context.Context, rt runtime.Runtime, sink output.Sink, opts StartOptions, tel *telemetry.Client, containers []runtime.ContainerConfig, token string) error {
266261
for _, c := range containers {
267262
if err := validateLicense(ctx, rt, sink, opts, tel, c, token); err != nil {
268263
return err
@@ -271,32 +266,32 @@ func validateLicenses(ctx context.Context, rt runtime.Runtime, sink output.Sink,
271266
return nil
272267
}
273268

274-
func startContainers(ctx context.Context, rt runtime.Runtime, sink output.Sink, tel telCtx, containers []runtime.ContainerConfig) error {
269+
func startContainers(ctx context.Context, rt runtime.Runtime, sink output.Sink, tel *telemetry.Client, containers []runtime.ContainerConfig) error {
275270
for _, c := range containers {
276271
startTime := time.Now()
277272
output.EmitStatus(sink, "starting", c.Name, "")
278273
containerID, err := rt.Start(ctx, c)
279274
if err != nil {
280-
tel.emitEmulatorStartError(ctx, c, telemetry.ErrCodeStartFailed, err.Error())
275+
emitEmulatorStartError(ctx, tel, c, telemetry.ErrCodeStartFailed, err.Error())
281276
return fmt.Errorf("failed to start LocalStack: %w", err)
282277
}
283278

284279
output.EmitStatus(sink, "waiting", c.Name, "")
285280
healthURL := fmt.Sprintf("http://localhost:%s%s", c.Port, c.HealthPath)
286281
if err := awaitStartup(ctx, rt, sink, containerID, "LocalStack", healthURL); err != nil {
287-
tel.emitEmulatorStartError(ctx, c, telemetry.ErrCodeStartFailed, err.Error())
282+
emitEmulatorStartError(ctx, tel, c, telemetry.ErrCodeStartFailed, err.Error())
288283
return err
289284
}
290285

291286
output.EmitStatus(sink, "ready", c.Name, fmt.Sprintf("containerId: %s", containerID[:12]))
292287

293288
lsInfo, _ := fetchLocalStackInfo(ctx, c.Port)
294-
tel.emitEmulatorStartSuccess(ctx, c, containerID[:12], time.Since(startTime).Milliseconds(), lsInfo)
289+
emitEmulatorStartSuccess(ctx, tel, c, containerID[:12], time.Since(startTime).Milliseconds(), lsInfo)
295290
}
296291
return nil
297292
}
298293

299-
func selectContainersToStart(ctx context.Context, rt runtime.Runtime, sink output.Sink, tel telCtx, containers []runtime.ContainerConfig) ([]runtime.ContainerConfig, error) {
294+
func selectContainersToStart(ctx context.Context, rt runtime.Runtime, sink output.Sink, tel *telemetry.Client, containers []runtime.ContainerConfig) ([]runtime.ContainerConfig, error) {
300295
var filtered []runtime.ContainerConfig
301296
for _, c := range containers {
302297
running, err := rt.IsRunning(ctx, c.Name)
@@ -309,7 +304,7 @@ func selectContainersToStart(ctx context.Context, rt runtime.Runtime, sink outpu
309304
}
310305
if err := ports.CheckAvailable(c.Port); err != nil {
311306
emitPortInUseError(sink, c.Port)
312-
tel.emitEmulatorStartError(ctx, c, telemetry.ErrCodePortConflict, err.Error())
307+
emitEmulatorStartError(ctx, tel, c, telemetry.ErrCodePortConflict, err.Error())
313308
return nil, output.NewSilentError(err)
314309
}
315310
filtered = append(filtered, c)
@@ -332,7 +327,7 @@ func emitPortInUseError(sink output.Sink, port string) {
332327
})
333328
}
334329

335-
func validateLicense(ctx context.Context, rt runtime.Runtime, sink output.Sink, opts StartOptions, tel telCtx, containerConfig runtime.ContainerConfig, token string) error {
330+
func validateLicense(ctx context.Context, rt runtime.Runtime, sink output.Sink, opts StartOptions, tel *telemetry.Client, containerConfig runtime.ContainerConfig, token string) error {
336331
version := containerConfig.Tag
337332
if version == "" || version == "latest" {
338333
actualVersion, err := rt.GetImageVersion(ctx, containerConfig.Image)
@@ -365,7 +360,7 @@ func validateLicense(ctx context.Context, rt runtime.Runtime, sink output.Sink,
365360
if errors.As(err, &licErr) && licErr.Detail != "" {
366361
opts.Logger.Error("license server response (HTTP %d): %s", licErr.Status, licErr.Detail)
367362
}
368-
tel.emitEmulatorStartError(ctx, containerConfig, telemetry.ErrCodeLicenseInvalid, err.Error())
363+
emitEmulatorStartError(ctx, tel, containerConfig, telemetry.ErrCodeLicenseInvalid, err.Error())
369364
return fmt.Errorf("license validation failed for %s:%s: %w", containerConfig.ProductName, version, err)
370365
}
371366

internal/container/stop.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ import (
1414
// StopOptions carries optional telemetry context for the stop command.
1515
type StopOptions struct {
1616
Telemetry *telemetry.Client
17-
AuthToken string
1817
}
1918

2019
func Stop(ctx context.Context, rt runtime.Runtime, sink output.Sink, containers []config.ContainerConfig, opts StopOptions) error {
@@ -51,7 +50,7 @@ func Stop(ctx context.Context, rt runtime.Runtime, sink output.Sink, containers
5150
if opts.Telemetry != nil {
5251
opts.Telemetry.Emit(ctx, "lstk_lifecycle", telemetry.ToMap(telemetry.LifecycleEvent{
5352
EventType: telemetry.LifecycleStop,
54-
Environment: opts.Telemetry.GetEnvironment(opts.AuthToken),
53+
Environment: opts.Telemetry.GetEnvironment(),
5554
Emulator: string(c.Type),
5655
DurationMS: time.Since(stopStart).Milliseconds(),
5756
LocalStackInfo: lsInfo,

0 commit comments

Comments
 (0)