Skip to content

Commit 10094d2

Browse files
committed
budget fixes
1 parent 8c0e941 commit 10094d2

9 files changed

Lines changed: 257 additions & 47 deletions

File tree

database/queries/submission.sql

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,13 @@ WHERE question_id = $1
1010

1111
-- name: UpdateSubmission :exec
1212
UPDATE submissions
13-
SET testcases_passed = $1, testcases_failed = $2, runtime = $3, memory = $4
14-
WHERE id = $5;
13+
SET
14+
runtime = $1,
15+
memory = $2,
16+
status = $3,
17+
testcases_passed = $4,
18+
testcases_failed = $5
19+
WHERE id = $6;
1520

1621
-- name: UpdateSubmissionStatus :exec
1722
UPDATE submissions
Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
11
-- name: CreateSubmissionStatus :exec
22
INSERT INTO submission_results (id, submission_id, testcase_id ,status ,runtime, memory, description)
3-
VALUES ($1, $2, $3, $4, $5, $6, $7);
3+
VALUES ($1, $2, $3, $4, $5, $6, $7);
4+
5+
-- name: GetStatsForFinalSubEntry :many
6+
SELECT
7+
runtime,
8+
memory,
9+
status
10+
FROM submission_results
11+
WHERE submission_id = $1;

internal/controllers/result.go

Lines changed: 107 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,15 @@ package controllers
22

