Skip to content

Commit

Permalink
fix: sentry version and message (#80)
Browse files Browse the repository at this point in the history
Closes: WORLD-1126

## Overview

Adding version and env to the sentry, and tidy up message for sentry

## Brief Changelog

- remove sentry capture message from zerolog hook
- add sentry capture whenever execution got error
- fix --config flags

## Testing and Verifying

- manual test
- unit test adjustment

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

- **New Features**
	- Introduced a new environment variable for production builds.
	- Enhanced telemetry initialization with environment context.

- **Bug Fixes**
	- Improved error handling across various commands and configuration retrieval.
	- Enhanced user feedback during image pulling operations.

- **Documentation**
	- Updated error handling mechanisms for clarity and robustness.

- **Refactor**
	- Simplified configuration retrieval methods by removing unnecessary parameters.
	- Updated command execution methods to enhance error signaling.
	- Removed unused dependencies and imports to streamline the codebase.
	- Enhanced error messaging consistency across various components.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
  • Loading branch information
zulkhair committed Oct 22, 2024
1 parent 88789d7 commit acd9f95
Show file tree
Hide file tree
Showing 23 changed files with 137 additions and 135 deletions.
2 changes: 2 additions & 0 deletions .goreleaser.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@ builds:
- CGO_ENABLED=0
- SENTRY_DSN={{ if index .Env "SENTRY_DSN" }}{{ .Env.SENTRY_DSN }}{{ else }}default_null{{ end }}
- POSTHOG_API_KEY={{ if index .Env "POSTHOG_API_KEY" }}{{ .Env.POSTHOG_API_KEY }}{{ else }}default_null{{ end }}
- BUILD_ENV={{ if index .Env "BUILD_ENV" }}{{ .Env.BUILD_ENV }}{{ else }}DEV{{ end }}
ldflags:
- -s -w
- -X main.AppVersion={{.Version}}
- -X main.SentryDsn={{.Env.SENTRY_DSN}}
- -X main.PosthogAPIKey={{.Env.POSTHOG_API_KEY}}
- -X main.Env={{.Env.BUILD_ENV}}
goos:
- linux
- windows
Expand Down
17 changes: 16 additions & 1 deletion cmd/world/cardinal/cardinal.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package cardinal
import (
"github.com/spf13/cobra"

"pkg.world.dev/world-cli/common/config"
"pkg.world.dev/world-cli/common/dependency"
"pkg.world.dev/world-cli/common/docker/service"
"pkg.world.dev/world-cli/common/logger"
"pkg.world.dev/world-cli/tea/style"
)
Expand All @@ -23,14 +25,27 @@ var BaseCmd = &cobra.Command{
dependency.DockerDaemon,
)
},
Run: func(cmd *cobra.Command, _ []string) {
RunE: func(cmd *cobra.Command, _ []string) error {
if err := cmd.Help(); err != nil {
logger.Fatalf("Failed to execute cardinal command : %s", err.Error())
return err
}
return nil
},
}

func init() {
// Register subcommands - `world cardinal [subcommand]`
BaseCmd.AddCommand(startCmd, devCmd, restartCmd, purgeCmd, stopCmd)
}

func getServices(cfg *config.Config) []service.Builder {
services := []service.Builder{service.NakamaDB, service.Redis, service.Cardinal, service.Nakama}
if cfg.Telemetry && cfg.DockerEnv["NAKAMA_TRACE_ENABLED"] == "true" {
services = append(services, service.Jaeger)
}
if cfg.Telemetry && cfg.DockerEnv["NAKAMA_METRICS_ENABLED"] == "true" {
services = append(services, service.Prometheus)
}
return services
}
2 changes: 1 addition & 1 deletion cmd/world/cardinal/dev.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ var devCmd = &cobra.Command{
return err
}

