Skip to content

Commit 384c8f3

Browse files
authored
Merge pull request #31 from vaibhavsijaria/main
Running code on visible test cases without creating submission
2 parents fbc114e + b0e9fbc commit 384c8f3

File tree

5 files changed

+153
-21
lines changed

5 files changed

+153
-21
lines changed

internal/controllers/runcode.go

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package controllers
2+
3+
import (
4+
"bytes"
5+
"encoding/json"
6+
"net/http"
7+
"net/url"
8+
9+
"github.com/CodeChefVIT/cookoff-backend/internal/db"
10+
"github.com/CodeChefVIT/cookoff-backend/internal/helpers/database"
11+
httphelpers "github.com/CodeChefVIT/cookoff-backend/internal/helpers/http"
12+
logger "github.com/CodeChefVIT/cookoff-backend/internal/helpers/logging"
13+
"github.com/CodeChefVIT/cookoff-backend/internal/helpers/submission"
14+
"github.com/google/uuid"
15+
)
16+
17+
type resp struct {
18+
Result []submission.Judgeresp `json:"result"`
19+
}
20+
21+
func RunCode(w http.ResponseWriter, r *http.Request) {
22+
ctx := r.Context()
23+
24+
var req subreq
25+
err := json.NewDecoder(r.Body).Decode(&req)
26+
if err != nil {
27+
httphelpers.WriteError(w, http.StatusBadRequest, "Invalid request payload")
28+
return
29+
}
30+
31+
question_id, _ := uuid.Parse(req.QuestionID)
32+
33+
testcases, err := database.Queries.GetTestCases(ctx, db.GetTestCasesParams{QuestionID: question_id, Column2: true})
34+
if err != nil {
35+
httphelpers.WriteError(w, http.StatusBadRequest, "Question not found")
36+
return
37+
}
38+
39+
judge0URL, _ := url.Parse(JUDGE0_URI + "/submissions/")
40+
params := url.Values{}
41+
params.Add("base64_encoded", "true")
42+
params.Add("wait", "true")
43+
judge0URL.RawQuery = params.Encode()
44+
45+
var payload submission.Submission
46+
response := resp{
47+
Result: make([]submission.Judgeresp, len(testcases)),
48+
}
49+
for i, testcase := range testcases {
50+
payload = submission.Submission{
51+
LanguageID: req.LanguageID,
52+
SourceCode: submission.B64(req.SourceCode),
53+
Input: submission.B64(*testcase.Input),
54+
Output: submission.B64(*testcase.ExpectedOutput),
55+
}
56+
57+
payloadJSON, err := json.Marshal(payload)
58+
if err != nil {
59+
logger.Errof("Error marshaling payload: %v", err)
60+
httphelpers.WriteError(w, http.StatusInternalServerError, "Unable to marshal payload")
61+
return
62+
}
63+
64+
result, err := http.Post(judge0URL.String(), "application/json", bytes.NewBuffer(payloadJSON))
65+
if err != nil {
66+
logger.Errof("Error making request to Judge0: %v", err)
67+
httphelpers.WriteError(w, http.StatusInternalServerError, "Error making request to Judge0")
68+
return
69+
}
70+
defer result.Body.Close()
71+
72+
var data submission.Judgeresp
73+
data.TestCaseID = testcase.ID.String()
74+
if err = json.NewDecoder(result.Body).Decode(&data); err != nil {
75+
logger.Errof("Error decoding response from Judge0: %v", err)
76+
httphelpers.WriteError(w, http.StatusInternalServerError, "Error decoding response from Judge0")
77+
return
78+
}
79+
80+
data.CompilerOutput, _ = submission.DecodeB64(data.CompilerOutput)
81+
response.Result[i] = data
82+
}
83+
w.Header().Set("Content-Type", "application/json")
84+
if err := json.NewEncoder(w).Encode(response); err != nil {
85+
logger.Errof("Error encoding response: %v", err)
86+
httphelpers.WriteError(w, http.StatusInternalServerError, "Error encoding response")
87+
}
88+
}

internal/controllers/submission.go

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,15 @@ import (
44
"bytes"
55
"encoding/json"
66
"net/http"
7+
"net/url"
78
"os"
89

910
"github.com/CodeChefVIT/cookoff-backend/internal/db"
1011
"github.com/CodeChefVIT/cookoff-backend/internal/helpers/database"
1112
httphelpers "github.com/CodeChefVIT/cookoff-backend/internal/helpers/http"
1213
logger "github.com/CodeChefVIT/cookoff-backend/internal/helpers/logging"
1314
"github.com/CodeChefVIT/cookoff-backend/internal/helpers/submission"
15+
"github.com/go-chi/jwtauth/v5"
1416
"github.com/google/uuid"
1517
)
1618

@@ -20,8 +22,9 @@ type subreq struct {
2022
QuestionID string `json:"question_id"`
2123
}
2224

