Skip to content

Commit cc19632

Browse files
committed
Added Sentry into go, added proper exit codes for coreconsole and rewrote some error handling.
1 parent 0f2bf9a commit cc19632

File tree

13 files changed

+222
-112
lines changed

13 files changed

+222
-112
lines changed

.env.example

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@ ENV=
33
CONFIGURED=false
44
SESSION_KEY=
55
HTTP_VALIDATION_KEY=
6-
HTTP_ENCRYPTION_KEY=
6+
HTTP_ENCRYPTION_KEY=
7+
LOGGGING_SENTRY_DSN=https://sentry.io/...

Makefile

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,14 @@ docker-build:
4343

4444
cs-build-release:
4545
cd coreconsole && \
46-
dotnet build -c Release -o ../cc
46+
dotnet build coreconsole.csproj -c Release -o ../cc && \
47+
cp data ../cc/data -r
48+
4749

4850
cs-build-debug:
4951
cd coreconsole && \
50-
dotnet build -c Debug -o ../cc
52+
dotnet build coreconsole.csproj -c Debug -o ../cc && \
53+
cp data ../cc/data -r
5154

5255
cs-clean:
5356
/bin/rm -rfv cc

coreconsole/Program.cs

Lines changed: 48 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -14,68 +14,64 @@ public static class MainClass
1414
{
1515
public static void Main(string[] args)
1616
{
17-
if(!Helpers.LoadEnv()) return;
18-
19-
using (SentrySdk.Init(o =>
20-
{
21-
o.Dsn = Environment.GetEnvironmentVariable("SENTRY_DSN");
22-
}))
17+
if (!Helpers.LoadEnv()) Environment.Exit((int)enums.ExitCode.EnvNotConfigured);
18+
19+
using (SentrySdk.Init(o => { o.Dsn = Environment.GetEnvironmentVariable("SENTRY_DSN"); }))
2320
{
24-
var pokemonArg = new Argument<string>(
25-
"pokemon",
26-
"The pokemon file (in base64 format)."
27-
);
21+
var pokemonArg = new Argument<string>(
22+
"pokemon",
23+
"The pokemon file (in base64 format)."
24+
);
2825

29-
var generationOption = new Option<EntityContext?>(
30-
"--generation",
31-
"Used to determine desired generation when generation could be 6/7 or 8/8b"
32-
);
26+
var generationOption = new Option<EntityContext?>(
27+
"--generation",
28+
"Used to determine desired generation when generation could be 6/7 or 8/8b"
29+
);
3330

34-
var cmd1 = new Command("summary", "Returns the summary for a given pokemon.")
35-
{
36-
pokemonArg,
37-
generationOption
38-
};
39-
cmd1.SetHandler(Summary.SummaryHandler, pokemonArg, generationOption);
31+
var cmd1 = new Command("summary", "Returns the summary for a given pokemon.")
32+
{
33+
pokemonArg,
34+
generationOption
35+
};
36+
cmd1.SetHandler(Summary.SummaryHandler, pokemonArg, generationOption);
4037

41-
var cmd2 = new Command("legality", "Returns the legality status for a Pokemon, including what checks fail.")
42-
{
43-
pokemonArg,
44-
generationOption
45-
};
38+
var cmd2 = new Command("legality", "Returns the legality status for a Pokemon, including what checks fail.")
39+
{
40+
pokemonArg,
41+
generationOption
42+
};
4643

47-
cmd2.SetHandler(Legality.LegalityCheckHandler, pokemonArg, generationOption);
44+
cmd2.SetHandler(Legality.LegalityCheckHandler, pokemonArg, generationOption);
4845

49-
var legalizationGenerationOverride = new Option<int?>("--legalization-generation",
50-
"Forces the legalized Pokemon to use the provided generation (may cause legalization to fail).");
46+
var legalizationGenerationOverride = new Option<int?>("--legalization-generation",
47+
"Forces the legalized Pokemon to use the provided generation (may cause legalization to fail).");
5148

52-
var legalizationGameVersionOverride = new Option<GameVersion?>("--version",
53-
"Game Version to use in trying to legalize the Pokemon (may cause legalization to fail).");
49+
var legalizationGameVersionOverride = new Option<GameVersion?>("--version",
50+
"Game Version to use in trying to legalize the Pokemon (may cause legalization to fail).");
5451

55-
var cmd3 = new Command("legalize", "Attempts to auto legalize a pokemon and returns it if successful.")
56-
{
57-
pokemonArg,
58-
generationOption,
59-
legalizationGenerationOverride,
60-
legalizationGameVersionOverride
61-
};
62-
cmd3.SetHandler(Legality.LegalizeHandler, pokemonArg, generationOption,
63-
legalizationGenerationOverride, legalizationGameVersionOverride);
52+
var cmd3 = new Command("legalize", "Attempts to auto legalize a pokemon and returns it if successful.")
53+
{
54+
pokemonArg,
55+
generationOption,
56+
legalizationGenerationOverride,
57+
legalizationGameVersionOverride
58+
};
59+
cmd3.SetHandler(Legality.LegalizeHandler, pokemonArg, generationOption,
60+
legalizationGenerationOverride, legalizationGameVersionOverride);
6461

65-
var cmd4 = new Command("version", "Returns the version for ALM/PKHeX");
66-
cmd4.SetHandler(() =>
67-
{
68-
Console.WriteLine(JsonSerializer.Serialize(new Version()));
69-
});
62+
var cmd4 = new Command("version", "Returns the version for ALM/PKHeX");
63+
cmd4.SetHandler(() => { Console.WriteLine(JsonSerializer.Serialize(new Version())); });
7064

71-
var cli = new RootCommand("CoreConsole - a tool for interacting with PKHeX and Auto Legality via CLI.")
72-
{
73-
cmd1,
74-
cmd2,
75-
cmd3,
76-
cmd4
77-
};
78-
cli.Invoke(args);
65+
var cli = new RootCommand("CoreConsole - a tool for interacting with PKHeX and Auto Legality via CLI.")
66+
{
67+
cmd1,
68+
cmd2,
69+
cmd3,
70+
cmd4
71+
};
72+
cli.Invoke(args);
7973
}
74+
75+
Environment.Exit((int)enums.ExitCode.Success);
8076
}
8177
}