cfg, err := config.GetConfig(cmd)
cfg, err := config.GetConfig()
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/world/cardinal/purge.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ var purgeCmd = &cobra.Command{
Long: `Stop and reset the state of your Cardinal game shard.
This command stop all Docker services and remove all Docker volumes.`,
RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := config.GetConfig(cmd)
cfg, err := config.GetConfig()
if err != nil {
return err
}
Expand Down
5 changes: 2 additions & 3 deletions cmd/world/cardinal/restart.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (

"pkg.world.dev/world-cli/common/config"
"pkg.world.dev/world-cli/common/docker"
"pkg.world.dev/world-cli/common/docker/service"
)

// restartCmd restarts your Cardinal game shard stack
Expand All @@ -19,7 +18,7 @@ This will restart the following Docker services:
- Cardinal (Core game logic)
- Nakama (Relay)`,
RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := config.GetConfig(cmd)
cfg, err := config.GetConfig()
if err != nil {
return err
}
Expand All @@ -39,7 +38,7 @@ This will restart the following Docker services:
}
defer dockerClient.Close()

err = dockerClient.Restart(cmd.Context(), service.Cardinal, service.Nakama)
err = dockerClient.Restart(cmd.Context(), getServices(cfg)...)
if err != nil {
return err
}
Expand Down
16 changes: 4 additions & 12 deletions cmd/world/cardinal/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"pkg.world.dev/world-cli/common"
"pkg.world.dev/world-cli/common/config"
"pkg.world.dev/world-cli/common/docker"
"pkg.world.dev/world-cli/common/docker/service"
)

/////////////////
Expand Down Expand Up @@ -59,7 +58,7 @@ This will start the following Docker services and its dependencies:
- Nakama (Relay)
- Redis (Cardinal dependency)`,
RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := config.GetConfig(cmd)
cfg, err := config.GetConfig()
if err != nil {
return err
}
Expand Down Expand Up @@ -90,7 +89,7 @@ This will start the following Docker services and its dependencies:
if logLevel != "" {
zeroLogLevel, err := zerolog.ParseLevel(logLevel)
if err != nil {
return fmt.Errorf("invalid value for flag %s: must be one of (%v)", flagLogLevel, validLogLevels)
return eris.Errorf("invalid value for flag %s: must be one of (%v)", flagLogLevel, validLogLevels)
}
cfg.DockerEnv[DockerCardinalEnvLogLevel] = zeroLogLevel.String()
}
Expand All @@ -101,7 +100,7 @@ This will start the following Docker services and its dependencies:
} else if _, err := zerolog.ParseLevel(cfg.DockerEnv[DockerCardinalEnvLogLevel]); err != nil {
// make sure the log level is valid when the flag is not set and using env var from config
// Error when CARDINAL_LOG_LEVEL is not a valid log level
return fmt.Errorf("invalid value for %s env variable in the config file: must be one of (%v)",
return eris.Errorf("invalid value for %s env variable in the config file: must be one of (%v)",
DockerCardinalEnvLogLevel, validLogLevels)
}

Expand All @@ -125,14 +124,7 @@ This will start the following Docker services and its dependencies:

// Start the World Engine stack
group.Go(func() error {
services := []service.Builder{service.NakamaDB, service.Redis, service.Cardinal, service.Nakama}
if cfg.Telemetry && cfg.DockerEnv["NAKAMA_TRACE_ENABLED"] == "true" {
services = append(services, service.Jaeger)
}
if cfg.Telemetry && cfg.DockerEnv["NAKAMA_METRICS_ENABLED"] == "true" {
services = append(services, service.Prometheus)
}
if err := dockerClient.Start(ctx, services...); err != nil {
if err := dockerClient.Start(ctx, getServices(cfg)...); err != nil {
return eris.Wrap(err, "Encountered an error with Docker")
}
return eris.Wrap(ErrGracefulExit, "Stack terminated")
Expand Down
2 changes: 1 addition & 1 deletion cmd/world/cardinal/stop.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ This will stop the following Docker services:
- Nakama (Relay) + DB
- Redis (Cardinal dependency)`,
RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := config.GetConfig(cmd)
cfg, err := config.GetConfig()
if err != nil {
return err
}
Expand Down
12 changes: 6 additions & 6 deletions cmd/world/evm/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ var startCmd = &cobra.Command{
Short: "Start the EVM base shard. Use --da-auth-token to pass in an auth token directly.",
Long: "Start the EVM base shard. Requires connection to celestia DA.",
RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := config.GetConfig(cmd)
cfg, err := config.GetConfig()
if err != nil {
return err
}
Expand Down Expand Up @@ -52,7 +52,7 @@ var startCmd = &cobra.Command{

err = dockerClient.Start(cmd.Context(), service.EVM)
if err != nil {
return fmt.Errorf("error starting %s docker container: %w", teacmd.DockerServiceEVM, err)
return eris.Wrapf(err, "error starting %s docker container", teacmd.DockerServiceEVM)
}

// Stop the DA service if it was started in dev mode
Expand Down Expand Up @@ -82,7 +82,7 @@ func validateDevDALayer(ctx context.Context, cfg *config.Config, dockerClient *d
cfg.Timeout = -1
logger.Println("starting DA docker service for dev mode...")
if err := dockerClient.Start(ctx, service.CelestiaDevNet); err != nil {
return fmt.Errorf("error starting %s docker container: %w", daService, err)
return eris.Wrapf(err, "error starting %s docker container", daService)
}
logger.Println("started DA service...")

Expand Down Expand Up @@ -115,12 +115,12 @@ func validateProdDALayer(cfg *config.Config) error {
if len(cfg.DockerEnv[env]) > 0 {
continue
}
errs = append(errs, fmt.Errorf("missing %q", env))
errs = append(errs, eris.Errorf("missing %q", env))
}
if len(errs) > 0 {
// Prepend an error describing the overall problem
errs = append([]error{
errors.New("the [evm] section of your config is missing some required variables"),
eris.New("the [evm] section of your config is missing some required variables"),
}, errs...)
return errors.Join(errs...)
}
Expand Down Expand Up @@ -169,7 +169,7 @@ func getDAToken(ctx context.Context, cfg *config.Config, dockerClient *docker.Cl
}

if token == "" {
return "", errors.New("got empty DA token")
return "", eris.New("got empty DA token")
}
return token, nil
}
2 changes: 1 addition & 1 deletion cmd/world/evm/stop.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ var stopCmd = &cobra.Command{
Short: "Stop the EVM base shard and DA layer client.",
Long: "Stop the EVM base shard and data availability layer client if they are running.",
RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := config.GetConfig(cmd)
cfg, err := config.GetConfig()
if err != nil {
return err
}
Expand Down
16 changes: 11 additions & 5 deletions cmd/world/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,15 @@ import (

// This variable will be overridden by ldflags during build
// Example:
// go build -ldflags "-X main.AppVersion=1.0.0 -X main.PosthogAPIKey=<POSTHOG_API_KEY> -X main.SentryDsn=<SENTRY_DSN>"
/*
go build -ldflags "-X main.AppVersion=1.0.0 -X main.PosthogAPIKey=<POSTHOG_API_KEY>
-X main.SentryDsn=<SENTRY_DSN> -X main.Env=<DEV|PROD>"
*/
var (
AppVersion string
PosthogAPIKey string
SentryDsn string
Env string
)

func init() {
Expand All @@ -27,16 +31,18 @@ func init() {
AppVersion = "v0.0.1-dev"
}
root.AppVersion = AppVersion

if Env == "" {
Env = "DEV"
}
root.Env = Env
}

func main() {
// Sentry initialization
telemetry.SentryInit(SentryDsn)
telemetry.SentryInit(SentryDsn, Env, AppVersion)
defer telemetry.SentryFlush()

// Set logger sentry hook
log.Logger = log.Logger.Hook(telemetry.SentryHook{})

// Set up config directory "~/.worldcli/"
err := globalconfig.SetupConfigDir()
if err != nil {
Expand Down
1 change: 0 additions & 1 deletion cmd/world/root/doctor.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ var DoctorDeps = []dependency.Dependency{
dependency.Git,
dependency.Go,
dependency.Docker,
dependency.DockerCompose,
dependency.DockerDaemon,
}

Expand Down
8 changes: 6 additions & 2 deletions cmd/world/root/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package root
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
Expand All @@ -13,6 +12,7 @@ import (
"time"

"github.com/charmbracelet/lipgloss"
"github.com/getsentry/sentry-go"
"github.com/hashicorp/go-version"
"github.com/rotisserie/eris"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -72,6 +72,9 @@ func init() {
rootCmd.AddCommand(cardinal.BaseCmd)
rootCmd.AddCommand(evm.BaseCmd)

// Remove completion subcommand
rootCmd.CompletionOptions.DisableDefaultCmd = true

config.AddConfigFlag(rootCmd)
logger.AddVerboseFlag(rootCmd)
}
Expand All @@ -95,7 +98,7 @@ func checkLatestVersion() error {
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
logger.Debug(eris.Wrap(errors.New("status is not 200"), "error fetching the latest release"))
logger.Debug(eris.Wrap(eris.New("status is not 200"), "error fetching the latest release"))
return nil
}

Expand Down Expand Up @@ -139,6 +142,7 @@ func checkLatestVersion() error {
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
sentry.CaptureException(err)
logger.Errors(err)
}
// print log stack
Expand Down
17 changes: 7 additions & 10 deletions cmd/world/root/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@ package root
import (
"bytes"
"context"
"errors"
"fmt"
"net"
"os"
"strings"
"testing"
"time"

"github.com/rotisserie/eris"
"github.com/spf13/cobra"
"gotest.tools/v3/assert"
)
Expand All @@ -34,12 +33,12 @@ func outputFromCmd(cobra *cobra.Command, cmd string) ([]string, error) {
}()

if err := cobra.Execute(); err != nil {
return nil, fmt.Errorf("root command failed with: %w", err)
return nil, eris.Errorf("root command failed with: %v", err)
}
lines := strings.Split(stdOut.String(), "\n")
errorStr := stdErr.String()
if len(errorStr) > 0 {
return lines, errors.New(errorStr)
return lines, eris.New(errorStr)
}

return lines, nil
Expand All @@ -49,11 +48,10 @@ func TestSubcommandsHaveHelpText(t *testing.T) {
lines, err := outputFromCmd(rootCmd, "help")
assert.NilError(t, err)
seenSubcommands := map[string]int{
"cardinal": 0,
"completion": 0,
"doctor": 0,
"help": 0,
"version": 0,
"cardinal": 0,
"doctor": 0,
"help": 0,
"version": 0,
}

for _, line := range lines {
Expand All @@ -78,7 +76,6 @@ func TestExecuteDoctorCommand(t *testing.T) {
"Git": 0,
"Go": 0,
"Docker": 0,
"Docker Compose": 0,
"Docker daemon is running": 0,
}

Expand Down
6 changes: 5 additions & 1 deletion cmd/world/root/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
)

var AppVersion string
var Env string

// versionCmd print the version number of World CLI
// Usage: `world version`
Expand All @@ -15,6 +16,9 @@ var versionCmd = &cobra.Command{
Short: "Print the version number of World CLI",
Long: `Print the version number of World CLI`,
Run: func(_ *cobra.Command, _ []string) {
fmt.Printf("World CLI %s\n", AppVersion)
if Env == "PROD" {
Env = ""
}
fmt.Printf("World CLI v%s %s\n", AppVersion, Env)
},
}
Loading

0 comments on commit acd9f95

Please # to comment.