33
import (
44
"context"
5+
"encoding/json"
6+
"fmt"
7+
"io"
58
"net/http"
9+
"strings"
610
"time"
711

812
httphelpers "github.com/CodeChefVIT/cookoff-backend/internal/helpers/http"
13+
logger "github.com/CodeChefVIT/cookoff-backend/internal/helpers/logging"
914
"github.com/CodeChefVIT/cookoff-backend/internal/helpers/submission"
1015
"github.com/CodeChefVIT/cookoff-backend/internal/helpers/validator"
1116

@@ -54,7 +59,7 @@ func GetResult(w http.ResponseWriter, r *http.Request) {
5459
return
5560
}
5661

57-
ticker := time.NewTicker(5 * time.Second)
62+
ticker := time.NewTicker(20 * time.Second)
5863
defer ticker.Stop()
5964

6065
for {
@@ -64,6 +69,10 @@ func GetResult(w http.ResponseWriter, r *http.Request) {
6469
return
6570

6671
case <-ticker.C:
72+
err := BadCodeAlert(ctx, subid, w)
73+
if err != nil {
74+
return
75+
}
6776
processed, err := submission.CheckStatus(ctx, subid)
6877
if err != nil {
6978
httphelpers.WriteError(w, http.StatusInternalServerError, "Internal server error while getting status")
@@ -83,3 +92,100 @@ func GetResult(w http.ResponseWriter, r *http.Request) {
8392
}
8493

8594
}
95+
96+
type GetStatus struct {
97+
Description string `json:"description"`
98+
ID int `json:"id"`
99+
}
100+
101+
type GetSub struct {
102+
CompileOutput *string `json:"compile_output"`
103+
Memory *int `json:"memory"`
104+
Message *string `json:"message"`
105+
Status GetStatus `json:"status"`
106+
Stderr *string `json:"stderr"`
107+
Stdout *string `json:"stdout"`
108+
Time *string `json:"time"`
109+
Token string `json:"token"`
110+
}
111+
112+
type Response struct {
113+
Submissions []GetSub `json:"submissions"`
114+
}
115+
116+
func BadCodeAlert(ctx context.Context, id uuid.UUID, w http.ResponseWriter) error {
117+
118+
members, err := submission.Tokens.GetTokenMember(ctx, id.String())
119+
if err != nil {
120+
return err
121+
}
122+
123+
if len(members) == 0 {
124+
err := submission.UpdateSubmission(ctx, id)
125+
if err != nil {
126+
fmt.Println("Error parsing JSON:", err)
127+
httphelpers.WriteError(w, http.StatusInternalServerError, "Internal server error!(Failed to update submission table)")
128+
return err
129+
}
130+
return nil
131+
}
132+
133+
var req string = "https://judge0-ce.p.sulu.sh/submissions/batch?tokens=" + strings.Join(members, ",")
134+
fmt.Println("urk :- ", req)
135+
resp, err := submission.BatchGet(req)
136+
if err != nil {
137+
logger.Errof("Error sending request to Judge0: %v", err)
138+
httphelpers.WriteError(
139+
w,
140+
http.StatusInternalServerError,
141+
fmt.Sprintf("Error sending request to Judge0: %v", err),
142+
)
143+
return err
144+
}
145+
defer resp.Body.Close()
146+
respBytes, err := io.ReadAll(resp.Body)
147+
if err != nil {
148+
logger.Errof("Error reading response body from Judge0: %v", err)
149+
httphelpers.WriteError(
150+
w,
151+
http.StatusInternalServerError,
152+
fmt.Sprintf("Error reading response body from Judge0: %v", err),
153+
)
154+
return err
155+
}
156+
157+
if resp.StatusCode != http.StatusOK {
158+
logger.Errof(
159+
"Unexpected status code from Judge0: %d, error: %v",
160+
resp.StatusCode,
161+
string(respBytes),
162+
)
163+
httphelpers.WriteError(w, http.StatusInternalServerError, "Internal server error!")
164+
return err
165+
}
166+
167+
var temp Response
168+
err = json.Unmarshal(respBytes, &temp)
169+
if err != nil {
170+
fmt.Println("Error parsing JSON:", err)
171+
httphelpers.WriteError(w, http.StatusInternalServerError, "Internal server error!(Failed to unmarshal the response)")
172+
return err
173+
}
174+
175+
if count, err := submission.Tokens.GetTokenCount(ctx, id.String()); count == 0 || err != nil {
176+
err := submission.UpdateSubmission(ctx, id)
177+
if err != nil {
178+
fmt.Println("Error parsing JSON:", err)
179+
httphelpers.WriteError(w, http.StatusInternalServerError, "Internal server error!(Failed to update submission table)")
180+
return err
181+
}
182+
}
183+
184+
for _, v := range temp.Submissions {
185+
if v.Status.ID != 1 || v.Status.ID != 2 {
186+
submission.Tokens.DeleteToken(ctx, v.Token)
187+
}
188+
}
189+
190+
return nil
191+
}

internal/db/submission.sql.go

Lines changed: 13 additions & 6 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

internal/db/submission_status.sql.go

Lines changed: 35 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

internal/helpers/submission/common.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,3 +107,20 @@ func SendToJudge0(judge0Url *url.URL, params url.Values, payload []byte) (*http.
107107

108108
return resp, nil
109109
}
110+
111+
func BatchGet(url string) (*http.Response, error) {
112+
judgereq, err := http.NewRequest("GET", url, nil)
113+
if err != nil {
114+
return nil, err
115+
}
116+
judgereq.Header.Add("Content-Type", "application/json")
117+
judgereq.Header.Add("Accept", "application/json")
118+
judgereq.Header.Add("Authorization", fmt.Sprintf("Bearer %v", bearer))
119+
120+
resp, err := http.DefaultClient.Do(judgereq)
121+
if err != nil {
122+
return nil, fmt.Errorf("error sending request to Judge0: %v", err)
123+
}
124+
125+
return resp, nil
126+
}

internal/helpers/submission/result.go

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,18 @@ package submission
33
import (
44
"context"
55
"fmt"
6+
"log"
7+
"math/big"
68

9+
"github.com/CodeChefVIT/cookoff-backend/internal/db"
710
"github.com/CodeChefVIT/cookoff-backend/internal/helpers/database"
811
logger "github.com/CodeChefVIT/cookoff-backend/internal/helpers/logging"
912
"github.com/google/uuid"
13+
"github.com/jackc/pgx/v5/pgtype"
1014
)
1115

16+
const SubmissionDoneStatus = "DONE"
17+
1218
func CheckStatus(ctx context.Context, subid uuid.UUID) (bool, error) {
1319
status, err := database.Queries.GetSubmissionStatusByID(ctx, subid)
1420
if err != nil {
@@ -77,3 +83,47 @@ func GetSubResult(ctx context.Context, subid uuid.UUID) (resultresp, error) {
7783

7884
return resp, nil
7985
}
86+
87+
func UpdateSubmission(ctx context.Context, idUUID uuid.UUID) error {
88+
status := SubmissionDoneStatus
89+
90+
data, err := database.Queries.GetStatsForFinalSubEntry(ctx, idUUID)
91+
if err != nil {
92+
log.Println("Error Fetching submission results: ", err)
93+
return err
94+
}
95+
var runtime float64
96+
var memory int64
97+
var passed, failed int
98+
for _, v := range data {
99+
temp, err := v.Runtime.Float64Value()
100+
if err != nil {
101+
log.Println("Failed to convert runtime to float kms")
102+
return err
103+
}
104+
runtime += temp.Float64
105+
memory += v.Memory.Int.Int64()
106+
if v.Status == "success" {
107+
passed += 1
108+
} else {
109+
failed += 1
110+
}
111+
}
112+
113+
err = database.Queries.UpdateSubmission(ctx, db.UpdateSubmissionParams{
114+
Runtime: pgtype.Numeric{Int: big.NewInt(int64(runtime * 1000)), Valid: true},
115+
Memory: pgtype.Numeric{Int: big.NewInt(int64(memory)), Valid: true},
116+
Status: &status,
117+
TestcasesPassed: pgtype.Int4{Int32: int32(passed), Valid: true},
118+
TestcasesFailed: pgtype.Int4{Int32: int32(failed), Valid: true},
119+
ID: idUUID,
120+
})
121+
122+
if err != nil {
123+
log.Println("Error updating submission: ", err)
124+
return err
125+
}
126+
127+
log.Printf("Submission ID: %v\n", idUUID)
128+
return nil
129+
}

internal/helpers/submission/tokens.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,11 @@ func (tm *TokenManager) GetSubID(ctx context.Context, token string) (string, err
4040
return subID, nil
4141
}
4242

43+
func (tm *TokenManager) GetTokenMember(ctx context.Context, subID string) ([]string, error) {
44+
members, err := tm.client.SMembers(ctx, fmt.Sprintf("sub:%s:tokens", subID)).Result()
45+
return members, err
46+
}
47+
4348
func (tm *TokenManager) GetTokenCount(ctx context.Context, subID string) (int64, error) {
4449
tokenCount, err := tm.client.SCard(ctx, fmt.Sprintf("sub:%s:tokens", subID)).Result()
4550
if err != nil {

0 commit comments

Comments
 (0)