25+
var JUDGE0_URI = os.Getenv("JUDGE0_URI")
26+
2327
func SubmitCode(w http.ResponseWriter, r *http.Request) {
24-
JUDGE0_URI := os.Getenv("JUDGE0_URI")
2528
ctx := r.Context()
2629

2730
var req subreq
@@ -47,8 +50,12 @@ func SubmitCode(w http.ResponseWriter, r *http.Request) {
4750
return
4851
}
4952

50-
judge0URL := JUDGE0_URI + "/submissions/batch?base64_encoded=true"
51-
resp, err := http.Post(judge0URL, "application/json", bytes.NewBuffer(payload))
53+
judge0URL, _ := url.Parse(JUDGE0_URI + "/submissions/batch")
54+
55+
params := url.Values{}
56+
params.Add("base64_encoded", "true")
57+
judge0URL.RawQuery = params.Encode()
58+
resp, err := http.Post(judge0URL.String(), "application/json", bytes.NewBuffer(payload))
5259
if err != nil {
5360
logger.Errof("Error sending request to Judge0: %v", err)
5461
httphelpers.WriteError(w, http.StatusInternalServerError, "Failed to send request to Judge0")
@@ -63,7 +70,13 @@ func SubmitCode(w http.ResponseWriter, r *http.Request) {
6370
return
6471
}
6572

66-
user_id, _ := r.Context().Value("user_id").(string)
73+
_, claims, err := jwtauth.FromContext(r.Context())
74+
if err != nil {
75+
httphelpers.WriteError(w, http.StatusUnauthorized, "unauthorized")
76+
return
77+
}
78+
79+
user_id, _ := claims["user_id"].(string)
6780
userID, _ := uuid.Parse(user_id)
6881
qID, _ := uuid.Parse(req.QuestionID)
6982
nullUserID := uuid.NullUUID{UUID: userID, Valid: true}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package submission
2+
3+
import (
4+
"encoding/base64"
5+
"encoding/json"
6+
)
7+
8+
type Submission struct {
9+
LanguageID int `json:"language_id"`
10+
SourceCode string `json:"source_code"`
11+
Input string `json:"stdin"`
12+
Output string `json:"expected_output"`
13+
Callback string `json:"callback_url"`
14+
}
15+
16+
type Judgeresp struct {
17+
TestCaseID string
18+
StdOut string `json:"stdout"`
19+
Time string `json:"time"`
20+
Memory int `json:"memory"`
21+
StdErr string `json:"stderr"`
22+
Token string `json:"token"`
23+
Message string `json:"message"`
24+
Status Status `json:"status"`
25+
CompilerOutput string `json:"compile_output"`
26+
}
27+
28+
type Status struct {
29+
ID json.Number `json:"id"`
30+
Description string `json:"description"`
31+
}
32+
33+
func B64(data string) string {
34+
return base64.StdEncoding.EncodeToString([]byte(data))
35+
}
36+
37+
func DecodeB64(encoded string) (string, error) {
38+
decodedBytes, err := base64.StdEncoding.DecodeString(encoded)
39+
if err != nil {
40+
return "", err
41+
}
42+
return string(decodedBytes), nil
43+
}

internal/helpers/submission/submission.go

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package submission
22

33
import (
44
"context"
5-
"encoding/base64"
65
"encoding/json"
76
"errors"
87
"net/http"
@@ -14,14 +13,6 @@ import (
1413
"github.com/google/uuid"
1514
)
1615

17-
type Submission struct {
18-
LanguageID int `json:"language_id"`
19-
SourceCode string `json:"source_code"`
20-
Input string `json:"stdin"`
21-
Output string `json:"expected_output"`
22-
Callback string `json:"callback_url"`
23-
}
24-
2516
type Token struct {
2617
Token string `json:"token"`
2718
}
@@ -44,10 +35,10 @@ func CreateSubmission(ctx context.Context, question_id uuid.UUID, language_id in
4435

4536
for i, testcase := range testcases {
4637
payload.Submissions[i] = Submission{
47-
SourceCode: b64(source),
38+
SourceCode: B64(source),
4839
LanguageID: language_id,
49-
Input: b64(*testcase.Input),
50-
Output: b64(*testcase.ExpectedOutput),
40+
Input: B64(*testcase.Input),
41+
Output: B64(*testcase.ExpectedOutput),
5142
Callback: callback_url,
5243
}
5344
}
@@ -83,7 +74,3 @@ func GetSubID(ctx context.Context, token string) (string, error) {
8374
}
8475
return subID, nil
8576
}
86-
87-
func b64(data string) string {
88-
return base64.StdEncoding.EncodeToString([]byte(data))
89-
}

internal/server/routes.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ func (s *Server) RegisterRoutes(taskClient *asynq.Client) http.Handler {
1717
r.Use(middleware.Logger)
1818

1919
r.Get("/ping", controllers.HealthCheck)
20-
r.Post("/submit", controllers.SubmitCode)
2120
r.Put("/callback", func(w http.ResponseWriter, r *http.Request) {
2221
controllers.CallbackUrl(w, r, taskClient)
2322
})
@@ -29,6 +28,8 @@ func (s *Server) RegisterRoutes(taskClient *asynq.Client) http.Handler {
2928
protected.Use(jwtauth.Authenticator(auth.TokenAuth))
3029

3130
protected.Get("/protected", controllers.ProtectedHandler)
31+
protected.Post("/submit", controllers.SubmitCode)
32+
protected.Post("/runcode", controllers.RunCode)
3233
protected.With(middlewares.RoleAuthorizationMiddleware("admin")).Post("/question/create", controllers.CreateQuestion)
3334
protected.With(middlewares.RoleAuthorizationMiddleware("admin")).Get("/questions", controllers.GetAllQuestion)
3435
protected.Get("/question/round", controllers.GetQuestionsByRound)

0 commit comments

Comments
 (0)