From e2d728265b7ab600dad39895f80c40372b9cb818 Mon Sep 17 00:00:00 2001 From: JBB0807 <104856796+JBB0807@users.noreply.github.com> Date: Wed, 7 May 2025 11:43:16 -0700 Subject: [PATCH 1/4] improved database updates for assignment creation --- assignment-db-service/app.js | 6 ++ assignment-service/routes/InstructorRouter.js | 73 +++++++++++--- auth-service/.env | 3 +- auth-service/.env.development | 1 + auth-service/passport.js | 16 +++- auth-service/routes/auth.js | 95 ++++++++++++------- auth-service/server.js | 51 ++++++---- deployment-service/src/index.js | 58 +++++++---- 8 files changed, 211 insertions(+), 92 deletions(-) diff --git a/assignment-db-service/app.js b/assignment-db-service/app.js index 91d19be..bfb2fbd 100644 --- a/assignment-db-service/app.js +++ b/assignment-db-service/app.js @@ -192,13 +192,17 @@ app.get("/assignments/appname/:appName", async (req, res) => { app.put("/assignments/:id", async (req, res) => { try { const { id } = req.params; + console.log("Updating assignment with ID:", id); + const assignment = await convertToAssignment(req); + console.log("Converted assignment object for update:", assignment); const existingAssignment = await prisma.assignments.findUnique({ where: { assignmentid: parseInt(id) }, }); if (!existingAssignment) { + console.log("No existing assignment found for ID:", id); return res.status(404).json({ message: "Assignment not found" }); } @@ -216,6 +220,8 @@ app.put("/assignments/:id", async (req, res) => { data: existingAssignment, }); + console.log("Assignment updated successfully:", updatedAssignment); + res.json({ message: "Assignment updated successfully", assignment: updatedAssignment, diff --git a/assignment-service/routes/InstructorRouter.js b/assignment-service/routes/InstructorRouter.js index 22777ca..73b7eb5 100644 --- a/assignment-service/routes/InstructorRouter.js +++ b/assignment-service/routes/InstructorRouter.js @@ -29,12 +29,17 @@ intructorRouter.post( return res.status(400).send("No file uploaded."); } + //insert the initial assignment data into the database console.log("Creating a new assignment with data:", req.body); - const response = await axios.post( + const dbResponse = await axios.post( `${DB_ASSIGNMENT_SERVICE_URL}/assignments`, req.body ); - console.log("Response from DB_ASSIGNMENT_SERVICE_URL:", response.data); + + const assignmentId = dbResponse.data.assignment.assignmentid; + console.log("Assignment created with ID:", assignmentId); + + console.log("Response from DB_ASSIGNMENT_SERVICE_URL:", dbResponse.data); // call upload api to upload the file to S3 console.log("Uploading file to:", `${DEPLOY_API_URL}/${assignmentData.appname}/upload`); @@ -53,9 +58,48 @@ intructorRouter.post( }); console.log('Response from DEPLOY_API_URL:', deployResponse.data); - res.status(response.status).json(response.data); + const ipv6 = deployResponse.data.ipv6; + console.log("Deployed Battlesnake API IPv6:", ipv6); + + // Update the assignment with the deployment details + const updatedAssignmentData = { + assignmenturl: ipv6, + } + console.log("Updating assignment with deployment details:", updatedAssignmentData); + const updateRespone = await axios.put( + `${DB_ASSIGNMENT_SERVICE_URL}/assignments/${assignmentId}`, + updatedAssignmentData + ); + + console.log("Response from DB_ASSIGNMENT_SERVICE_URL:", updateRespone.data); + + res.status(deployResponse.status).json(deployResponse.data); } catch (error) { console.error("Error creating assignment:", error.message); + //delete the file from s3 and the database if the assignment creation fails + try { + console.log("Deleting file from S3 due to error in assignment creation"); + await axios.post(`${DEPLOY_API_URL}/${req.body.appname}/delete`, { + "appName": req.body.appname + }); + + console.log('Response from DEPLOY_API_URL:', error.response.data); + } catch (deleteError) { + console.error("Error deleting file from S3:", deleteError.message); + } + //delete the assignment from the database + try { + console.log("Deleting assignment from database due to error in assignment creation"); + await axios.delete( + `${DB_ASSIGNMENT_SERVICE_URL}/assignments/${assignmentId}` + ); + } catch (deleteError) { + console.error("Error deleting assignment from database:", deleteError.message); + } + //send the error response to the client + console.error("Error response from DB_ASSIGNMENT_SERVICE_URL:", error.response.data); + console.error("Error response status:", error.response.status); + res.status(error.response?.status || 500).json({ error: error.message }); } } @@ -148,17 +192,20 @@ intructorRouter.delete( } // Delete the Battlesnake API - console.log('Deploying a new Battlesnake API'); - console.log("DEPLOY_API_URL:", DEPLOY_API_URL, assignmentData.appname); - const deployResponse = await axios.post(`${DEPLOY_API_URL}/${assignmentData.appname}/delete`, { - "appName": assignmentData.appname - }); - //throw error if the response is not 200 - if (deployResponse.status !== 200) { - throw new Error(`Failed to delete Battlesnake API: ${deployResponse.statusText}`); + if(assignmentData.appname){ + console.log(`Deleting Battlesnake API: ${assignmentData.appname}`); + console.log("DEPLOY_API_URL:", DEPLOY_API_URL, assignmentData.appname); + const deployResponse = await axios.post(`${DEPLOY_API_URL}/${assignmentData.appname}/delete`, { + "appName": assignmentData.appname + }); + //throw error if the response is not 200 + console.log('Response from DEPLOY_API_URL:', deployResponse.data); + if (deployResponse.status !== 200) { + throw new Error(`Failed to delete Battlesnake API: ${deployResponse.statusText}`); + } + console.log('Response from DEPLOY_API_URL:', deployResponse.data); } - console.log('Response from DEPLOY_API_URL:', deployResponse.data); - + const response = await axios.delete( `${DB_ASSIGNMENT_SERVICE_URL}/assignments/${assignmentId}` ); diff --git a/auth-service/.env b/auth-service/.env index 75d4e76..5c3c27a 100644 --- a/auth-service/.env +++ b/auth-service/.env @@ -2,10 +2,11 @@ GOOGLE_CLIENT_ID = "485880105639-1in8tvb6ondnn198rasuj2d8ank06ntp.apps.googleuse GOOGLE_CLIENT_SECRET = "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" GOOGLE_CALLBACK_URL = "https://byte-camp-auth-service.fly.dev/auth/google/callback" LOGIN_REDIRECT_URL = "https://bytecamp-web.fly.dev/" -ACCEPTED_ORIGINS ="https://bytecamp-web.fly.dev,https://byte-camp-auth-service.fly.dev,http://localhost:5173" +ACCEPTED_ORIGINS ="https://bytecamp-web.fly.dev,https://byte-camp-auth-service.fly.dev,https://bytecamp-web.fly.dev/" #DB_USER_SERVICE_URL = "http://localhost:3000/" DB_USER_SERVICE_URL = "http://db-user-service.internal:3000/" AUTH_SESSION_KEY = "f3f4d8e6b17a4b3abdc8e9a2c0457aaf91c0d5f6e3b7a9c8df624bd71ea35f42" +AUTH_URL = "https://byte-camp-auth-service.fly" ASSIGNMENT_SERVICE_URL="http://assignment-service.internal:8080" # fly secrets set GOOGLE_CALLBACK_URL=https://byte-camp-auth-service.fly.dev/auth/google/callback diff --git a/auth-service/.env.development b/auth-service/.env.development index 5fd061d..de2aacf 100644 --- a/auth-service/.env.development +++ b/auth-service/.env.development @@ -8,4 +8,5 @@ ACCEPTED_ORIGINS=http://localhost:3000,http://localhost:8081,http://localhost:30 ASSIGNMENT_SERVICE_URL="http://localhost:8082" DB_USER_SERVICE_URL="http://localhost:3100/" AUTH_SESSION_KEY="f3f4d8e6b17a4b3abdc8e9a2c0457aaf91c0d5f6e3b7a9c8df624bd71ea35f42" +AUTH_URL = "http://localhost:8080" PORT=8080 \ No newline at end of file diff --git a/auth-service/passport.js b/auth-service/passport.js index e04adb9..39479de 100644 --- a/auth-service/passport.js +++ b/auth-service/passport.js @@ -5,6 +5,8 @@ const passport = require("passport"); const CustomStrategy = require("passport-custom").Strategy; const axios = require("axios"); + + passport.use( new GoogleStrategy( { @@ -14,7 +16,11 @@ passport.use( scope: ["profile", "email"], }, function (accessToken, refreshToken, profile, callback) { - callback(null, {...profile, role: "instructor"}); + // console.log("Google Strategy invoked"); + // console.log("Access Token:", accessToken); + // console.log("Refresh Token:", refreshToken); + // console.log("Profile:", profile); + callback(null, { ...profile, role: "instructor" }); } ) ); @@ -57,19 +63,19 @@ passport.use( ); passport.serializeUser((user, done) => { - // done(null, user); console.log("Serializing user:", user); + // done(null, user); done(null, { userId: user.qrcodenumber || user.id, displayName: user.studentname || user.displayName, role: user.role, - emails: user.emails || "none", + // emails: user.emails || "none", }); }); -passport.deserializeUser(async (user, done) => { +passport.deserializeUser((user, done) => { + console.log("Deserializing user:", user); try { - console.log("Deserializing user:", user); done(null, user); } catch (err) { console.error("Error during deserialization:", err); diff --git a/auth-service/routes/auth.js b/auth-service/routes/auth.js index 05d5f63..88a0309 100644 --- a/auth-service/routes/auth.js +++ b/auth-service/routes/auth.js @@ -2,12 +2,43 @@ const router = require("express").Router(); const passport = require("passport"); const axios = require("axios"); +const AUTH_URL = process.env.AUTH_URL || "http://localhost:8080"; + router.get( "/google/callback", passport.authenticate("google", { - successRedirect: "/auth/google/login", failureRedirect: "/auth/login/failed", - }) + keepSessionInfo: true, + }), + async (req, res) => { + console.log("Google callback endpoint hit"); + if (req.user) { + console.log(`${process.env.DB_USER_SERVICE_URL}instructor/register-user`); + axios + .post(`${process.env.DB_USER_SERVICE_URL}instructor/register-user`, { + user: req.user, + }) + .then((response) => { + req.user.userId = response.data.user.userid; + console.log("User ID:", response.data.user.userid); + req.user.role = "instructor"; + console.log("User registration response:", response.data); + req.login(req.user, (err) => { + if (err) { + console.error("Login error:", err); + return res.status(500).send("Login failed"); + } + return res.redirect(process.env.LOGIN_REDIRECT_URL); + }); + }) + .catch((error) => { + console.error("Error registering user:", error.message); + res.status(500).json({ error: true, message: "User login failed" }); + }); + } else { + res.status(403).json({ error: true, message: "Not Authorized" }); + } + } ); router.get("/current_user", (req, res) => { @@ -22,28 +53,28 @@ router.get("/current_user", (req, res) => { } }); -router.get("/google/login", (req, res) => { - if (req.user) { - console.log(`${process.env.DB_USER_SERVICE_URL}instructor/register-user`); - axios - .post(`${process.env.DB_USER_SERVICE_URL}instructor/register-user`, { - user: req.user, - }) - .then((response) => { - req.user.userId = response.data.user.userid; - console.log("User ID:", response.data.user.userid); - req.user.role = "instructor"; - console.log("User registration response:", response.data); - res.redirect(process.env.LOGIN_REDIRECT_URL); - }) - .catch((error) => { - console.error("Error registering user:", error.message); - res.status(500).json({ error: true, message: "User login failed" }); - }); - } else { - res.status(403).json({ error: true, message: "Not Authorized" }); - } -}); +// router.get("/google/login", (req, res) => { +// if (req.user) { +// console.log(`${process.env.DB_USER_SERVICE_URL}instructor/register-user`); +// axios +// .post(`${process.env.DB_USER_SERVICE_URL}instructor/register-user`, { +// user: req.user, +// }) +// .then((response) => { +// req.user.userId = response.data.user.userid; +// console.log("User ID:", response.data.user.userid); +// req.user.role = "instructor"; +// console.log("User registration response:", response.data); +// res.redirect(process.env.LOGIN_REDIRECT_URL); +// }) +// .catch((error) => { +// console.error("Error registering user:", error.message); +// res.status(500).json({ error: true, message: "User login failed" }); +// }); +// } else { +// res.status(403).json({ error: true, message: "Not Authorized" }); +// } +// }); router.get("/login/failed", (req, res) => { res.status(401).json({ @@ -56,7 +87,7 @@ router.get("/google", passport.authenticate("google", ["profile", "email"])); router.post( "/student/login", - passport.authenticate("student-auth"), + passport.authenticate("student-auth", { keepSessionInfo: true }), (req, res) => { console.log("Student login endpoint hit"); @@ -68,18 +99,17 @@ router.post( req.user.userId = req.user.assignmentid; req.user.role = "student"; - req.logIn(req.user, function(err) { + req.logIn(req.user, function (err) { if (err) return next(err); - - console.log('is authenticated?: ' + req.isAuthenticated()); - + + console.log("is authenticated?: " + req.isAuthenticated()); + return res.status(200).json({ success: true, - message: 'Successful Login', - user: req.user + message: "Successful Login", + user: req.user, }); }); - } else { console.log("Authentication failed"); res.status(401).json({ error: true, message: "Authentication failed" }); @@ -88,7 +118,6 @@ router.post( ); router.get("/logout", (req, res) => { - req.logout((err) => { if (err) { return next(err); diff --git a/auth-service/server.js b/auth-service/server.js index 924dfac..5f5a393 100644 --- a/auth-service/server.js +++ b/auth-service/server.js @@ -1,4 +1,4 @@ -require('dotenv').config(); +require("dotenv").config(); const cors = require("cors"); const express = require("express"); @@ -9,35 +9,46 @@ const session = require("express-session"); const bodyParser = require("body-parser"); const app = express(); -app.use(bodyParser.json()); // or express.json() +app.use(express.json()); app.use(bodyParser.urlencoded({ extended: true })); +// console.log("AUTH_URL:", process.env.AUTH_URL); +const isProduction = process.env.NODE_ENV === "production"; app.use( - - session({ - secret: process.env.AUTH_SESSION_KEY, - resave: false, - saveUninitialized: false, - cookie: { - maxAge: 24 * 60 * 60 * 1000, // 1 day - }, - }) + session({ + secret: process.env.AUTH_SESSION_KEY, + resave: false, + saveUninitialized: false, + cookie: { + maxAge: 24 * 60 * 60 * 1000, // 1 day + //keep production security settings below disable for the mean-time because we need to integrate redis session for cross-origin to work properly + //sameSite: isProduction ? "none" : "lax", // or 'none' if using cross-origin + //secure: isProduction, // only true in production over HTTPS + }, + }) ); app.use(passport.initialize()); app.use(passport.session()); -app.use( - cors({ - origin: process.env.ACCEPTED_ORIGINS.split(","), - methods: ["GET", "POST"], - credentials: true, - }) -) +const allowedOrigins = process.env.ACCEPTED_ORIGINS.split(","); -app.use(express.json()); +const corsOptions = { + origin: function (origin, callback) { + if (!origin || allowedOrigins.includes(origin)) { + callback(null, origin); // allow the request + } else { + callback(new Error("Not allowed by CORS")); + } + }, + methods: ["GET", "POST", "OPTIONS"], + allowedHeaders: ["Content-Type", "Authorization"], + credentials: true, +}; + +app.use(cors(corsOptions)); app.use("/auth", authRoute); const port = process.env.PORT || 8080; -app.listen(port, () => console.log(`Listening on port ${port}...`)); \ No newline at end of file +app.listen(port, () => console.log(`Listening on port ${port}...`)); diff --git a/deployment-service/src/index.js b/deployment-service/src/index.js index 1467d13..3551744 100644 --- a/deployment-service/src/index.js +++ b/deployment-service/src/index.js @@ -91,13 +91,6 @@ app.post("/deploy", async (req, res) => { return res.status(400).json({ error: "appName required" }); } - // const notebookPath = path.join(__dirname, '../snakeapi_service/notebooks', notebookName); - // console.log('Resolved notebookPath:', notebookPath); - // if (!fs.existsSync(notebookPath)) { - // console.error('Notebook not found at:', notebookPath); - // return res.status(500).json({ error: `Notebook not found: ${notebookPath}` }); - // } - try { const fly = createFlyClient(); @@ -108,17 +101,6 @@ app.post("/deploy", async (req, res) => { primary_region: "sea", }); - // console.log('Uploading notebook to S3'); - // const data = fs.readFileSync(notebookPath); - // const key = `${appName}/notebooks/${Date.now()}-notebook.ipynb`; - // console.log('S3 key:', key); - // await s3.putObject({ - // Bucket: COMMON_BUCKET, - // Key: key, - // Body: data, - // ContentType: 'application/json' - // }).promise(); - console.log("Creating machine"); const machineConfig = { name: `${appName}-machine`, @@ -237,12 +219,23 @@ app.post("/:appName/delete", async (req, res) => { try { const fly = createFlyClient(); console.log("Destroying Fly app:", appName); + + //check if the app exists + console.log("Checking if app exists:", appName); + const appCheck = await fly.get(`/apps/${appName}`); + console.log("App check response:", appCheck.status); + if (appCheck.status !== 200) { + console.log("App not found:", appName); + return res.json({ status: "App not found", app: appName }); + } + await fly.delete(`/apps/${appName}`); return res.json({ status: "deleted", app: appName }); } catch (err) { - console.error("App deletion error:", err.response?.data || err.message); - return res.status(500).json({ error: err.response?.data || err.message }); + const errorData = err.response?.data || err.stack || err.message; + console.error("App deletion error:", errorData); + return res.status(500).json({ errorData }); } }); @@ -250,3 +243,28 @@ const LISTEN_PORT = process.env.PORT || 3006; app.listen(LISTEN_PORT, "0.0.0.0", () => { console.log(`Deployment service listening on port ${LISTEN_PORT}`); }); + +//deploy fly app based on appname +app.post("/deploy/:appName", async (req, res) => { + const { appName } = req.params; + const { region } = req.body; + + if (!appName || !region) { + return res.status(400).json({ error: "appName and region are required" }); + } + + try { + const fly = createFlyClient(); + console.log("Creating Fly app:", appName); + await fly.post("/apps", { + app_name: appName, + org_slug: FLY_ORG, + primary_region: region, + }); + + return res.json({ status: "created", app: appName }); + } catch (err) { + console.error("App creation error:", err.response?.data || err.message); + return res.status(500).json({ error: err.response?.data || err.message }); + } +}); From 372120e83524e11d4aa8fd6a5baa24762b9411f4 Mon Sep 17 00:00:00 2001 From: JBB0807 <104856796+JBB0807@users.noreply.github.com> Date: Wed, 7 May 2025 14:11:19 -0700 Subject: [PATCH 2/4] Update environment variables --- assignment-db-service/.env.test | 2 +- assignment-service/.env.test | 4 ++-- auth-service/.env.test | 12 ++++++++++++ auth-service/passport.js | 2 +- compose.yaml | 22 ++++++++++++++++++---- deployment-service/.env.test | 9 +++++++++ user-db-service/.env.development | 2 +- user-db-service/.env.test | 12 ++++++++++++ 8 files changed, 56 insertions(+), 9 deletions(-) create mode 100644 auth-service/.env.test create mode 100644 deployment-service/.env.test create mode 100644 user-db-service/.env.test diff --git a/assignment-db-service/.env.test b/assignment-db-service/.env.test index b464239..048a45c 100644 --- a/assignment-db-service/.env.test +++ b/assignment-db-service/.env.test @@ -1,4 +1,4 @@ -NODE_ENV=development +NODE_ENV=docker # Environment variables declared in this file are automatically made available to Prisma. # See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema diff --git a/assignment-service/.env.test b/assignment-service/.env.test index fd1e4e1..2c83b66 100644 --- a/assignment-service/.env.test +++ b/assignment-service/.env.test @@ -1,4 +1,4 @@ -NODE_ENV=test +NODE_ENV=docker DB_ASSIGNMENT_SERVICE_URL="http://js-assignment-db-service:3200" -DEPLOY_API_URL="http://localhost:3006/deploy" +DEPLOY_API_URL="http://js-deployment-service:3006/deploy" NODE_PORT=8082 \ No newline at end of file diff --git a/auth-service/.env.test b/auth-service/.env.test new file mode 100644 index 0000000..3787375 --- /dev/null +++ b/auth-service/.env.test @@ -0,0 +1,12 @@ +NODE_ENV=docker + +GOOGLE_CLIENT_ID="485880105639-1in8tvb6ondnn198rasuj2d8ank06ntp.apps.googleusercontent.com" +GOOGLE_CLIENT_SECRET="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" +GOOGLE_CALLBACK_URL="http://localhost:8080/auth/google/callback" +LOGIN_REDIRECT_URL="http://localhost:5173/" +ACCEPTED_ORIGINS=http://localhost:3000,http://localhost:8081,http://localhost:3001,http://localhost:5173 +ASSIGNMENT_SERVICE_URL="http://js-assignment-service:8082" +DB_USER_SERVICE_URL="http://js-user-db-service:3100/" +AUTH_SESSION_KEY="f3f4d8e6b17a4b3abdc8e9a2c0457aaf91c0d5f6e3b7a9c8df624bd71ea35f42" +AUTH_URL = "http://localhost:8080" +PORT=8080 \ No newline at end of file diff --git a/auth-service/passport.js b/auth-service/passport.js index 39479de..14f3481 100644 --- a/auth-service/passport.js +++ b/auth-service/passport.js @@ -66,7 +66,7 @@ passport.serializeUser((user, done) => { console.log("Serializing user:", user); // done(null, user); done(null, { - userId: user.qrcodenumber || user.id, + userId: user.qrcodenumber || user.userId, displayName: user.studentname || user.displayName, role: user.role, // emails: user.emails || "none", diff --git a/compose.yaml b/compose.yaml index 41c59e6..46bf230 100644 --- a/compose.yaml +++ b/compose.yaml @@ -11,7 +11,7 @@ services: ports: - "3200:3200" # Expose port to the same host env_file: - - ./assignment-db-service/.env.development + - ./assignment-db-service/.env.test networks: - backend @@ -25,7 +25,7 @@ services: ports: - "8082:8082" # Expose port to the same host env_file: - - ./assignment-service/.env.development + - ./assignment-service/.env.test depends_on: - js-assignment-db-service networks: @@ -41,7 +41,7 @@ services: ports: - "8080:8080" # Expose port to the same host env_file: - - ./auth-service/.env.development + - ./auth-service/.env.test networks: - backend @@ -55,7 +55,21 @@ services: ports: - "3100:3100" # Expose port to the same host env_file: - - ./user-db-service/.env.development + - ./user-db-service/.env.test + networks: + - backend + + js-deployment-service: + build: + context: ./deployment-service + dockerfile: DockerfileDEV + container_name: js-deployment-service + restart: unless-stopped + init: true + ports: + - "3100:3100" # Expose port to the same host + env_file: + - ./deployment-service/.env.test networks: - backend diff --git a/deployment-service/.env.test b/deployment-service/.env.test new file mode 100644 index 0000000..8c0e809 --- /dev/null +++ b/deployment-service/.env.test @@ -0,0 +1,9 @@ +NODE_ENV=docker +FLY_ACCESS_TOKEN="FlyV1 fm2_lJPECAAAAAAACJJHxBAjRF69RAjf3FXXuVT+M3bcwrVodHRwczovL2FwaS5mbHkuaW8vdjGUAJLOAA//nh8Lk7lodHRwczovL2FwaS5mbHkuaW8vYWFhL3YxxDxmIdNTu/DGjUSyYxuC5W7Rio4bNT5w6c1Ihi+ZJnjcmEutbt5KuyFcCo1C0CFPEhrP4hY5SEvXN58GHUDEToWZ0GwI5ndmIsZnhWSG8TBixbuFTaBb8lTBU5lNOvm2l4rX1i6dfId7S9Ko6qXpOzl9oYngy0zw+g2MwXuQrH6/XELBdEy/KThVeTEjt8QgBzOo/Eae+DsrATm6WjVv9f5a4iS/s7WtYHydZZr3z9M=,fm2_lJPEToWZ0GwI5ndmIsZnhWSG8TBixbuFTaBb8lTBU5lNOvm2l4rX1i6dfId7S9Ko6qXpOzl9oYngy0zw+g2MwXuQrH6/XELBdEy/KThVeTEjt8QQNZaUoOrVdOnk6Vo/DkeMGsO5aHR0cHM6Ly9hcGkuZmx5LmlvL2FhYS92MZgEks5oGwzFzwAAAAEkEyrjF84AD2FZCpHOAA9hWQzEEASQrBHkPDFO3LlZDaxRRIjEIEW1ki/syKHnhFamHgze8PFeunPOAmNmh57hslV04lL7" +AWS_ACCESS_KEY_ID='tid__NSmOVaGknqitaCySppZjqVTgJSdDFnFbWcQllkC_juHwkbQZO' +AWS_ENDPOINT_URL_S3='https://fly.storage.tigris.dev' +AWS_REGION='auto' +AWS_SECRET_ACCESS_KEY='tsec_6Bz1aMbfYQftuq5WfIVEDZkHwskU4MMjVywdtxSP6uxetEBvkSC2VHI9HfTeDgHr4D6kiz' +COMMON_BUCKET='snakeapi-deployment-test-bucket' +FLY_ORG='personal' +IMAGE_REF="registry.fly.io/snake-api-template:latest" \ No newline at end of file diff --git a/user-db-service/.env.development b/user-db-service/.env.development index 7509cce..52a3ca1 100644 --- a/user-db-service/.env.development +++ b/user-db-service/.env.development @@ -5,7 +5,7 @@ # See the documentation for all the connection string options: https://pris.ly/d/connection-strings #use this when testing local, remmber to run the proxy command -DATABASE_URL="postgresql://postgres:wly9H8gjjmxYfg1@host.docker.internal:15432/postgres?schema=public" +DATABASE_URL="postgresql://postgres:wly9H8gjjmxYfg1@localhost:15432/postgres?schema=public" # DATABASE_URL="postgres://postgres:wly9H8gjjmxYfg1@bytecamp-db.flycast:5432?sslmode=disable" # DATABASE_URL=postgres://snakebyte:zVB7lgOiKr89dq6@localhost:5432/snakebyte?sslmode=disable diff --git a/user-db-service/.env.test b/user-db-service/.env.test new file mode 100644 index 0000000..7509cce --- /dev/null +++ b/user-db-service/.env.test @@ -0,0 +1,12 @@ +# Environment variables declared in this file are automatically made available to Prisma. +# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema + +# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB. +# See the documentation for all the connection string options: https://pris.ly/d/connection-strings + +#use this when testing local, remmber to run the proxy command +DATABASE_URL="postgresql://postgres:wly9H8gjjmxYfg1@host.docker.internal:15432/postgres?schema=public" + +# DATABASE_URL="postgres://postgres:wly9H8gjjmxYfg1@bytecamp-db.flycast:5432?sslmode=disable" +# DATABASE_URL=postgres://snakebyte:zVB7lgOiKr89dq6@localhost:5432/snakebyte?sslmode=disable +NODE_PORT=3100 From a494cd4f0ab15cd51bd944186834445322b9684b Mon Sep 17 00:00:00 2001 From: JBB0807 <104856796+JBB0807@users.noreply.github.com> Date: Wed, 7 May 2025 23:30:37 -0700 Subject: [PATCH 3/4] now getting the correct IPV6 for proxy --- assignment-service/.env | 1 + assignment-service/.env.development | 2 ++ assignment-service/.env.test | 3 ++- assignment-service/routes/InstructorRouter.js | 4 +++- deployment-service/src/index.js | 12 ++++++++++-- 5 files changed, 18 insertions(+), 4 deletions(-) diff --git a/assignment-service/.env b/assignment-service/.env index f5f5b51..19e98cb 100644 --- a/assignment-service/.env +++ b/assignment-service/.env @@ -1,3 +1,4 @@ DB_ASSIGNMENT_SERVICE_URL = "http://db-assignment-service.internal:3000" DEPLOY_API_URL="http://localhost:3006" +PROXY_URL="https://proxy-service.fly.dev" NODE_PORT = 8080 \ No newline at end of file diff --git a/assignment-service/.env.development b/assignment-service/.env.development index b683362..b1d5a57 100644 --- a/assignment-service/.env.development +++ b/assignment-service/.env.development @@ -8,4 +8,6 @@ AWS_REGION='auto' AWS_SECRET_ACCESS_KEY='tsec_6Bz1aMbfYQftuq5WfIVEDZkHwskU4MMjVywdtxSP6uxetEBvkSC2VHI9HfTeDgHr4D6kiz' COMMON_BUCKET='snakeapi-deployment-test-bucket' +PROXY_URL="https://proxy-service.fly.dev" + NODE_PORT=8082 \ No newline at end of file diff --git a/assignment-service/.env.test b/assignment-service/.env.test index 2c83b66..d920c9b 100644 --- a/assignment-service/.env.test +++ b/assignment-service/.env.test @@ -1,4 +1,5 @@ NODE_ENV=docker DB_ASSIGNMENT_SERVICE_URL="http://js-assignment-db-service:3200" DEPLOY_API_URL="http://js-deployment-service:3006/deploy" -NODE_PORT=8082 \ No newline at end of file +NODE_PORT=8082 +PROXY_URL="https://proxy-service.fly.dev" diff --git a/assignment-service/routes/InstructorRouter.js b/assignment-service/routes/InstructorRouter.js index 73b7eb5..8d6fcc1 100644 --- a/assignment-service/routes/InstructorRouter.js +++ b/assignment-service/routes/InstructorRouter.js @@ -8,6 +8,7 @@ const DB_ASSIGNMENT_SERVICE_URL = process.env.DB_ASSIGNMENT_SERVICE_URL || "http://localhost:3000"; const DEPLOY_API_URL = process.env.DEPLOY_API_URL || "http://localhost:3600"; +const PROXY_URL = process.env.PROXY_URL; console.log("DB_ASSIGNMENT_SERVICE_URL:", DB_ASSIGNMENT_SERVICE_URL); console.log("DEPLOY_API_URL:", DEPLOY_API_URL); @@ -63,8 +64,9 @@ intructorRouter.post( // Update the assignment with the deployment details const updatedAssignmentData = { - assignmenturl: ipv6, + assignmenturl: `${PROXY_URL}/${ipv6}`, } + console.log("Updating assignment with deployment details:", updatedAssignmentData); const updateRespone = await axios.put( `${DB_ASSIGNMENT_SERVICE_URL}/assignments/${assignmentId}`, diff --git a/deployment-service/src/index.js b/deployment-service/src/index.js index 3551744..64ad909 100644 --- a/deployment-service/src/index.js +++ b/deployment-service/src/index.js @@ -163,13 +163,21 @@ app.post("/deploy", async (req, res) => { const ipv6 = v6resp.data.data.allocateIpAddress.ipAddress.address; console.log("Allocated IPv6:", ipv6); + const machines = await fly.get(`/apps/${appName}/machines`); + const firstPrivateIp = machines.data[0]?.private_ip; + if (!firstPrivateIp) { + console.error("No private IP found for the machine:", machines.data); + return machines.status(500).json({ error: "No private IP found" }); + } + console.log("First private IP:", firstPrivateIp); + return res.json({ status: "created", app: appName, ipv4, - ipv6, + ipv6 : firstPrivateIp, url_v4: `http://${ipv4}`, - url_v6: `http://[${ipv6}]`, + url_v6: `http://[${firstPrivateIp}]`, }); } catch (err) { console.error( From 06a6e9b8a53e5645cfbe9d3ab1392d33ade76d29 Mon Sep 17 00:00:00 2001 From: JBB0807 <104856796+JBB0807@users.noreply.github.com> Date: Thu, 8 May 2025 00:14:10 -0700 Subject: [PATCH 4/4] bug fix on delete --- assignment-db-service/app.js | 2 ++ assignment-service/routes/InstructorRouter.js | 5 +++-- deployment-service/src/index.js | 14 +++++++++----- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/assignment-db-service/app.js b/assignment-db-service/app.js index bfb2fbd..8216bf2 100644 --- a/assignment-db-service/app.js +++ b/assignment-db-service/app.js @@ -236,11 +236,13 @@ app.put("/assignments/:id", async (req, res) => { app.delete("/assignments/:id", async (req, res) => { try { const { id } = req.params; + console.log("Deleting assignment with ID:", id); await prisma.assignments.delete({ where: { assignmentid: parseInt(id) }, }); + console.log("Assignment deleted successfully:", id); res.json({ message: "Assignment deleted successfully" }); } catch (err) { console.error("Error deleting assignment:", err.message); diff --git a/assignment-service/routes/InstructorRouter.js b/assignment-service/routes/InstructorRouter.js index 8d6fcc1..c2187b0 100644 --- a/assignment-service/routes/InstructorRouter.js +++ b/assignment-service/routes/InstructorRouter.js @@ -66,7 +66,7 @@ intructorRouter.post( const updatedAssignmentData = { assignmenturl: `${PROXY_URL}/${ipv6}`, } - + console.log("Updating assignment with deployment details:", updatedAssignmentData); const updateRespone = await axios.put( `${DB_ASSIGNMENT_SERVICE_URL}/assignments/${assignmentId}`, @@ -196,7 +196,6 @@ intructorRouter.delete( // Delete the Battlesnake API if(assignmentData.appname){ console.log(`Deleting Battlesnake API: ${assignmentData.appname}`); - console.log("DEPLOY_API_URL:", DEPLOY_API_URL, assignmentData.appname); const deployResponse = await axios.post(`${DEPLOY_API_URL}/${assignmentData.appname}/delete`, { "appName": assignmentData.appname }); @@ -208,9 +207,11 @@ intructorRouter.delete( console.log('Response from DEPLOY_API_URL:', deployResponse.data); } + console.log("Deleting assignment from database:", assignmentId); const response = await axios.delete( `${DB_ASSIGNMENT_SERVICE_URL}/assignments/${assignmentId}` ); + console.log("Response from DB_ASSIGNMENT_SERVICE_URL:", response.data); res.status(response.status).json(response.data); } catch (error) { res.status(error.response?.status || 500).json({ error: error.message }); diff --git a/deployment-service/src/index.js b/deployment-service/src/index.js index 64ad909..2e60234 100644 --- a/deployment-service/src/index.js +++ b/deployment-service/src/index.js @@ -230,17 +230,21 @@ app.post("/:appName/delete", async (req, res) => { //check if the app exists console.log("Checking if app exists:", appName); + const appCheck = await fly.get(`/apps/${appName}`); console.log("App check response:", appCheck.status); - if (appCheck.status !== 200) { - console.log("App not found:", appName); - return res.json({ status: "App not found", app: appName }); - } - + await fly.delete(`/apps/${appName}`); return res.json({ status: "deleted", app: appName }); } catch (err) { + + //handle the 404 error and not treat it as a failure (no app to delete) + if (err.response?.status === 404) { + console.log("App not found, nothing to delete:", appName); + return res.status(200).json({ error: "App not found" }); + } + const errorData = err.response?.data || err.stack || err.message; console.error("App deletion error:", errorData); return res.status(500).json({ errorData });