diff --git a/.vscode/settings.json b/.vscode/settings.json index d3ec034..19d6722 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -2,8 +2,8 @@ "emeraldwalk.runonsave": { "commands": [ { - "match": "api/\\.py$", - "cmd": "./api/bin/isort \"${file}\"" + "match": "\\.py$", + "cmd": "./processor/bin/isort \"${file}\"" } ] } diff --git a/api/src/__api__.py b/api/src/__api__.py deleted file mode 100644 index 64c6d9d..0000000 --- a/api/src/__api__.py +++ /dev/null @@ -1,66 +0,0 @@ -""" -The API endpoints for the proessor -Author: oitsjustjose @ modrinth/curseforge/twitter -""" - -import json -from dataclasses import asdict -from multiprocessing import Process -from os import environ as env - -from flask import Flask, request - -from data import Status -from job_database import Job, JobDb, Status - -app = Flask(__name__) - -db = JobDb(env["MONGO_URI"], int(env["MONGO_PORT"])) - - -@app.route("/jobs/status/", methods=["GET", "POST"]) -def get_job_status(job_id: str) -> str: - "Gets the queue status for a given job" - - status, logs, queue = db.get_job_status(job_id) - if status == Status.ENQUEUED: - return f"Enqueued: {queue} Job(s) Ahead In Queue", 200 - if status == Status.PROCESSING: - return f"Currently Processing\n{logs}", 200 - if status == Status.COMPLETE: - return logs, 200 - return "Failed to find job", 404 - - -@app.route("/jobs/info/", methods=["GET", "POST"]) -def get_job_info(job_id: str): - """Gets the job info for a given uuid""" - job = db.get_job(job_id) - if not job: - return "Failed to find job", 404 - job.github_pat = "" - return json.dumps(asdict(job), indent=2), 200 - - -@app.route("/jobs/new", methods=["POST"]) -def new_job(): - """Creates a new job""" - try: - data = json.loads(request.data) - jobe = Job( - github_pat=data["githubPat"], - curseforge_slug=data["slug"], - modrinth_id=data["projId"], - delimiter=data["delimiter"] if "delimiter" in data else "-", - ) - - # Job already exists in queue, give it back - existing = db.get_existing_queued_job(jobe.curseforge_slug, jobe.modrinth_id) - if existing: - return existing, 200 - return db.enqueue_job(jobe), 200 - except: - return "Internal Server Error", 500 - - -app.run("0.0.0.0", env["PORT"] if "PORT" in env else 3000) diff --git a/backend/.envrc b/backend/.envrc new file mode 100644 index 0000000..a2078c9 --- /dev/null +++ b/backend/.envrc @@ -0,0 +1,3 @@ +export SECRET=krRkGF2rthrT3DScCwXY4Jc_z9ldSQFw32OJt1iKFh0= +export MONGO_URI=localhost +export MONGO_PORT=27017 \ No newline at end of file diff --git a/backend/.gitignore b/backend/.gitignore new file mode 100644 index 0000000..6aeadb2 --- /dev/null +++ b/backend/.gitignore @@ -0,0 +1,29 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# production +/build +/dist + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +yarn.lock + +.vscode/ +.vscode/* \ No newline at end of file diff --git a/backend/Dockerfile b/backend/Dockerfile new file mode 100644 index 0000000..f5751cb --- /dev/null +++ b/backend/Dockerfile @@ -0,0 +1,27 @@ +FROM node:18 AS builder + +WORKDIR /usr/src/app + +COPY package*.json ./ +RUN npm install + +COPY . . + +RUN npm run ts:build + +FROM node:18-alpine AS server + +WORKDIR /usr/src/app +RUN chown -R node:node /usr/src/app + +USER node +EXPOSE 5000 + +COPY package*.json ./ +RUN npm install --production + +COPY --from=0 /usr/src/app/dist dist + +ENV NODE_ENV=production + +CMD ["node", "dist/server.js"] diff --git a/backend/package.json b/backend/package.json new file mode 100644 index 0000000..52c523e --- /dev/null +++ b/backend/package.json @@ -0,0 +1,28 @@ +{ + "name": "ctmmm-api", + "version": "1.0.0", + "main": "index.js", + "license": "MIT", + "dependencies": { + "body-parser": "^1.20.0", + "cors": "^2.8.5", + "express": "^4.18.1", + "fernet-nodejs": "^1.0.4", + "moment": "^2.29.3", + "mongoose": "^7.0.0", + "shortid": "^2.2.16" + }, + "devDependencies": { + "@types/body-parser": "^1.19.2", + "@types/cors": "^2.8.12", + "@types/express": "^4.17.13", + "@types/shortid": "^0.0.29", + "typescript": "^4.7.4" + }, + "scripts": { + "start:live": "yarn run ts:build; concurrently -k -p \"[{name}]\" -n \"TypeScript,Node\" -c \"cyan.bold,green.bold\" \"yarn run ts:watch\" \"yarn run start:serve\"", + "start:serve": "nodemon --inspect dist/server.js", + "ts:build": "tsc", + "ts:watch": "tsc -w" + } +} diff --git a/backend/src/app.ts b/backend/src/app.ts new file mode 100644 index 0000000..dc56774 --- /dev/null +++ b/backend/src/app.ts @@ -0,0 +1,16 @@ +import { json, urlencoded } from "body-parser"; +import cors from "cors"; +import express from "express"; +import GetJob from "./app/controllers/job/get"; +import PutJob from "./app/controllers/job/put"; + +const app = express(); + +app.use(json({ limit: "50mb" })); +app.use(urlencoded({ extended: true })); +app.use(cors()); + +app.post("/api/v1/jobs/:jobId", GetJob); +app.put("/api/v1/jobs", PutJob); + +export default app; diff --git a/backend/src/app/controllers/job/get.ts b/backend/src/app/controllers/job/get.ts new file mode 100644 index 0000000..45fcfab --- /dev/null +++ b/backend/src/app/controllers/job/get.ts @@ -0,0 +1,38 @@ +import { Request, Response } from "express"; +import Jobs from "../../models/Job"; +import Status from "../../status"; + +export default async (req: Request, res: Response) => { + try { + if (!req.params.jobId) { + return res.status(403).send("URL Param for Job ID is required"); + } + + const job = await Jobs.findOne({ job_id: req.params.jobId }); + if (!job) { + return res + .status(404) + .send(`Job with id ${req.params.jobId} was not found`); + } + + // Determine how many items in the queue are ahead of this one + const aheadInQueue = await Jobs.find({ + queue_place: { $lt: job.queuePlace }, + }); + + let text: string = ""; + if (job.status == Status.ENQUEUED) { + text = `Enqueued: ${aheadInQueue.length} Job(s) ahead in queue`; + } else if (job.status == Status.PROCESSING) { + text = `Currently Processing\n${job.logs}`; + } else if (job.status == Status.COMPLETE) { + text = job.logs; + } else { + text = "Could not find job status"; + } + + return res.status(200).send(text); + } catch (ex) { + return res.status(500).json(ex); + } +}; diff --git a/backend/src/app/controllers/job/put.ts b/backend/src/app/controllers/job/put.ts new file mode 100644 index 0000000..c09b883 --- /dev/null +++ b/backend/src/app/controllers/job/put.ts @@ -0,0 +1,49 @@ +import { Request, Response } from "express"; +import Job from "../../models/Job"; +import Status from "../../status"; +import { Fernet } from "fernet-nodejs"; + +const getNextQueuePlace = async () => { + const allActiveJobs = await Job.find({ status: Status.ENQUEUED }).sort({ + queue_place: "desc", + }); + if (allActiveJobs.length) { + return allActiveJobs[0].queuePlace + 1; + } + return 1; +}; + +export default async (req: Request, res: Response) => { + try { + if ( + !req.body.githubPat || + !req.body.curseforgeSlug || + !req.body.modrinthId + ) { + return res + .status(403) + .send( + [ + "Missing a required parameter in the JSON body", + "Required params: githubPat: string, curseforgeSlug: string, modrinthId: string", + ].join(" ") + ); + } + + const fern = new Fernet(process.env.SECRET); + + const newJob = new Job({ + githubPat: fern.encrypt(req.body.githubPat), + curseforgeSlug: req.body.curseforgeSlug, + modrinthId: req.body.modrinthId, + delimiter: req.body.delimiter || "-", + queuePlace: await getNextQueuePlace(), + }); + + await newJob.save(); + return res.status(200).send(newJob.jobId); + } catch (ex) { + console.log(ex); + return res.status(500).send(ex); + } +}; diff --git a/backend/src/app/models/Job.ts b/backend/src/app/models/Job.ts new file mode 100644 index 0000000..34e05c2 --- /dev/null +++ b/backend/src/app/models/Job.ts @@ -0,0 +1,52 @@ +import { Document, model, Schema } from "mongoose"; +import shortid from "shortid"; +import Status from "../status"; + +export type JobType = Document & { + jobId: string; + githubPat: string; + curseforgeSlug: string; + modrinthId: string; + delimiter: string; + logs: string; + status: number; + queuePlace: number; +}; + +const JobSchema = new Schema({ + jobId: { + type: String, + default: shortid.generate, + required: true, + }, + githubPat: { + type: String, + required: true, + }, + curseforgeSlug: { + type: String, + required: true, + }, + modrinthId: { + type: String, + required: true, + }, + delimiter: { + type: String, + required: true, + }, + logs: { + type: String, + default: "", + }, + status: { + type: Number, + default: Status.ENQUEUED, + }, + queuePlace: { + type: Number, + required: true, + }, +}); + +export default model("jobs", JobSchema, "jobs"); diff --git a/backend/src/app/status.ts b/backend/src/app/status.ts new file mode 100644 index 0000000..628a110 --- /dev/null +++ b/backend/src/app/status.ts @@ -0,0 +1,11 @@ +enum Status { + ENQUEUED = 0, + PROCESSING = 1, + COMPLETE = 2, + SUCCESS = 3, + PARTIAL_FAIL = 4, + FAIL = 5, + NOTFOUND = -1, +} + +export default Status; diff --git a/backend/src/db.ts b/backend/src/db.ts new file mode 100644 index 0000000..f732c2f --- /dev/null +++ b/backend/src/db.ts @@ -0,0 +1,7 @@ +import mongoose from "mongoose"; + +export const connectDb = async () => { + await mongoose.connect(`mongodb://${process.env.MONGO_URI}/ctmmm`, { + autoIndex: true, + }); +}; diff --git a/backend/src/server.ts b/backend/src/server.ts new file mode 100644 index 0000000..3387cfd --- /dev/null +++ b/backend/src/server.ts @@ -0,0 +1,8 @@ +import App from "./app"; +import { connectDb } from "./db"; + +(async () => { + await connectDb(); + const port = process.env.PORT || 3030; + App.listen(port, () => console.log(`Listening on http://0.0.0.0:${port}`)); +})(); diff --git a/backend/tsconfig.json b/backend/tsconfig.json new file mode 100644 index 0000000..4597037 --- /dev/null +++ b/backend/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "target": "es2017", + "noImplicitAny": true, + "moduleResolution": "node", + "resolveJsonModule": true, + "sourceMap": true, + "outDir": "dist", + "baseUrl": ".", + "paths": { + "*": ["node_modules/*"] + }, + "lib": ["es2019"] + }, + "include": ["src/**/*", "src/types.d.ts"], + "exclude": ["test/**/*"] +} diff --git a/ctme.code-workspace b/ctme.code-workspace index 10d2b26..0955608 100644 --- a/ctme.code-workspace +++ b/ctme.code-workspace @@ -1,11 +1,14 @@ { - "folders": [ - { - "path": "frontend" - }, - { - "path": "api" - } - ], + "folders": [ + { + "path": "frontend" + }, + { + "path": "backend" + }, + { + "path": "processor" + } + ], "settings": {} -} \ No newline at end of file +} diff --git a/frontend/src/components/OutputLog.jsx b/frontend/src/components/OutputLog.jsx index 36739d9..b0763e1 100644 --- a/frontend/src/components/OutputLog.jsx +++ b/frontend/src/components/OutputLog.jsx @@ -5,7 +5,7 @@ export default ({ id }) => { useEffect(() => { const handle = setInterval(async () => { - const resp = await fetch(`/jobs/status/${id}`); + const resp = await fetch(`/api/v1/jobs/${id}`, { method: 'POST' }); if (resp.ok) { setLogs(await resp.text()); } else { diff --git a/frontend/src/pages/Home.jsx b/frontend/src/pages/Home.jsx index ad9955a..a2c30b8 100644 --- a/frontend/src/pages/Home.jsx +++ b/frontend/src/pages/Home.jsx @@ -25,8 +25,8 @@ export default () => { evt.preventDefault(); if (!isValidState()) return; - const resp = await fetch('/jobs/new', { - method: 'POST', + const resp = await fetch('/api/v1/jobs', { + method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData), }); diff --git a/api/.dockerignore b/processor/.dockerignore similarity index 100% rename from api/.dockerignore rename to processor/.dockerignore diff --git a/api/.gitignore b/processor/.gitignore similarity index 100% rename from api/.gitignore rename to processor/.gitignore diff --git a/api/Dockerfile b/processor/Dockerfile similarity index 100% rename from api/Dockerfile rename to processor/Dockerfile diff --git a/api/README.md b/processor/README.md similarity index 100% rename from api/README.md rename to processor/README.md diff --git a/api/pyvenv.cfg b/processor/pyvenv.cfg similarity index 100% rename from api/pyvenv.cfg rename to processor/pyvenv.cfg diff --git a/api/requirements.txt b/processor/requirements.txt similarity index 100% rename from api/requirements.txt rename to processor/requirements.txt diff --git a/api/src/__main__.py b/processor/src/__main__.py similarity index 93% rename from api/src/__main__.py rename to processor/src/__main__.py index e1bd073..15e3ab1 100644 --- a/api/src/__main__.py +++ b/processor/src/__main__.py @@ -9,8 +9,10 @@ from data import Job, Status from job_database import JobDb from netio_processor import download, upload +job_db = JobDb(env["MONGO_URI"], int(env["MONGO_PORT"])) -def _resume(job_db: JobDb): + +def _resume(): """Resumes processing jobs on server restart""" print("Resuming jobs from last run") @@ -37,7 +39,7 @@ def _resume(job_db: JobDb): ) -def _work(job_db: JobDb) -> bool: +def _work() -> bool: """Does the actual lifting""" job: Job = job_db.get_next_job() if not job: @@ -67,13 +69,13 @@ def _work(job_db: JobDb) -> bool: if __name__ == "__main__": print("Starting the job processor") - job_db = JobDb(env["MONGO_URI"], int(env["MONGO_PORT"])) - _resume(job_db) + _resume() while True: try: - if _work(job_db): + if _work(): sleep(1) else: sleep(5) except KeyboardInterrupt: + print("Quitting..") break diff --git a/api/src/data.py b/processor/src/data.py similarity index 96% rename from api/src/data.py rename to processor/src/data.py index 74a8138..3185445 100644 --- a/api/src/data.py +++ b/processor/src/data.py @@ -4,7 +4,9 @@ Author: oitsjustjose @ modrinth/curseforge/twitter """ from dataclasses import dataclass from enum import Enum -from typing import List, Union + + +from typing import List class Status(Enum): diff --git a/api/src/job_database.py b/processor/src/job_database.py similarity index 78% rename from api/src/job_database.py rename to processor/src/job_database.py index 4d16f73..5f15f59 100644 --- a/api/src/job_database.py +++ b/processor/src/job_database.py @@ -28,7 +28,7 @@ class JobDb: def get_job(self, job_id: str) -> Union[Job, None]: """Gets a job by the job's short ID""" - data: Union[dict, None] = self._coll.find_one({"job_id": job_id}) + data: Union[dict, None] = self._coll.find_one({"jobId": job_id}) if not data: return None return self._dict_to_job(data) @@ -37,7 +37,7 @@ class JobDb: """Gets the next job to do, if any""" data: List[Union[dict, None]] = list( self._coll.find({"status": Status.ENQUEUED.value}) - .sort("queue_place", ASCENDING) + .sort("queuePlace", ASCENDING) .limit(1) ) if data: @@ -45,10 +45,11 @@ class JobDb: return None def get_active_jobs(self) -> List[Job]: + """Gets all active jobs - only used for resuming between restarts""" data: List[Union[dict, None]] = list( - self._coll.find({"status": Status.PROCESSING.value}) - .sort("queue_place", ASCENDING) - .limit(1) + self._coll.find({"status": Status.PROCESSING.value}).sort( + "queuePlace", ASCENDING + ) ) return [self._dict_to_job(x) for x in data] @@ -57,11 +58,11 @@ class JobDb: queue_place = 0 data: List[Union[dict, None]] = list( self._coll.find({"status": Status.ENQUEUED.value}) - .sort("queue_place", DESCENDING) + .sort("queuePlace", DESCENDING) .limit(1) ) if data: - queue_place = data[0]["queue_place"] + 1 + queue_place = data[0]["queuePlace"] + 1 job.queue_place = queue_place job.github_pat = self._fernet.encrypt(job.github_pat.encode()) job.status = job.status.value @@ -76,17 +77,17 @@ class JobDb: update = {"status": status.value} if logs: update["logs"] = logs - self._coll.update_one({"job_id": job_id}, {"$set": update}) + self._coll.update_one({"jobId": job_id}, {"$set": update}) def get_job_status(self, job_id: str) -> Tuple[Status, str, int]: """Gets the status of a job, including queue place and logs""" - data: Union[dict, None] = self._coll.find_one({"job_id": job_id}) + data: Union[dict, None] = self._coll.find_one({"jobId": job_id}) if not data: return (Status.NOTFOUND, [], -1) return ( Status(data["status"]), data["logs"], - data["queue_place"], + data["queuePlace"], ) def get_existing_queued_job(self, slug: str, proj_id: str) -> Union[str, None]: @@ -94,24 +95,24 @@ class JobDb: data: Union[dict, None] = self._coll.find_one( { "status": Status.ENQUEUED.value, - "curseforge_slug": slug, - "modrinth_id": proj_id, + "curseforgeSlug": slug, + "modrinthId": proj_id, } ) print(data) if not data: return None - return data["job_id"] + return data["jobId"] def _dict_to_job(self, data: Dict) -> Job: """Converts a dictionary (from mongo) into a Job""" return Job( - github_pat=self._fernet.decrypt(data["github_pat"].decode()), - curseforge_slug=data["curseforge_slug"], - modrinth_id=data["modrinth_id"], + github_pat=self._fernet.decrypt(data["githubPat"].decode()), + curseforge_slug=data["curseforgeSlug"], + modrinth_id=data["modrinthId"], logs=data["logs"] if "logs" in data else [], - job_id=data["job_id"], + job_id=data["jobId"], delimiter=data["delimiter"] if "delimiter" in data else "-", status=data["status"], - queue_place=data["queue_place"], + queue_place=data["queuePlace"], ) diff --git a/api/src/netio_processor.py b/processor/src/netio_processor.py similarity index 100% rename from api/src/netio_processor.py rename to processor/src/netio_processor.py