Separate API, proc

This commit is contained in:
oitsjustjose 2023-04-22 23:46:37 -05:00
commit 6a3f531527
27 changed files with 334 additions and 104 deletions

View file

@ -2,8 +2,8 @@
"emeraldwalk.runonsave": {
"commands": [
{
"match": "api/\\.py$",
"cmd": "./api/bin/isort \"${file}\""
"match": "\\.py$",
"cmd": "./processor/bin/isort \"${file}\""
}
]
}

View file

@ -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/<job_id>", 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/<job_id>", 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)

3
backend/.envrc Normal file
View file

@ -0,0 +1,3 @@
export SECRET=krRkGF2rthrT3DScCwXY4Jc_z9ldSQFw32OJt1iKFh0=
export MONGO_URI=localhost
export MONGO_PORT=27017

29
backend/.gitignore vendored Normal file
View file

@ -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/*

27
backend/Dockerfile Normal file
View file

@ -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"]

28
backend/package.json Normal file
View file

@ -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"
}
}

16
backend/src/app.ts Normal file
View file

@ -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;

View file

@ -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);
}
};

View file

@ -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);
}
};

View file

@ -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<JobType>({
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<JobType>("jobs", JobSchema, "jobs");

11
backend/src/app/status.ts Normal file
View file

@ -0,0 +1,11 @@
enum Status {
ENQUEUED = 0,
PROCESSING = 1,
COMPLETE = 2,
SUCCESS = 3,
PARTIAL_FAIL = 4,
FAIL = 5,
NOTFOUND = -1,
}
export default Status;

7
backend/src/db.ts Normal file
View file

@ -0,0 +1,7 @@
import mongoose from "mongoose";
export const connectDb = async () => {
await mongoose.connect(`mongodb://${process.env.MONGO_URI}/ctmmm`, {
autoIndex: true,
});
};

8
backend/src/server.ts Normal file
View file

@ -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}`));
})();

20
backend/tsconfig.json Normal file
View file

@ -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/**/*"]
}

View file

@ -1,11 +1,14 @@
{
"folders": [
{
"path": "frontend"
},
{
"path": "api"
}
],
"folders": [
{
"path": "frontend"
},
{
"path": "backend"
},
{
"path": "processor"
}
],
"settings": {}
}
}

View file

@ -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 {

View file

@ -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),
});

View file

@ -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

View file

@ -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):

View file

@ -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"],
)