-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgrading.ts
More file actions
178 lines (153 loc) · 5.4 KB
/
Copy pathgrading.ts
File metadata and controls
178 lines (153 loc) · 5.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import {
FirestoreCollection,
GradingJobStatus,
PermissionRole,
} from "@app-portal/shared/constants";
import type { GradingJobDataInternal } from "@app-portal/shared/types";
import { submitGradingJobSchema } from "@app-portal/shared/types";
import type { Response, Request } from "express";
import { Router } from "express";
import { Timestamp } from "firebase-admin/firestore";
import { logger } from "firebase-functions";
import { v4 as uuidv4 } from "uuid";
import { db } from "../index";
import {
isAuthenticated,
hasRoles,
getUserById,
} from "../middleware/authentication";
import { validateSchema } from "../middleware/validation";
import type { ApplicationResponse } from "../models/appResponse";
import type { GradingJobPublic } from "../models/autograder";
import { publishGradingTask } from "../utils/cloudTasks";
import { appCollection } from "../utils/firestore";
const router = Router();
router.post(
"/submit",
[
isAuthenticated,
hasRoles([
PermissionRole.Applicant,
PermissionRole.Board,
PermissionRole.SuperReviewer,
]),
validateSchema(submitGradingJobSchema),
],
async (req: Request, res: Response) => {
try {
const { responseId, repoURL } = req.body;
const userId = req.token?.uid;
const user = await getUserById(userId ?? "");
if (!userId || !user) {
return res.status(401).send("Unauthorized");
}
logger.info(`Received autograder request for responseId ${responseId}`);
const applicationResponseCollection = appCollection(
FirestoreCollection.ApplicationResponses,
);
const gradingJobsPublicCollection = appCollection(
FirestoreCollection.GradingJobsPublic,
);
const gradingJobsInternalCollection = appCollection(
FirestoreCollection.GradingJobsInternal,
);
const responseDoc = await applicationResponseCollection
.doc(responseId)
.get();
if (!responseDoc.exists) {
logger.warn(`Response ${responseId} not found`);
return res.status(404).send("Application response not found");
}
const responseData: ApplicationResponse | undefined = responseDoc.data();
if (!responseData) {
logger.warn(
`Attempted to retrieve response with id: ${responseId} unsuccessfully`,
);
return res.status(404).send("Application response not found");
}
const isOwner = responseData.userId === userId;
const isAdmin = [
PermissionRole.Board,
PermissionRole.SuperReviewer,
].includes(user.role);
if (!isOwner && !isAdmin) {
logger.warn(
`User ${userId} attempted to submit grading for response ${responseId} they don't own`,
);
return res
.status(403)
.send(
"You do not have permission to submit an autograder request for this application",
);
}
const jobId = uuidv4();
const now = Timestamp.now();
const testRepo = "https://github.com/Hack4Impact-UMD/FAKE_REPO"; // TODO: replace with real repo
// NOTE: cloud tasks publishing is outside this transaction right now, so docs may be created and left even if publish fails
const duplicateFound = await db.runTransaction(async (transaction) => {
// validation: exit if user has existing running job
const existingJobsSnapshot = await transaction.get(
gradingJobsPublicCollection.where("responseId", "==", responseId),
);
const runningJobs = existingJobsSnapshot.docs.filter((doc) => {
const status = doc.data().status;
return (
status !== GradingJobStatus.Completed &&
status !== GradingJobStatus.Failed
);
});
if (runningJobs.length > 0) {
return true;
}
// create: job docs and cloud tasks job
const publicJob: GradingJobPublic = {
id: jobId,
responseId,
repoURL,
status: GradingJobStatus.Queued,
score: 0,
totalTests: 0, // TODO: fetch to real repo's # of tests
completedTests: 0,
started: now,
updated: now,
suiteResults: {},
publicTests: {},
};
const internalJob: GradingJobDataInternal = {
id: jobId,
testRepo,
buildLog: "",
installLog: "",
playwrightLog: "",
tests: {},
};
transaction.set(gradingJobsPublicCollection.doc(jobId), publicJob);
transaction.set(gradingJobsInternalCollection.doc(jobId), internalJob);
return false;
});
if (duplicateFound) {
logger.info(`Found existing running job for response ${responseId}`);
return res
.status(409)
.send("A grading job is already in progress for this application.");
}
logger.info(`Created Firestore documents for job ${jobId}`);
const taskName = await publishGradingTask({
jobId,
responseId,
repoURL,
testRepo,
});
logger.info(`Successfully published task ${taskName} for job ${jobId}`);
return res.status(200).json({
status: "success",
message: "Grading job queued successfully",
jobId,
});
} catch (error) {
logger.error("Failed to submit grading job:", error);
return res.status(500).send("Failed to submit grading job");
}
},
);
export default router;