coreconsole/enums/ExitCode.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
namespace coreconsole.enums;
2+
3+
public enum ExitCode: int
4+
{
5+
Success = 0,
6+
BadBase64 = 1,
7+
Base64NotPokemon = 2,
8+
UnknownErrorDuringBase64ToPokemon = 3,
9+
EnvNotConfigured = 4
10+
}

coreconsole/utils/Helpers.cs

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55

66
namespace coreconsole.utils;
77

8-
public class Helpers
8+
public static class Helpers
99
{
1010
public static JsonSerializerOptions? SerializerOptions;
11+
1112
// Used for tests
1213
public static byte[] StringToByteArray(string hex)
1314
{
@@ -22,40 +23,39 @@ public static void Init()
2223
EncounterEvent.RefreshMGDB(string.Empty);
2324
RibbonStrings.ResetDictionary(GameInfo.Strings.ribbons);
2425
Sprites.Init();
25-
26+
2627
SerializerOptions = new JsonSerializerOptions
2728
{
2829
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
2930
};
3031
}
3132

32-
public static PKM? PokemonFromBase64(string pokemon, EntityContext context = EntityContext.None)
33+
public static PKM PokemonFromBase64(string pokemon, EntityContext context = EntityContext.None)
3334
{
3435
try
3536
{
3637
var pkmnStrBytes = Convert.FromBase64String(pokemon);
3738

3839
var pkmn = EntityFormat.GetFromBytes(pkmnStrBytes, context);
3940

40-
if (pkmn is null)
41-
{
42-
Console.Error.WriteLine("{\"error\": \"base64 is not a pokemon\"}");
43-
SentrySdk.CaptureMessage(level: SentryLevel.Error, message: "base64 provided is not a pokemon");
44-
return null;
45-
}
46-
47-
return pkmn;
41+
if (pkmn is not null) return pkmn;
42+
Console.Error.WriteLine("{\"error\": \"base64 is not a pokemon\"}");
43+
SentrySdk.CaptureMessage(level: SentryLevel.Error, message: "base64 provided is not a pokemon");
44+
Environment.Exit((int)enums.ExitCode.Base64NotPokemon);
4845
}
4946
catch (Exception e) when (e is FormatException or ArgumentNullException)
5047
{
5148
Console.Error.WriteLine("{\"error\": \"invalid base64 string provided\"}");
5249
SentrySdk.CaptureException(e);
53-
return null;
54-
} catch (Exception e) when (e is not FormatException and not ArgumentNullException)
50+
Environment.Exit((int)enums.ExitCode.BadBase64);
51+
}
52+
catch (Exception e) when (e is not FormatException and not ArgumentNullException)
5553
{
5654
SentrySdk.CaptureException(e);
57-
return null;
55+
Environment.Exit((int)enums.ExitCode.UnknownErrorDuringBase64ToPokemon);
5856
}
57+
58+
return null;
5959
}
6060

