Skip to content

Commit 692d907

Browse files
authored
Merge pull request #39 from vaibhavsijaria/main
Runtime Multipliers
2 parents a55612e + f7f58b6 commit 692d907

File tree

7 files changed

+98
-51
lines changed

7 files changed

+98
-51
lines changed

database/schema.sql

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ CREATE TABLE testcases (
4444
memory TEXT,
4545
input TEXT,
4646
hidden BOOLEAN,
47-
runtime TIME,
47+
runtime DECIMAL,
4848
question_id UUID NOT NULL,
4949
PRIMARY KEY(id)
5050
);

internal/controllers/runcode.go

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package controllers
33
import (
44
"bytes"
55
"encoding/json"
6+
"fmt"
67
"net/http"
78
"net/url"
89

@@ -44,11 +45,15 @@ func RunCode(w http.ResponseWriter, r *http.Request) {
4445

4546
testcases, err := database.Queries.GetTestCases(ctx, db.GetTestCasesParams{QuestionID: question_id, Column2: true})
4647
if err != nil {
47-
httphelpers.WriteError(w, http.StatusBadRequest, "Question not found")
48+
httphelpers.WriteError(w, http.StatusBadRequest, fmt.Sprintf("error getting test cases for question_id %d: %v", question_id, err))
4849
return
4950
}
5051

51-
judge0URL, _ := url.Parse(JUDGE0_URI + "/submissions/")
52+
judge0URL, err := url.Parse(JUDGE0_URI + "/submissions/")
53+
if err != nil {
54+
httphelpers.WriteError(w, http.StatusInternalServerError, fmt.Sprintf("Error parsing Judge0 URL: %v", err))
55+
return
56+
}
5257
params := url.Values{}
5358
params.Add("base64_encoded", "true")
5459
params.Add("wait", "true")
@@ -58,25 +63,33 @@ func RunCode(w http.ResponseWriter, r *http.Request) {
5863
response := resp{
5964
Result: make([]submission.Judgeresp, len(testcases)),
6065
}
66+
67+
runtime_mut, err := submission.RuntimeMut(req.LanguageID)
68+
if err != nil {
69+
httphelpers.WriteError(w, http.StatusBadRequest, err.Error())
70+
return
71+
}
72+
6173
for i, testcase := range testcases {
74+
runtime, _ := testcase.Runtime.Float64Value()
6275
payload = submission.Submission{
6376
LanguageID: req.LanguageID,
6477
SourceCode: submission.B64(req.SourceCode),
6578
Input: submission.B64(*testcase.Input),
6679
Output: submission.B64(*testcase.ExpectedOutput),
80+
Runtime: runtime.Float64 * float64(runtime_mut),
6781
}
6882

6983
payloadJSON, err := json.Marshal(payload)
7084
if err != nil {
71-
logger.Errof("Error marshaling payload: %v", err)
72-
httphelpers.WriteError(w, http.StatusInternalServerError, "Unable to marshal payload")
85+
httphelpers.WriteError(w, http.StatusInternalServerError, fmt.Sprintf("error marshaling payload: %v", err))
7386
return
7487
}
7588

7689
result, err := http.Post(judge0URL.String(), "application/json", bytes.NewBuffer(payloadJSON))
7790
if err != nil {
78-
logger.Errof("Error making request to Judge0: %v", err)
79-
httphelpers.WriteError(w, http.StatusInternalServerError, "Error making request to Judge0")
91+
logger.Errof("Error sending request to Judge0: %v", err)
92+
httphelpers.WriteError(w, http.StatusInternalServerError, fmt.Sprintf("Error sending request to Judge0: %v", err))
8093
return
8194
}
8295
defer result.Body.Close()
@@ -85,7 +98,7 @@ func RunCode(w http.ResponseWriter, r *http.Request) {
8598
data.TestCaseID = testcase.ID.String()
8699
if err = json.NewDecoder(result.Body).Decode(&data); err != nil {
87100
logger.Errof("Error decoding response from Judge0: %v", err)
88-
httphelpers.WriteError(w, http.StatusInternalServerError, "Error decoding response from Judge0")
101+
httphelpers.WriteError(w, http.StatusInternalServerError, fmt.Sprintf("Error decoding response from Judge0: %v", err))
89102
return
90103
}
91104

@@ -95,6 +108,6 @@ func RunCode(w http.ResponseWriter, r *http.Request) {
95108
w.Header().Set("Content-Type", "application/json")
96109
if err := json.NewEncoder(w).Encode(response); err != nil {
97110
logger.Errof("Error encoding response: %v", err)
98-
httphelpers.WriteError(w, http.StatusInternalServerError, "Error encoding response")
111+
httphelpers.WriteError(w, http.StatusInternalServerError, fmt.Sprintf("Error encoding response: %v", err))
99112
}
100113
}

internal/controllers/submission.go

Lines changed: 34 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package controllers
33
import (
44
"bytes"
55
"encoding/json"
6+
"fmt"
67
"net/http"
78
"net/url"
89
"os"
@@ -34,65 +35,71 @@ func SubmitCode(w http.ResponseWriter, r *http.Request) {
3435
return
3536
}
3637

37-
question_id, _ := uuid.Parse(req.QuestionID)
38+
userID, _ := auth.GetUserID(w, r)
39+
nullUserID := uuid.NullUUID{UUID: userID, Valid: true}
40+
41+
question_id, err := uuid.Parse(req.QuestionID)
42+
if err != nil {
43+
httphelpers.WriteError(w, http.StatusBadRequest, "Invalid question id, unable to parse it to uuid")
44+
return
45+
}
46+
47+
qualified, err := auth.VerifyRound(ctx, userID, question_id)
48+
if err != nil {
49+
httphelpers.WriteError(w, http.StatusNotFound, err.Error())
50+
return
51+
}
52+
if !qualified {
53+
httphelpers.WriteError(w, http.StatusForbidden, "User is not qualified for this round")
54+
return
55+
}
3856

3957
payload, err := submission.CreateSubmission(ctx, question_id, req.LanguageID, req.SourceCode)
4058
if err != nil {
41-
logger.Errof("Error creating submission: %v", err)
42-
httphelpers.WriteError(w, http.StatusInternalServerError, "Failed to create submission")
59+
httphelpers.WriteError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to create submission payload: %v", err))
4360
return
4461
}
4562

4663
subID, err := uuid.NewV7()
4764
if err != nil {
4865
logger.Errof("Error in generating uuid for submission: %v", err)
49-
httphelpers.WriteError(w, http.StatusInternalServerError, "Error in generating uuid for submission")
66+
httphelpers.WriteError(w, http.StatusInternalServerError, fmt.Sprintf("Error in generating uuid for submission: %v", err))
5067
return
5168
}
5269

53-
judge0URL, _ := url.Parse(JUDGE0_URI + "/submissions/batch")
70+
judge0URL, err := url.Parse(JUDGE0_URI + "/submissions/batch")
71+
if err != nil {
72+
httphelpers.WriteError(w, http.StatusInternalServerError, fmt.Sprintf("Error parsing Judge0 URL: %v", err))
73+
return
74+
}
5475

5576
params := url.Values{}
5677
params.Add("base64_encoded", "true")
5778
judge0URL.RawQuery = params.Encode()
5879
resp, err := http.Post(judge0URL.String(), "application/json", bytes.NewBuffer(payload))
5980
if err != nil {
6081
logger.Errof("Error sending request to Judge0: %v", err)
61-
httphelpers.WriteError(w, http.StatusInternalServerError, "Failed to send request to Judge0")
82+
httphelpers.WriteError(w, http.StatusInternalServerError, fmt.Sprintf("Error sending request to Judge0: %v", err))
6283
return
6384
}
6485
defer resp.Body.Close()
6586

6687
err = submission.StoreTokens(ctx, subID, resp)
6788
if err != nil {
6889
logger.Errof("Error storing tokens for submission ID %s: %v", subID, err)
69-
httphelpers.WriteError(w, http.StatusInternalServerError, "Error storing tokens for the submission")
70-
return
71-
}
72-
73-
userID, _ := auth.GetUserID(w, r)
74-
qID, _ := uuid.Parse(req.QuestionID)
75-
nullUserID := uuid.NullUUID{UUID: userID, Valid: true}
76-
77-
qualified, err := auth.VerifyRound(ctx, userID, qID)
78-
if err != nil {
79-
httphelpers.WriteError(w, http.StatusNotFound, err.Error())
80-
return
81-
}
82-
if !qualified {
83-
httphelpers.WriteError(w, http.StatusForbidden, "User is not qualified for this round")
90+
httphelpers.WriteError(w, http.StatusInternalServerError, fmt.Sprintf("Error storing tokens for submission ID %s: %v", subID, err))
8491
return
8592
}
8693

8794
err = database.Queries.CreateSubmission(ctx, db.CreateSubmissionParams{
8895
ID: subID,
8996
UserID: nullUserID,
90-
QuestionID: qID,
97+
QuestionID: question_id,
9198
LanguageID: int32(req.LanguageID),
9299
})
93100
if err != nil {
94101
logger.Errof("Error creating submission in database: %v", err)
95-
httphelpers.WriteError(w, http.StatusInternalServerError, "Error creating submission in database")
102+
httphelpers.WriteError(w, http.StatusInternalServerError, fmt.Sprintf("Error creating submission in database: %v", err))
96103
return
97104
}
98105

@@ -103,5 +110,8 @@ func SubmitCode(w http.ResponseWriter, r *http.Request) {
103110
SubmissionID: subID.String(),
104111
}
105112
w.Header().Set("Content-Type", "application/json")
106-
_ = json.NewEncoder(w).Encode(respData)
113+
if err := json.NewEncoder(w).Encode(respData); err != nil {
114+
httphelpers.WriteError(w, http.StatusInternalServerError, fmt.Sprintf("Error encoding response: %v", err))
115+
return
116+
}
107117
}

internal/db/models.go

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

internal/helpers/auth/utils.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package auth
22

33
import (
44
"context"
5+
"fmt"
56
"net/http"
67

78
"github.com/CodeChefVIT/cookoff-backend/internal/helpers/database"
@@ -13,19 +14,19 @@ import (
1314
func GetUserID(w http.ResponseWriter, r *http.Request) (uuid.UUID, error) {
1415
_, claims, err := jwtauth.FromContext(r.Context())
1516
if err != nil {
16-
httphelpers.WriteError(w, http.StatusUnauthorized, "unauthorized")
17+
httphelpers.WriteError(w, http.StatusUnauthorized, fmt.Sprintf("unauthorized: %v", err))
1718
return uuid.UUID{}, err
1819
}
1920

2021
userID, ok := claims["user_id"].(string)
2122
if !ok {
22-
httphelpers.WriteError(w, http.StatusUnauthorized, "unauthorized")
23-
return uuid.UUID{}, err
23+
httphelpers.WriteError(w, http.StatusUnauthorized, "unauthorized: user_id not found in claims")
24+
return uuid.UUID{}, fmt.Errorf("user_id not found in claims")
2425
}
2526

2627
userUUID, err := uuid.Parse(userID)
2728
if err != nil {
28-
httphelpers.WriteError(w, http.StatusUnauthorized, "unauthorized")
29+
httphelpers.WriteError(w, http.StatusUnauthorized, fmt.Sprintf("unauthorized: %v", err))
2930
return uuid.UUID{}, err
3031
}
3132

internal/helpers/submission/common.go

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,16 @@ package submission
33
import (
44
"encoding/base64"
55
"encoding/json"
6+
"fmt"
67
)
78

89
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"`
10+
LanguageID int `json:"language_id"`
11+
SourceCode string `json:"source_code"`
12+
Input string `json:"stdin"`
13+
Output string `json:"expected_output"`
14+
Runtime float64 `json:"cpu_time_limit"`
15+
Callback string `json:"callback_url"`
1416
}
1517

1618
type Judgeresp struct {
@@ -41,3 +43,20 @@ func DecodeB64(encoded string) (string, error) {
4143
}
4244
return string(decodedBytes), nil
4345
}
46+
47+
func RuntimeMut(language_id int) (int, error) {
48+
var runtime_mut int
49+
switch language_id {
50+
case 50, 54, 60, 73, 63:
51+
runtime_mut = 1
52+
case 51, 62:
53+
runtime_mut = 2
54+
case 68:
55+
runtime_mut = 3
56+
case 71:
57+
runtime_mut = 5
58+
default:
59+
return 0, fmt.Errorf("invalid language ID: %d", language_id)
60+
}
61+
return runtime_mut, nil
62+
}

internal/helpers/submission/submission.go

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,12 @@ package submission
33
import (
44
"context"
55
"encoding/json"
6-
"errors"
6+
"fmt"
77
"net/http"
88
"os"
99

1010
"github.com/CodeChefVIT/cookoff-backend/internal/db"
1111
"github.com/CodeChefVIT/cookoff-backend/internal/helpers/database"
12-
logger "github.com/CodeChefVIT/cookoff-backend/internal/helpers/logging"
1312
"github.com/google/uuid"
1413
)
1514

@@ -26,26 +25,31 @@ func CreateSubmission(ctx context.Context, question_id uuid.UUID, language_id in
2625

2726
testcases, err := database.Queries.GetTestCases(ctx, db.GetTestCasesParams{QuestionID: question_id, Column2: false})
2827
if err != nil {
29-
logger.Errof("Error getting test cases for question_id %d: %v", question_id, err)
30-
return nil, err
28+
return nil, fmt.Errorf("error getting test cases for question_id %d: %v", question_id, err)
3129
}
3230
payload := Payload{
3331
Submissions: make([]Submission, len(testcases)),
3432
}
3533

34+
runtime_mut, err := RuntimeMut(language_id)
35+
if err != nil {
36+
return nil, err
37+
}
38+
3639
for i, testcase := range testcases {
40+
runtime, _ := testcase.Runtime.Float64Value()
3741
payload.Submissions[i] = Submission{
3842
SourceCode: B64(source),
3943
LanguageID: language_id,
4044
Input: B64(*testcase.Input),
4145
Output: B64(*testcase.ExpectedOutput),
46+
Runtime: runtime.Float64 * float64(runtime_mut),
4247
Callback: callback_url,
4348
}
4449
}
4550
payloadJSON, err := json.Marshal(payload)
4651
if err != nil {
47-
logger.Errof("Error marshaling payload: %v", err)
48-
return nil, err
52+
return nil, fmt.Errorf("error marshaling payload: %v", err)
4953
}
5054

5155
return payloadJSON, nil
@@ -55,13 +59,13 @@ func StoreTokens(ctx context.Context, subID uuid.UUID, r *http.Response) error {
5559
var tokens []Token
5660
err := json.NewDecoder(r.Body).Decode(&tokens)
5761
if err != nil {
58-
return errors.New("Invalid request payload")
62+
return fmt.Errorf("Invalid request payload")
5963
}
6064

6165
for _, t := range tokens {
6266
err := Tokens.AddToken(ctx, t.Token, subID.String())
6367
if err != nil {
64-
return errors.New("Failed to add token")
68+
return fmt.Errorf("Failed to add token")
6569
}
6670
}
6771
return nil

0 commit comments

Comments
 (0)