6161
public static bool LoadEnv()
@@ -70,7 +70,7 @@ public static bool LoadEnv()
7070
{
7171
var parts = line.Split("=");
7272
if (parts.Length != 2) continue;
73-
73+
7474
Environment.SetEnvironmentVariable(parts[0], parts[1]);
7575
}
7676

go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ go 1.20
44

55
require (
66
github.com/apex/log v1.9.0
7+
github.com/getsentry/sentry-go v0.21.0
78
github.com/go-chi/chi/v5 v5.0.8
89
github.com/go-chi/httprate v0.7.4
910
github.com/lrstanley/chix v1.0.0

go.sum

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,13 @@ github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBD
6666
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
6767
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
6868
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
69+
github.com/getsentry/sentry-go v0.21.0 h1:c9l5F1nPF30JIppulk4veau90PK6Smu3abgVtVQWon4=
70+
github.com/getsentry/sentry-go v0.21.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY=
6971
github.com/go-chi/chi/v5 v5.0.8 h1:lD+NLqFcAi1ovnVZpsnObHGW4xb4J8lNmoYVfECH1Y0=
7072
github.com/go-chi/chi/v5 v5.0.8/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
7173
github.com/go-chi/httprate v0.7.4 h1:a2GIjv8he9LRf3712zxxnRdckQCm7I8y8yQhkJ84V6M=
7274
github.com/go-chi/httprate v0.7.4/go.mod h1:6GOYBSwnpra4CQfAKXu8sQZg+nZ0M1g9QnyFvxrAB8A=
75+
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
7376
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
7477
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
7578
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
@@ -204,6 +207,7 @@ github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyex
204207
github.com/mrjones/oauth v0.0.0-20180629183705-f4e24b6d100c/go.mod h1:skjdDftzkFALcuGzYSklqYd8gvat6F1gZJ4YPVbkZpM=
205208
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
206209
github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
210+
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
207211
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
208212
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
209213
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=

internal/handlers/generalhandler/handler.go

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88

99
"github.com/FlagBrew/CoreAPI/internal/models"
1010
"github.com/FlagBrew/CoreAPI/internal/utils"
11+
"github.com/getsentry/sentry-go"
1112
"github.com/go-chi/chi/v5"
1213
"github.com/lrstanley/chix"
1314
)
@@ -21,20 +22,39 @@ func NewHandler() *Handler {
2122

2223
func (h *Handler) Route(r chi.Router) {
2324
r.Get("/ping", h.ping)
25+
r.Get("/kuma-ping", h.kumaPing)
26+
}
27+
28+
func (h *Handler) kumaPing(w http.ResponseWriter, r *http.Request) {
29+
chix.JSON(w, r, http.StatusOK, chix.M{
30+
"status": "ok",
31+
})
2432
}
2533

2634
func (h *Handler) ping(w http.ResponseWriter, r *http.Request) {
2735
start := time.Now()
2836
version, err := utils.RunCoreConsole(r.Context(), "version", "")
2937

3038
if err != nil {
39+
// if error code 4, the .env is missing for coreconsole, which should only happen if I forget to set it up, meaning we can tell the user that coreconsole is currently being set-up and to try again later
40+
if err.Error() == "CoreConsole exited with code 4" {
41+
w.Header().Set("Content-Type", "application/json")
42+
43+
chix.JSON(w, r, http.StatusServiceUnavailable, chix.M{
44+
"error": "CoreConsole is currently being set-up, please try again later",
45+
})
46+
return
47+
}
48+
49+
// If we got here, then something went wrong but likely wasn't caught by coreconsole inside sentry so we'll deal with it here.
50+
sentry.CaptureException(err)
3151
chix.Error(w, r, fmt.Errorf("something went wrong, please try again later"))
3252
return
3353
}
3454

3555
v := &models.ALMVersion{}
3656
if err := json.Unmarshal([]byte(version), &v); err != nil {
37-
fmt.Println(err)
57+
sentry.CaptureException(err)
3858
chix.Error(w, r, fmt.Errorf("something went wrong, please try again later"))
3959
return
4060
}

internal/handlers/infohandler/handler.go

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
package infohandler
22

33
import (
4-
"encoding/json"
54
"fmt"
65
"net/http"
76

87
"github.com/FlagBrew/CoreAPI/internal/models"
98
"github.com/FlagBrew/CoreAPI/internal/utils"
9+
"github.com/getsentry/sentry-go"
1010
"github.com/go-chi/chi/v5"
1111
"github.com/lrstanley/chix"
1212
)
@@ -31,7 +31,18 @@ func (h *Handler) getInfo(w http.ResponseWriter, r *http.Request) {
3131

3232
// Get the pkmn in base64
3333
pkmn, err := utils.GetPkmnFromRequest(w, r)
34-
if chix.Error(w, r, err) {
34+
if err != nil {
35+
if err.Error() == "file too large" {
36+
w.Header().Set("Content-Type", "application/json")
37+
38+
chix.JSON(w, r, http.StatusRequestEntityTooLarge, chix.M{
39+
"error": "file too large",
40+
})
41+
return
42+
}
43+
44+
chix.Error(w, r, err)
45+
sentry.CaptureException(err)
3546
return
3647
}
3748

@@ -43,23 +54,34 @@ func (h *Handler) getInfo(w http.ResponseWriter, r *http.Request) {
4354

4455
output, err := utils.RunCoreConsole(r.Context(), "summary", pkmn, extraArgs...)
4556
if err != nil {
46-
if err.Error() != "exit status 1" {
47-
chix.Error(w, r, err)
57+
// if error code 1 or 2, the pkmn provided is invalid.
58+
if err.Error() == "CoreConsole exited with code 1" || err.Error() == "CoreConsole exited with code 2" {
59+
w.Header().Set("Content-Type", "application/json")
60+
w.WriteHeader(http.StatusBadRequest)
61+
62+
w.Write([]byte(output))
4863
return
4964
}
5065

51-
// try to parse the output as JSON
52-
var js json.RawMessage
53-
if json.Unmarshal([]byte(output), &js) != nil {
54-
// this is not JSON, DO NOT RETURN THIS TO THE USER
66+
// if error code 3, something unknown happened, but should've been captured by sentry inside coreconsole itself.
67+
if err.Error() == "CoreConsole exited with code 3" {
5568
chix.Error(w, r, fmt.Errorf("something went wrong, please try again later"))
5669
return
5770
}
5871

59-
w.Header().Set("Content-Type", "application/json")
60-
w.WriteHeader(http.StatusBadRequest)
72+
// if error code 4, the .env is missing for coreconsole, which should only happen if I forget to set it up, meaning we can tell the user that coreconsole is currently being set-up and to try again later
73+
if err.Error() == "CoreConsole exited with code 4" {
74+
w.Header().Set("Content-Type", "application/json")
75+
76+
chix.JSON(w, r, http.StatusServiceUnavailable, chix.M{
77+
"error": "CoreConsole is currently being set-up, please try again later",
78+
})
79+
return
80+
}
6181

62-
w.Write([]byte(output))
82+
// If we got here, then something went wrong but likely wasn't caught by coreconsole inside sentry so we'll deal with it here.
83+
sentry.CaptureException(err)
84+
chix.Error(w, r, fmt.Errorf("something went wrong, please try again later"))
6385
return
6486
}
6587
// we got JSON back, so we can just write it to the response

0 commit comments

Comments
 (0)