81 Commits

Author SHA1 Message Date
2e089e192d Merge branch 'main' of https://git.csi-kjsce.org/Arnab-Afk/monaco 2025-12-05 00:37:51 +05:30
38cf325e22 gitea test 2025-12-05 00:36:15 +05:30
16620111cf test 2025-12-04 23:55:16 +05:30
ishikabhoyar
fbbcabbeab style: update padding for console content for improved layout 2025-11-09 13:58:11 +05:30
ishikabhoyar
35d40da727 feat: enhance terminal input handling and improve WebSocket connection safety 2025-11-09 13:52:48 +05:30
ebaef13845 feat: add functionality to mark questions for review and update styles for marked questions 2025-11-08 23:03:25 +05:30
b075e5b3d3 feat: implement test cases tab with styling and functionality for displaying test cases 2025-11-08 22:52:51 +05:30
ishikabhoyar
1d3b1c74e1 fix: process code input to handle newlines and tabs correctly; update CSS for better text wrapping 2025-11-08 18:44:55 +05:30
ishikabhoyar
8ec0935486 refactor question bar and problem container styles for improved layout and readability 2025-11-03 20:21:33 +05:30
ishikabhoyar
33b9e2fe38 add reset code functionality to restore original starter code in CodeChallenge component 2025-11-03 20:02:01 +05:30
ishikabhoyar
c579f972b8 remove example problem data and related starter code handling from CodeChallenge component 2025-11-03 19:59:49 +05:30
ishikabhoyar
0c844c3122 remove starter code templates for all questions in CodeChallenge component 2025-11-03 19:53:45 +05:30
356d532beb add terminal input handling and styling to CodeChallenge component 2025-11-03 15:30:58 +05:30
ishikabhoyar
2508731ec7 refactor WebSocket and fetch API URLs to use environment variables for better configuration 2025-11-03 14:25:01 +05:30
6ef2edb768 add tunnel-only setup with host network mode, including updated Dockerfile, docker-compose, and configuration files 2025-11-01 00:55:04 +05:30
fbafab5d51 add tunnel-only setup with Docker, including Dockerfile, docker-compose, and scripts 2025-11-01 00:49:59 +05:30
a433c5067f update service configuration to use host.docker.internal for backend connectivity 2025-10-31 21:21:46 +05:30
ishikabhoyar
ec33604a6f refactor docker-compose configuration to simplify network setup for tunnel service 2025-10-31 16:36:17 +05:30
ishikabhoyar
dbd8770f20 refactor Dockerfile and configuration for cloudflared tunnel setup 2025-10-31 16:28:37 +05:30
ishikabhoyar
9fa0528ff0 remove DNS routing setup for cloudflared tunnel in Dockerfile 2025-10-31 16:23:19 +05:30
ishikabhoyar
e82554215b add Dockerfile, docker-compose, and scripts for frontend tunnel setup 2025-10-31 16:08:02 +05:30
ishikabhoyar
abc15efabd refactor API URL handling in TestList and AuthContext components 2025-10-31 15:12:58 +05:30
ishikabhoyar
b18dc5f21b update styling for language selector and reset code button in CodeChallenge component 2025-10-30 23:24:48 +05:30
ishikabhoyar
336ad17240 remove active line border from Monaco Editor 2025-10-30 23:10:43 +05:30
ishikabhoyar
9d180e13b1 increase font size for time labels in index.css 2025-10-30 23:07:04 +05:30
ishikabhoyar
6b98938245 update font sizes and layout adjustments in CodeChallenge component 2025-10-30 23:06:22 +05:30
ishikabhoyar
9a1dee00a1 Enhance UI and UX of Code Challenge Component 2025-10-30 22:21:49 +05:30
ishikabhoyar
9d6729e63c modernize UI for Code Challenge page with new header, question palette, and improved styling 2025-10-30 21:54:07 +05:30
ishikabhoyar
4daafa726d fix: update API URL for student submissions in CodeChallenge component 2025-10-29 16:43:37 +05:30
47f73681af feat: Update login navigation and authentication flow
- Changed navigation from '/editor' to '/tests' after successful login.
- Introduced token state management in AuthContext for better handling of authentication.
- Updated login function to store JWT instead of Google token.
- Added error handling for login and test fetching processes.

style: Enhance UI with new footer and test list styles

- Added a footer component with copyright information.
- Created a new TestList component with improved styling and animations.
- Implemented responsive design for test cards and filter tabs.
- Added loading and error states for better user experience.

fix: Improve API interaction for test fetching and password verification

- Refactored API calls to use a centralized studentApi utility.
- Enhanced error handling for API responses, including unauthorized access.
- Implemented password verification for protected tests before starting them.
2025-10-29 11:37:19 +05:30
ishikabhoyar
304761e258 Remove Header component from ProtectedRoute in App.jsx 2025-10-28 14:14:44 +05:30
ishikabhoyar
453f44a43a Add Google OAuth integration, routing, and theme toggle; implement login and protected routes 2025-10-13 23:51:39 +05:30
Ishika Bhoyar
e8e6011524 Merge pull request #2 from ishikabhoyar/leetcode
Leetcode
2025-10-13 16:38:55 +05:30
ishikabhoyar
eabfbf806e Refactor footer padding and enhance scrollbar styles for terminal and content areas 2025-08-17 17:07:38 +05:30
ishikabhoyar
e4f193613a Add footer component and styles to prevent overlap with content 2025-08-17 17:03:16 +05:30
210f531990 Update configuration defaults for server and executor settings 2025-08-15 14:53:57 +05:30
e9553dd3af Add DNS routing setup for cloudflared tunnel in Dockerfile 2025-08-15 14:23:29 +05:30
458b2ca06f Add credentials.json and update cloudflared configuration in Dockerfile 2025-08-15 14:19:58 +05:30
232c6ec530 Update supervisord configuration for cloudflared to use tunnel URL and modify tunnel ID in config.json 2025-08-15 14:17:18 +05:30
20680719f5 Update Dockerfile and docker-compose to enhance cloudflared configuration and startup process 2025-08-15 14:09:36 +05:30
c7d65c612f Refactor Dockerfile and docker-compose to use supervisord for process management and update cloudflared installation method 2025-08-15 14:05:00 +05:30
e5827cfa42 Add supervisord configuration for backend and cloudflared services 2025-08-14 23:55:57 +05:30
720a37fa82 Refactor Dockerfile to create startup script dynamically, ensuring correct line endings and improved backend initialization 2025-08-14 23:52:05 +05:30
9474d2f633 Add Dockerfile and Makefile for cloudflared tunnel setup; include startup script 2025-08-14 23:49:19 +05:30
5902300c95 Refactor Dockerfile to streamline cloudflared installation and improve image layering 2025-08-14 23:42:45 +05:30
eb2873a3b9 Add Docker setup for Monaco backend with Cloudflare tunnel support 2025-08-14 21:15:53 +05:30
ishikabhoyar
25900803c3 Increase timeout settings for Python, C, C++, JavaScript, and Go language configurations to improve execution reliability 2025-08-08 13:39:49 +05:30
ishikabhoyar
5104fcbde0 java timeout 2025-08-08 13:37:52 +05:30
ishikabhoyar
402235bdec Remove unused vite.svg file to declutter the project 2025-08-08 13:37:30 +05:30
2af996b83e Add Dockerfile and Nginx configuration for multi-stage build setup 2025-07-23 19:31:13 +05:30
ishikabhoyar
d501b53ab6 Add favicon.ico and link it in index.html for improved branding 2025-07-23 17:25:21 +05:30
ishikabhoyar
ac12360822 Remove CodeChallenge component CSS file to streamline styling management 2025-07-23 17:17:12 +05:30
ishikabhoyar
4654b93b15 Enhance styling in CodeChallenge component for improved UI and readability 2025-07-23 17:16:23 +05:30
ishikabhoyar
2867f3bf42 Enhance CodeChallenge component with improved styling for problem examples and refined WebSocket handling for execution state management 2025-07-23 16:04:06 +05:30
ishikabhoyar
6d77a6b8ce Refactor language identifier mapping and remove unused language options in CodeChallenge component 2025-07-22 15:52:06 +05:30
ishikabhoyar
233be39b7f Add language identifier mapping and starter code templates for multiple languages in CodeChallenge component 2025-07-22 15:47:24 +05:30
ishikabhoyar
6964f370cb Enhance WebSocket message handling to support new message types and improve error reporting 2025-07-22 15:32:59 +05:30
ishikabhoyar
e12bbcfc6a Implement Code Challenge component with styling and WebSocket integration 2025-07-22 15:26:54 +05:30
ishikabhoyar
e61bd7cfca Add new backend implementation in main file 2025-06-22 12:46:46 +05:30
ishikabhoyar
a6bd8eeebb Refactor WebSocket input handling to support structured messages and improve error logging 2025-06-22 12:44:00 +05:30
ishikabhoyar
c529a48f31 Enhance C code execution by adding a wrapper to disable stdout buffering 2025-06-22 12:11:13 +05:30
ishikabhoyar
86bc89c12e new backend changes 2025-06-22 11:30:47 +05:30
ishikabhoyar
6802cefcaa Remove unused Monaco distribution files for Windows and macOS 2025-06-22 11:17:30 +05:30
ishikabhoyar
85c9b99ef6 Remove unused Monaco distribution files for various platforms 2025-06-22 11:16:58 +05:30
ishikabhoyar
142ff262ac Remove unused Monaco distribution files 2025-06-22 11:16:50 +05:30
ishikabhoyar
7eb42b20dd Remove unused backend distribution files and configuration 2025-06-22 11:16:40 +05:30
ishikabhoyar
6128348417 Remove backend documentation and test files 2025-06-22 11:16:22 +05:30
ishikabhoyar
b860db0b41 Remove backend main.go and go.sum files 2025-06-22 11:16:12 +05:30
ishikabhoyar
75ffb94cca Remove unused data fetching and Go module files 2025-06-22 11:16:03 +05:30
56e3086cd9 Merge pull request #1 from Arnab-Afk/socket
Socket Integration
2025-03-30 21:36:59 +05:30
4a737744df Update README.md to include WebSocket support and enhance installation instructions 2025-03-30 21:34:56 +05:30
1cbb4f3c35 Implement execution status polling and enhance input handling in EditorArea and Panel components 2025-03-30 21:34:45 +05:30
ishikabhoyar
918b323cda Add warning indicator and language mode to StatusBar component 2025-03-30 11:15:26 +05:30
ishikabhoyar
208655c9bc Refactor StatusBar component and adjust CSS for improved layout and styling 2025-03-30 02:06:27 +05:30
ishikabhoyar
48a14f674d Refactor Panel and StatusBar components by adding comments for clarity and improving accessibility with aria-labels 2025-03-30 01:59:12 +05:30
ishikabhoyar
697c4b8460 Enhance Panel component with additional tabs and keyboard input handling for terminal 2025-03-30 01:51:21 +05:30
ishikabhoyar
99e12a7355 Add custom icon for README.md file in Sidebar component 2025-03-30 01:26:27 +05:30
ishikabhoyar
3cc73e786a Refactor Sidebar component by removing unused folder icon and cleaning up code 2025-03-30 01:18:15 +05:30
ishikabhoyar
80a713cc56 Remove Navbar component and associated styles 2025-03-30 01:11:21 +05:30
ishikabhoyar
648391e6ba Update README and EditorArea components with project description and functionalities 2025-03-30 00:45:05 +05:30
3a75000e12 Implement WebSocket support for terminal connections and enhance terminal UI 2025-03-30 00:13:32 +05:30
112 changed files with 7529 additions and 3118 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

56
Dockerfile Normal file
View File

@@ -0,0 +1,56 @@
# Stage 1: Build the React frontend
FROM node:18-alpine AS frontend-builder
WORKDIR /app/frontend
# Define a build-time argument for the API URL with a default value
ARG VITE_API_URL=""
# Set it as an environment variable for the build command
ENV VITE_API_URL=$VITE_API_URL
# Copy package files and install dependencies
COPY Frontend/package.json Frontend/package-lock.json* Frontend/yarn.lock* ./
RUN yarn install --frozen-lockfile
# Copy the rest of the frontend source code
COPY Frontend/ ./
# Build the static files. Vite will use the VITE_API_URL env var.
RUN yarn build
# Stage 2: Build the Go backend
FROM golang:1.19-alpine AS backend-builder
WORKDIR /app/backend
# Install git for dependency fetching
RUN apk update && apk add --no-cache git
# Copy go module files and download dependencies
COPY new-backend/go.mod new-backend/go.sum ./
RUN go mod download
# Copy the backend source code
COPY new-backend/ ./
# Build the Go binary
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags="-s -w" -o /monaco-backend .
# Stage 3: Create the final image with Nginx
FROM nginx:1.25-alpine
# Install Docker client for the backend
RUN apk update && apk add --no-cache docker-cli
# Copy the Go backend binary
COPY --from=backend-builder /monaco-backend /usr/local/bin/monaco-backend
# Copy the built frontend files to the Nginx html directory
COPY --from=frontend-builder /app/frontend/dist /usr/share/nginx/html
# Copy the Nginx configuration
COPY nginx.conf /etc/nginx/nginx.conf
# Expose the public port for Nginx
EXPOSE 80
# Start both the backend and Nginx
CMD sh -c 'monaco-backend & nginx -g "daemon off;"'

View File

@@ -1 +1,2 @@
VITE_API_URL="http://localhost:8080"
VITE_FACULTY_API_URL="http://localhost:5000/api"

7
Frontend/.env.example Normal file
View File

@@ -0,0 +1,7 @@
# Monaco Frontend Environment Variables
# Backend API URL (Monaco code execution server)
VITE_API_URL=http://localhost:8080
# Faculty API URL (Faculty/Student management backend)
VITE_FACULTY_API_URL=http://localhost:5000/api

View File

@@ -0,0 +1,35 @@
# Final stage
FROM alpine:latest
# Install supervisor and wget
RUN apk update && apk add --no-cache supervisor wget
# Get cloudflared directly from GitHub
RUN wget -O cloudflared https://github.com/cloudflare/cloudflared/releases/download/2023.5.0/cloudflared-linux-amd64 && \
chmod +x cloudflared && \
mv cloudflared /usr/local/bin/
# Create directories for cloudflared
RUN mkdir -p /etc/cloudflared
# Copy the cloudflared config and credentials
COPY credentials.json /etc/cloudflared/credentials.json
COPY config.json /etc/cloudflared/config.json
# Create supervisord config (only cloudflared, no frontend inside container)
RUN mkdir -p /etc/supervisor/conf.d/
RUN echo "[supervisord]" > /etc/supervisor/conf.d/supervisord.conf && \
echo "nodaemon=true" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "user=root" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "[program:cloudflared]" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "command=cloudflared tunnel --config /etc/cloudflared/config.json run" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "autostart=true" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "autorestart=true" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "stdout_logfile=/dev/stdout" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "stdout_logfile_maxbytes=0" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "stderr_logfile=/dev/stderr" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "stderr_logfile_maxbytes=0" >> /etc/supervisor/conf.d/supervisord.conf
# Use supervisord to manage cloudflared
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]

View File

@@ -1,13 +1,24 @@
# VSCode Clone with React and Vite
# VS Code Clone Project
This project is a VSCode-like code editor built with React and Vite. It features a customizable UI with an activity bar, sidebar, editor area, panel, and status bar, mimicking the look and feel of Visual Studio Code.
## Authors
- Arnab Bhowmik
- Ishika Bhoyar
## Features
## Description
This project is a VS Code Clone built with React and Monaco Editor. It features a file tree navigation, tab management, code editing with syntax highlighting, and a terminal panel for running code. It mimics the core functionalities of Visual Studio Code in a browser-based environment.
- **Activity Bar**: Switch between different views like Explorer, Search, Source Control, etc.
- **Sidebar**: Displays file explorer, search results, and source control information.
- **Editor Area**: Code editor with syntax highlighting and multiple tabs.
- **Panel**: Terminal, Problems, and Output views.
- **Status Bar**: Displays status information and provides quick actions.
## Frontend Functionalities
- Built with React and Monaco Editor.
- File tree navigation for managing files and folders.
- Tab management for opening multiple files simultaneously.
- Code editing with syntax highlighting and language support.
- Terminal panel for running code and viewing output.
- Persistent file structure and content using localStorage.
## Project Structure
## Backend Functionalities
- Built with Go and Docker for secure code execution.
- Supports multiple programming languages (Python, Java, C/C++).
- Executes code in isolated Docker containers with resource limits.
- RESTful API for submitting code, checking status, and retrieving results.
- Job queue system for managing concurrent executions.
- Enforces timeouts and resource limits for security and performance.

15
Frontend/config.json Normal file
View File

@@ -0,0 +1,15 @@
{
"tunnel": "8c559c7c-42bb-4b9d-96a2-99cefd274b06",
"credentials-file": "/etc/cloudflared/credentials.json",
"ingress": [
{
"hostname": "monaco.ishikabhoyar.tech",
"service": "http://host.docker.internal:8001"
},
{
"service": "http_status:404"
}
],
"protocol": "http2",
"loglevel": "info"
}

View File

@@ -0,0 +1,5 @@
{
"AccountTag": "453afb9373a00a55876e6127cf0efd97",
"TunnelSecret": "afJ6YY25rj9+G6qqHy+2jss4h+QKfw6YntijRZvo4ZQ=",
"TunnelID": "8c559c7c-42bb-4b9d-96a2-99cefd274b06"
}

View File

@@ -0,0 +1,10 @@
services:
tunnel:
build:
context: .
dockerfile: Dockerfile.tunnel
restart: unless-stopped
network_mode: "host"
environment:
# Define cloudflared environment variables
- NO_AUTOUPDATE=true

View File

@@ -3,6 +3,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="/public/favicon.ico" type="image/x-icon" />
<title>VSCode</title>
</head>
<body>

View File

@@ -9,11 +9,13 @@
"version": "0.0.0",
"dependencies": {
"@monaco-editor/react": "^4.7.0",
"@react-oauth/google": "^0.12.2",
"lucide-react": "^0.483.0",
"monaco-editor": "^0.52.2",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-resizable-panels": "^2.1.7"
"react-resizable-panels": "^2.1.7",
"react-router-dom": "^7.9.4"
},
"devDependencies": {
"@eslint/js": "^9.21.0",
@@ -1041,6 +1043,16 @@
"react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/@react-oauth/google": {
"version": "0.12.2",
"resolved": "https://registry.npmjs.org/@react-oauth/google/-/google-0.12.2.tgz",
"integrity": "sha512-d1GVm2uD4E44EJft2RbKtp8Z1fp/gK8Lb6KHgs3pHlM0PxCXGLaq8LLYQYENnN4xPWO1gkL4apBtlPKzpLvZwg==",
"license": "MIT",
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
}
},
"node_modules/@rollup/rollup-android-arm-eabi": {
"version": "4.36.0",
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.36.0.tgz",
@@ -1602,6 +1614,15 @@
"dev": true,
"license": "MIT"
},
"node_modules/cookie": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.0.2.tgz",
"integrity": "sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA==",
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -2656,9 +2677,9 @@
"license": "ISC"
},
"node_modules/postcss": {
"version": "8.5.3",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.3.tgz",
"integrity": "sha512-dle9A3yYxlBSrt8Fu+IpjGT8SY8hN0mlaA6GY8t0P5PjIOZemULz/E2Bnm/2dcUOena75OTNkHI76uZBNUUq3A==",
"version": "8.5.6",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",
"integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==",
"dev": true,
"funding": [
{
@@ -2676,7 +2697,7 @@
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.8",
"nanoid": "^3.3.11",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
@@ -2745,6 +2766,44 @@
"react-dom": "^16.14.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"
}
},
"node_modules/react-router": {
"version": "7.9.4",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.9.4.tgz",
"integrity": "sha512-SD3G8HKviFHg9xj7dNODUKDFgpG4xqD5nhyd0mYoB5iISepuZAvzSr8ywxgxKJ52yRzf/HWtVHc9AWwoTbljvA==",
"license": "MIT",
"dependencies": {
"cookie": "^1.0.1",
"set-cookie-parser": "^2.6.0"
},
"engines": {
"node": ">=20.0.0"
},
"peerDependencies": {
"react": ">=18",
"react-dom": ">=18"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true
}
}
},
"node_modules/react-router-dom": {
"version": "7.9.4",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.9.4.tgz",
"integrity": "sha512-f30P6bIkmYvnHHa5Gcu65deIXoA2+r3Eb6PJIAddvsT9aGlchMatJ51GgpU470aSqRRbFX22T70yQNUGuW3DfA==",
"license": "MIT",
"dependencies": {
"react-router": "7.9.4"
},
"engines": {
"node": ">=20.0.0"
},
"peerDependencies": {
"react": ">=18",
"react-dom": ">=18"
}
},
"node_modules/resolve-from": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
@@ -2810,6 +2869,12 @@
"semver": "bin/semver.js"
}
},
"node_modules/set-cookie-parser": {
"version": "2.7.1",
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.1.tgz",
"integrity": "sha512-IOc8uWeOZgnb3ptbCURJWNjWUPcO3ZnTTdzsurqERrP6nPyv+paC55vJM0LpOlT2ne+Ix+9+CRG1MNLlyZ4GjQ==",
"license": "MIT"
},
"node_modules/shebang-command": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",

View File

@@ -11,11 +11,13 @@
},
"dependencies": {
"@monaco-editor/react": "^4.7.0",
"@react-oauth/google": "^0.12.2",
"lucide-react": "^0.483.0",
"monaco-editor": "^0.52.2",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-resizable-panels": "^2.1.7"
"react-resizable-panels": "^2.1.7",
"react-router-dom": "^7.9.4"
},
"devDependencies": {
"@eslint/js": "^9.21.0",

Binary file not shown.

After

Width:  |  Height:  |  Size: 677 KiB

BIN
Frontend/public/Bottom.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

BIN
Frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

BIN
Frontend/public/kjsce2x.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -1,12 +1,50 @@
import VSCodeUI from "./components/VSCodeUI.jsx"
import "./index.css"
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { GoogleOAuthProvider } from '@react-oauth/google';
import { AuthProvider } from './contexts/AuthContext';
import Login from './components/Login';
import TestList from './components/TestList';
import CodeChallenge from "./components/CodeChallenge.jsx";
import Header from './components/Header';
import Footer from './components/Footer';
import ProtectedRoute from './components/ProtectedRoute';
import "./index.css";
function App() {
// Google OAuth Client ID - in production, this should be in environment variables
const GOOGLE_CLIENT_ID = "586378657128-smg8t52eqbji66c3eg967f70hsr54q5r.apps.googleusercontent.com";
return (
<div className="App">
<VSCodeUI />
</div>
)
<GoogleOAuthProvider clientId={GOOGLE_CLIENT_ID}>
<AuthProvider>
<Router>
<div className="App">
<Routes>
<Route path="/login" element={<Login />} />
<Route
path="/tests"
element={
<ProtectedRoute>
<TestList />
<Footer />
</ProtectedRoute>
}
/>
<Route
path="/editor"
element={
<ProtectedRoute>
<CodeChallenge />
<Footer />
</ProtectedRoute>
}
/>
<Route path="/" element={<Navigate to="/tests" replace />} />
</Routes>
</div>
</Router>
</AuthProvider>
</GoogleOAuthProvider>
);
}
export default App

File diff suppressed because it is too large Load Diff

View File

@@ -9,6 +9,32 @@ import {
import Sidebar from "./Sidebar";
import Panel from "./Panel"; // Import Panel component
// Add this function to map file extensions to language identifiers
const getLanguageFromExtension = (extension) => {
const extensionMap = {
'js': 'javascript',
'jsx': 'javascript',
'ts': 'typescript',
'tsx': 'typescript',
'py': 'python',
'java': 'java',
'c': 'c',
'cpp': 'cpp',
'h': 'c',
'hpp': 'cpp',
'cs': 'csharp',
'go': 'go',
'rb': 'ruby',
'php': 'php',
'html': 'html',
'css': 'css',
'json': 'json',
'md': 'markdown'
};
return extensionMap[extension] || 'text';
};
const EditorArea = ({
sidebarVisible = true,
activeView = "explorer",
@@ -62,8 +88,8 @@ const EditorArea = ({
// Add a new state for user input
const [userInput, setUserInput] = useState("");
// Add a new state for waiting for input
const [waitingForInput, setWaitingForInput] = useState(false);
// Add socket state to track the connection
const [activeSocket, setActiveSocket] = useState(null);
// Focus the input when new file modal opens
useEffect(() => {
@@ -110,11 +136,6 @@ const EditorArea = ({
useEffect(() => {
localStorage.setItem("vscode-clone-files", JSON.stringify(files));
}, [files]);
useEffect(() => {
localStorage.setItem("vscode-clone-structure", JSON.stringify(fileStructure));
}, [fileStructure]);
// Add this effect to handle editor resize when sidebar changes
useEffect(() => {
// Force editor to readjust layout when sidebar visibility changes
@@ -132,6 +153,41 @@ const EditorArea = ({
}
}, [panelVisible]);
// Add this useEffect for cleanup
useEffect(() => {
// Cleanup function to close socket when component unmounts
return () => {
if (activeSocket) {
activeSocket.close();
}
};
}, []);
// Add interval to poll execution status
useEffect(() => {
const checkInterval = setInterval(() => {
// Poll execution status
if (activeSocket && activeRunningFile) {
// Check if socket is still connected
if (activeSocket.readyState !== WebSocket.OPEN) {
console.warn("Socket not in OPEN state:", activeSocket.readyState);
setTerminalOutput(prev => [...prev, {
type: 'warning',
content: `Terminal connection lost, attempting to reconnect...`
}]);
// Could implement reconnection logic here
}
}
}, 5000);
// Clean up interval when component unmounts
return () => {
if (checkInterval) {
clearInterval(checkInterval);
}
};
}, [activeSocket, activeRunningFile]);
const handleEditorDidMount = (editor) => {
editorRef.current = editor;
};
@@ -479,21 +535,31 @@ const EditorArea = ({
case "README.md":
return `# VS Code Clone Project
## Overview
This is a simple VS Code clone built with React and Monaco Editor.
## Authors
- Arnab Bhowmik
- Ishika Bhoyar
## Features
- File tree navigation
- Tab management
- Code editing with Monaco Editor
- Syntax highlighting
## Description
This project is a VS Code Clone built with React and Monaco Editor. It features a file tree navigation, tab management, code editing with syntax highlighting, and a terminal panel for running code. It mimics the core functionalities of Visual Studio Code in a browser-based environment.
## Frontend Functionalities
- Built with React and Monaco Editor.
- File tree navigation for managing files and folders.
- Tab management for opening multiple files simultaneously.
- Code editing with syntax highlighting and language support.
- Terminal panel for running code and viewing output.
- Persistent file structure and content using localStorage.
## Backend Functionalities
- Built with Go and Docker for secure code execution.
- Supports multiple programming languages (Python, Java, C/C++).
- Executes code in isolated Docker containers with resource limits.
- RESTful API for submitting code, checking status, and retrieving results.
- Job queue system for managing concurrent executions.
- Enforces timeouts and resource limits for security and performance.
`;
## Getting Started
1. Create a new file using the + button in the sidebar
2. Edit your code in the editor
3. Save changes using the save button
Happy coding!`;
default:
return "";
}
@@ -507,7 +573,7 @@ Happy coding!`;
width: `calc(100% - ${sidebarVisible ? sidebarWidth : 0}px)`
};
// Modify the handleRunCode function to prompt for input first
// Update the handleRunCode function
const handleRunCode = async () => {
if (!activeFile) return;
@@ -517,49 +583,36 @@ Happy coding!`;
setPanelVisible(true);
}
// Set state to waiting for input
setWaitingForInput(true);
setActiveRunningFile(activeFile.id);
// Clear previous output and add new command
const fileExtension = activeFile.id.split('.').pop().toLowerCase();
const language = getLanguageFromExtension(fileExtension);
const newOutput = [
{ type: 'command', content: `$ run ${activeFile.id}` },
{ type: 'output', content: 'Waiting for input (press Enter if no input is needed)...' }
{ type: 'output', content: 'Submitting code...' }
];
setTerminalOutput(newOutput);
};
// Add a new function to handle input submission
const handleInputSubmit = async () => {
if (!activeFile || !waitingForInput) return;
// Set running state
setIsRunning(true);
setWaitingForInput(false);
// Add message that we're running with the input
setTerminalOutput(prev => [
...prev,
{ type: 'output', content: userInput ? `Using input: "${userInput}"` : 'Running without input...' }
]);
// Use API URL from environment variable
const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:8080';
try {
// Now make the API call with the input that was entered
const submitResponse = await fetch(`${apiUrl}/submit`, {
// Close any existing socket
if (activeSocket) {
activeSocket.close();
setActiveSocket(null);
}
// Use API URL from environment variable
const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:8080';
// Submit the code to get an execution ID
const submitResponse = await fetch(`${apiUrl}/api/submit`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
language: getLanguageFromExtension(activeFile.id.split('.').pop().toLowerCase()),
language: language,
code: activeFile.content,
input: userInput
input: "" // Explicitly passing empty input, no user input handling
}),
});
@@ -570,87 +623,270 @@ Happy coding!`;
const { id } = await submitResponse.json();
setTerminalOutput(prev => [...prev, { type: 'output', content: `Job submitted with ID: ${id}` }]);
// Step 2: Poll for status until completed or failed
let status = 'pending';
while (status !== 'completed' && status !== 'failed') {
// Add a small delay between polls
await new Promise(resolve => setTimeout(resolve, 1000));
// Set active running file
setActiveRunningFile(activeFile.id);
const statusResponse = await fetch(`${apiUrl}/status?id=${id}`);
if (!statusResponse.ok) {
throw new Error(`Status check failed: ${statusResponse.status}`);
// Connect to WebSocket with the execution ID
const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsBaseUrl = apiUrl.replace(/^https?:\/\//, '');
const wsUrl = `${wsProtocol}//${wsBaseUrl}/api/ws/terminal/${id}`;
setTerminalOutput(prev => [...prev, { type: 'output', content: `Connecting to: ${wsUrl}` }]);
// Create a new WebSocket
const newSocket = new WebSocket(wsUrl);
// Set up event handlers
newSocket.onopen = () => {
console.log("WebSocket connected");
setTerminalOutput(prev => [...prev, { type: 'output', content: 'Connected to execution terminal' }]);
setIsRunning(true);
};
newSocket.onmessage = (event) => {
console.log("WebSocket message received:", event.data);
try {
const message = JSON.parse(event.data);
// Handle different message types
switch (message.type) {
case 'output':
setTerminalOutput(prev => [...prev, {
type: 'output',
content: message.content.text,
isError: message.content.isError
}]);
break;
case 'status':
const status = message.content.status;
setTerminalOutput(prev => [...prev, {
type: 'status',
content: `Status: ${status}`
}]);
// Update running state based on status
if (status === 'completed' || status === 'failed') {
// Don't immediately set isRunning to false - we'll wait for the socket to close or delay
}
break;
case 'system':
setTerminalOutput(prev => [...prev, {
type: 'system',
content: message.content
}]);
break;
case 'error':
setTerminalOutput(prev => [...prev, {
type: 'error',
content: `Error: ${message.content.message}`
}]);
break;
default:
// For raw or unknown messages
setTerminalOutput(prev => [...prev, {
type: 'output',
content: event.data
}]);
}
// Check if this message is likely asking for input (prompt detection)
if (message.type === 'output' && !message.content.isError &&
(message.content.text.includes("?") ||
message.content.text.endsWith(":") ||
message.content.text.endsWith("> "))) {
console.log("Input prompt detected, focusing terminal");
// Force terminal to focus after a prompt is detected
setTimeout(() => {
document.querySelector('.panel-terminal')?.focus();
}, 100);
}
} catch (err) {
// Handle case where message isn't valid JSON
console.warn("Failed to parse WebSocket message:", err);
setTerminalOutput(prev => [...prev, {
type: 'output',
content: event.data
}]);
}
};
const statusData = await statusResponse.json();
status = statusData.status;
// Add polling for job status
let statusCheckInterval;
if (id) {
// Start polling the status endpoint every 2 seconds
statusCheckInterval = setInterval(async () => {
try {
const statusResponse = await fetch(`${apiUrl}/api/status/${id}`);
if (statusResponse.ok) {
const statusData = await statusResponse.json();
// Update terminal with status (for any status type)
setTerminalOutput(prev => {
// Update the last status message or add a new one
const hasStatus = prev.some(line => line.content.includes('Status:'));
if (hasStatus) {
return prev.map(line =>
line.content.includes('Status:')
? { ...line, content: `Status: ${status}` }
: line
);
} else {
return [...prev, { type: 'output', content: `Status: ${status}` }];
// If the process is completed or failed, stop polling and update UI
if (statusData.status === 'completed' || statusData.status === 'failed') {
clearInterval(statusCheckInterval);
console.log("Process status:", statusData.status);
// Update the UI to show process is no longer running
setIsRunning(false);
// Display the final result if WebSocket didn't capture it
if (statusData.output && statusData.output.length > 0) {
setTerminalOutput(prev => {
// Check if the output is already in the terminal
const lastOutput = prev[prev.length - 1]?.content || "";
if (!lastOutput.includes(statusData.output)) {
return [...prev, {
type: 'output',
content: `\n[System] Final output:\n${statusData.output}`
}];
}
return prev;
});
}
// Close socket if it's still open
if (newSocket && newSocket.readyState === WebSocket.OPEN) {
newSocket.close();
}
}
}
} catch (error) {
console.error("Status check error:", error);
}
}, 2000);
// Clean up interval when component unmounts or when socket closes
newSocket.addEventListener('close', () => {
if (statusCheckInterval) {
clearInterval(statusCheckInterval);
}
});
}
// Get the result for both completed and failed status
const resultResponse = await fetch(`${apiUrl}/result?id=${id}`);
if (!resultResponse.ok) {
throw new Error(`Result fetch failed: ${resultResponse.status}`);
}
newSocket.onclose = (event) => {
console.log("WebSocket closed:", event);
const { output } = await resultResponse.json();
const reason = event.reason ? `: ${event.reason}` : '';
const code = event.code ? ` (code: ${event.code})` : '';
// Format and display output
const outputLines = output.split('\n').map(line => ({
type: status === 'failed' ? 'warning' : 'output',
content: line
}));
// Don't mark as not running if this is expected close (after execution completes)
// Code 1000 is normal closure, 1005 is no status code
const isExpectedClose = event.code === 1000 || event.code === 1005;
setTerminalOutput(prev => [
...prev,
{
type: status === 'failed' ? 'warning' : 'output',
content: status === 'failed'
? '------- EXECUTION FAILED -------'
: '------- EXECUTION RESULT -------'
},
...outputLines
]);
// Only set running to false if it wasn't an expected close
if (!isExpectedClose) {
setIsRunning(false);
if (status === 'failed') {
console.error('Code execution failed:', output);
}
// Add a graceful reconnection message
setTerminalOutput(prev => [...prev, {
type: 'warning',
content: `Terminal connection closed${reason}${code}`
}]);
// Attempt reconnection for certain close codes (unexpected closes)
if (activeRunningFile && event.code !== 1000) {
setTerminalOutput(prev => [...prev, {
type: 'info',
content: `Attempting to reconnect...`
}]);
// Reconnection delay
setTimeout(() => {
// Attempt to reconnect for the same file
if (activeRunningFile) {
console.log("Attempting to reconnect for", activeRunningFile);
// You could call your run function here again
}
}, 3000);
}
}
setActiveSocket(null);
// Clean up interval
if (statusCheckInterval) {
clearInterval(statusCheckInterval);
}
};
newSocket.onerror = (event) => {
console.error("WebSocket error:", event);
setTerminalOutput(prev => [...prev, {
type: 'warning',
content: `WebSocket error occurred`
}]);
};
// Set the active socket after all handlers are defined
setActiveSocket(newSocket);
} catch (error) {
console.error("Run code error:", error);
setTerminalOutput(prev => [...prev, { type: 'warning', content: `Error: ${error.message}` }]);
} finally {
// Set running state to false
setIsRunning(false);
// Also add cleanup in the error handler
if (statusCheckInterval) {
clearInterval(statusCheckInterval);
}
}
};
// Helper function to convert file extension to language identifier for API
const getLanguageFromExtension = (extension) => {
const languageMap = {
'java': 'java',
'c': 'c',
'cpp': 'cpp',
'py': 'python',
'js': 'javascript',
'jsx': 'javascript',
'ts': 'typescript',
'tsx': 'typescript'
};
// Update handleInputSubmit to ensure the input is sent properly
const handleInputSubmit = (input) => {
// Use the direct input parameter instead of relying on userInput state
const textToSend = input || userInput;
return languageMap[extension] || extension;
console.log("Input submit called, active socket state:",
activeSocket ? activeSocket.readyState : "no socket",
"input:", textToSend);
if (!activeSocket) {
console.warn("Cannot send input: No active socket");
setTerminalOutput(prev => [...prev, {
type: 'warning',
content: `Cannot send input: No active connection`
}]);
return;
}
if (activeSocket.readyState !== WebSocket.OPEN) {
console.warn("Socket not in OPEN state:", activeSocket.readyState);
setTerminalOutput(prev => [...prev, {
type: 'warning',
content: `Cannot send input: Connection not open (state: ${activeSocket.readyState})`
}]);
return;
}
try {
// Add the input to the terminal display
setTerminalOutput(prev => [...prev, { type: 'command', content: `> ${textToSend}` }]);
// Send the input via WebSocket
console.log("Sending input:", textToSend);
// Instead of just sending the raw input, send a formatted input message
// This helps the backend identify it as user input rather than a command
activeSocket.send(JSON.stringify({
type: "input",
content: textToSend
}));
// Clear the input field
setUserInput("");
} catch (error) {
console.error("Error sending input:", error);
setTerminalOutput(prev => [...prev, {
type: 'warning',
content: `Error sending input: ${error.message}`
}]);
}
};
// Update this function to also update parent state
@@ -834,18 +1070,17 @@ Happy coding!`;
document.addEventListener("mouseup", onMouseUp);
}}
/>
<Panel
height={panelHeight}
terminalOutput={terminalOutput}
isRunning={isRunning}
waitingForInput={waitingForInput}
activeRunningFile={activeRunningFile}
initialTab="terminal"
onClose={togglePanel}
userInput={userInput}
onUserInputChange={setUserInput}
onInputSubmit={handleInputSubmit}
/>
<Panel
height={panelHeight}
terminalOutput={terminalOutput}
isRunning={isRunning}
activeRunningFile={activeRunningFile}
initialTab="terminal"
onClose={togglePanel}
userInput={userInput}
onUserInputChange={setUserInput}
onInputSubmit={handleInputSubmit}
/>
</>
)}

View File

@@ -0,0 +1,14 @@
const Footer = () => {
return (
<footer className="footer-bar fixed bottom-0 left-0 right-0 border-t border-slate-200/40 dark:border-gray-800/20 bg-black">
<div className="flex items-center justify-center h-7">
<span className="text-xs text-slate-400 dark:text-gray-400 flex items-center">
Copyright © 2025. Made with
by Ishika and Arnab.
</span>
</div>
</footer>
);
};
export default Footer;

View File

@@ -0,0 +1,41 @@
import { useAuth } from '../contexts/AuthContext';
import { useNavigate } from 'react-router-dom';
const Header = () => {
const { user, logout } = useAuth();
const navigate = useNavigate();
const handleLogout = () => {
logout();
navigate('/login');
};
return (
<header className="bg-gray-800 border-b border-gray-700 px-4 py-2 flex items-center justify-between">
<div className="flex items-center space-x-4">
<h1 className="text-white font-bold text-lg">Monaco Editor</h1>
</div>
<div className="flex items-center space-x-4">
{user?.picture && (
<img
src={user.picture}
alt="Profile"
className="w-8 h-8 rounded-full"
/>
)}
<span className="text-gray-300 text-sm">
Welcome, {user?.name || user?.email}
</span>
<button
onClick={handleLogout}
className="bg-red-600 hover:bg-red-700 text-white text-sm px-3 py-1 rounded transition-colors duration-200"
>
Logout
</button>
</div>
</header>
);
};
export default Header;

View File

@@ -0,0 +1,161 @@
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { GoogleLogin } from '@react-oauth/google';
import { useAuth } from '../contexts/AuthContext';
import ThemeToggle from './ThemeToggle';
const Login = () => {
const [error, setError] = useState('');
const navigate = useNavigate();
const { login } = useAuth();
// Check if user is already logged in
useEffect(() => {
const token = localStorage.getItem('monaco_token');
if (token) {
navigate('/tests');
}
}, [navigate]);
const handleLoginSuccess = async (credentialResponse) => {
console.log('Google login success:', credentialResponse);
if (credentialResponse.credential) {
try {
console.log('Processing Google credential...');
// For demo purposes, we'll decode the JWT token to get user info
// In a real app, you would send this to your backend for verification
const base64Url = credentialResponse.credential.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
const userInfo = JSON.parse(jsonPayload);
console.log('User info:', userInfo);
const success = await login(userInfo.email, credentialResponse.credential, userInfo);
if (success) {
navigate('/tests');
} else {
throw new Error('Authentication failed');
}
} catch (error) {
console.error('Error during login:', error);
setError(`Authentication failed: ${error.message || 'Please try again.'}`);
}
} else {
console.error('No credential received from Google');
setError('No credential received from Google. Please try again.');
}
};
const handleLoginError = () => {
console.error('Google login failed - checking network and configuration...');
// Check if we're online
if (!navigator.onLine) {
setError('You appear to be offline. Please check your internet connection and try again.');
return;
}
// Check if Google Identity Services script loaded
if (typeof window !== 'undefined' && !window.google) {
console.error('Google Identity Services script not loaded');
setError('Google authentication service is not available. Please refresh the page and try again.');
return;
}
setError('Google login failed. This might be due to network connectivity issues, browser compatibility, or Google account configuration. Please try again or contact support if the problem persists.');
};
return (
<div className="login-container">
{/* Theme Toggle - Top Right */}
<div className="theme-toggle">
<ThemeToggle />
</div>
{/* Left Side - Background Image */}
<div className="login-left">
<img
src="/BG-login(2).jpg"
alt="Login Background"
className="login-bg-image"
/>
</div>
{/* Right Side - Login Form */}
<div className="login-right">
<div className="login-form-container">
{/* Logos */}
<div className="login-logos">
<img
src="/Vidyavihar@3x.png"
alt="KJSCE"
className="login-logo"
/>
<img
src="/kjsce2x.png"
alt="Somaiya Vidyavihar"
className="login-logo"
/>
</div>
{/* Title */}
<h1 className="login-title">
Welcome To Monaco Editor
</h1>
<p className="login-subtitle">
Please sign in with your Google account to continue.
</p>
{/* Error Display */}
{error && (
<div className="login-error">
<p style={{ fontSize: '0.875rem', margin: 0 }}>{error}</p>
</div>
)}
{/* Google Login Button */}
<div style={{ display: 'flex', justifyContent: 'center', marginBottom: '1.5rem' }}>
<GoogleLogin
onSuccess={handleLoginSuccess}
onError={handleLoginError}
useOneTap
/>
</div>
<div className="login-footer">
<p className="login-footer-text">
Need help?{' '}
<button className="login-footer-link">
Contact admin
</button>
</p>
</div>
<div className="login-demo-note">
<p className="login-demo-text">
Sign in with your Google account to access the Monaco Editor
</p>
</div>
{/* Trust Logo */}
<div className="login-trust-logo">
<img
src="/Bottom.png"
alt="Somaiya Trust"
className="trust-logo-img"
/>
</div>
</div>
</div>
</div>
);
};
export default Login;

View File

@@ -1,150 +0,0 @@
import React from "react"
"use client"
import Link from "next/link"
import { ChevronDown } from "lucide-react"
import { Button } from "@/components/ui/button"
import {
NavigationMenu,
NavigationMenuContent,
NavigationMenuItem,
NavigationMenuLink,
NavigationMenuList,
NavigationMenuTrigger,
} from "@/components/ui/navigation-menu"
export function Navbar() {
return (
<header className="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<div className="container flex h-16 items-center justify-between">
<Link href="/" className="flex items-center space-x-2">
<span className="text-xl font-bold">*Azzle</span>
</Link>
<NavigationMenu className="hidden md:flex">
<NavigationMenuList>
<NavigationMenuItem>
<NavigationMenuTrigger>
Demo <ChevronDown className="h-4 w-4" />
</NavigationMenuTrigger>
<NavigationMenuContent>
<div className="grid gap-3 p-6 w-[400px]">
<NavigationMenuLink asChild>
<Link
href="/demo/features"
className="block select-none space-y-1 rounded-md p-3 leading-none no-underline outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground"
>
<div className="text-sm font-medium leading-none">Features</div>
<p className="line-clamp-2 text-sm leading-snug text-muted-foreground">
Explore all the features our platform has to offer
</p>
</Link>
</NavigationMenuLink>
<NavigationMenuLink asChild>
<Link
href="/demo/pricing"
className="block select-none space-y-1 rounded-md p-3 leading-none no-underline outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground"
>
<div className="text-sm font-medium leading-none">Pricing</div>
<p className="line-clamp-2 text-sm leading-snug text-muted-foreground">
View our flexible pricing plans
</p>
</Link>
</NavigationMenuLink>
</div>
</NavigationMenuContent>
</NavigationMenuItem>
<NavigationMenuItem>
<Link href="/about" legacyBehavior passHref>
<NavigationMenuLink className="group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50">
About
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
<NavigationMenuItem>
<NavigationMenuTrigger>
Services <ChevronDown className="h-4 w-4" />
</NavigationMenuTrigger>
<NavigationMenuContent>
<div className="grid gap-3 p-6 w-[400px]">
<NavigationMenuLink asChild>
<Link
href="/services/consulting"
className="block select-none space-y-1 rounded-md p-3 leading-none no-underline outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground"
>
<div className="text-sm font-medium leading-none">Consulting</div>
<p className="line-clamp-2 text-sm leading-snug text-muted-foreground">
Expert guidance for your business needs
</p>
</Link>
</NavigationMenuLink>
<NavigationMenuLink asChild>
<Link
href="/services/implementation"
className="block select-none space-y-1 rounded-md p-3 leading-none no-underline outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground"
>
<div className="text-sm font-medium leading-none">Implementation</div>
<p className="line-clamp-2 text-sm leading-snug text-muted-foreground">
Full-service implementation and support
</p>
</Link>
</NavigationMenuLink>
</div>
</NavigationMenuContent>
</NavigationMenuItem>
<NavigationMenuItem>
<NavigationMenuTrigger>
Pages <ChevronDown className="h-4 w-4" />
</NavigationMenuTrigger>
<NavigationMenuContent>
<div className="grid gap-3 p-6 w-[400px]">
<NavigationMenuLink asChild>
<Link
href="/blog"
className="block select-none space-y-1 rounded-md p-3 leading-none no-underline outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground"
>
<div className="text-sm font-medium leading-none">Blog</div>
<p className="line-clamp-2 text-sm leading-snug text-muted-foreground">
Read our latest articles and updates
</p>
</Link>
</NavigationMenuLink>
<NavigationMenuLink asChild>
<Link
href="/resources"
className="block select-none space-y-1 rounded-md p-3 leading-none no-underline outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground"
>
<div className="text-sm font-medium leading-none">Resources</div>
<p className="line-clamp-2 text-sm leading-snug text-muted-foreground">
Helpful guides and documentation
</p>
</Link>
</NavigationMenuLink>
</div>
</NavigationMenuContent>
</NavigationMenuItem>
<NavigationMenuItem>
<Link href="/contact" legacyBehavior passHref>
<NavigationMenuLink className="group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50">
Contact
</NavigationMenuLink>
</Link>
</NavigationMenuItem>
</NavigationMenuList>
</NavigationMenu>
<div className="flex items-center space-x-4">
<Button variant="ghost" asChild>
<Link href="/login">Login</Link>
</Button>
<Button asChild>
<Link href="/signup">Sign up free</Link>
</Button>
</div>
</div>
</header>
)
}
export default Navbar

View File

@@ -1,6 +1,5 @@
import React from "react";
import { useState, useEffect } from "react";
import { X } from "lucide-react";
import React, { useState, useEffect, useRef } from "react";
import { X, Maximize2, ChevronDown, Plus } from "lucide-react";
const Panel = ({
height,
@@ -12,85 +11,135 @@ const Panel = ({
onClose,
userInput = "",
onUserInputChange,
onInputSubmit
onInputSubmit,
}) => {
const [activeTab, setActiveTab] = useState(initialTab);
const terminalRef = useRef(null);
const [inputBuffer, setInputBuffer] = useState("");
// Set active tab when initialTab changes
// Update active tab when initialTab changes
useEffect(() => {
setActiveTab(initialTab);
}, [initialTab]);
const renderTerminal = () => {
return (
<div className="panel-terminal">
{terminalOutput.length > 0 ? (
// Render output from EditorArea when available
<>
{terminalOutput.map((line, index) => (
<div key={index} className={`terminal-line ${line.type === 'warning' ? 'terminal-warning' : 'terminal-output'}`}>
{line.type === 'command' ? <span className="terminal-prompt">$</span> : ''} {line.content}
// Auto-scroll terminal to the bottom when content changes
useEffect(() => {
if (terminalRef.current) {
terminalRef.current.scrollTop = terminalRef.current.scrollHeight;
}
}, [terminalOutput]);
// Handle keyboard input for the terminal
useEffect(() => {
const handleKeyDown = (e) => {
if (!isRunning) return;
if (e.key === "Enter") {
if (inputBuffer.trim() && onInputSubmit) {
e.preventDefault();
// Update parent's userInput state directly and call submit in the same function
// instead of using setTimeout which creates a race condition
onUserInputChange(inputBuffer);
onInputSubmit(inputBuffer); // Pass inputBuffer directly to avoid race condition
setInputBuffer("");
}
} else if (e.key === "Backspace") {
setInputBuffer((prev) => prev.slice(0, -1));
} else if (e.key.length === 1) {
setInputBuffer((prev) => prev + e.key);
}
};
const terminalElement = terminalRef.current;
terminalElement?.addEventListener("keydown", handleKeyDown);
return () => {
terminalElement?.removeEventListener("keydown", handleKeyDown);
};
}, [isRunning, inputBuffer, onInputSubmit, onUserInputChange]);
// Render the terminal tab
const renderTerminal = () => (
<div
className="panel-terminal"
ref={terminalRef}
tabIndex={0} // Make div focusable
onClick={() => terminalRef.current?.focus()} // Focus when clicked
>
{terminalOutput.length > 0 ? (
<>
{terminalOutput.map((line, index) => {
const typeClass =
line.type === "warning"
? "terminal-warning"
: line.type === "error"
? "terminal-error"
: "terminal-output";
return (
<div key={index} className={`terminal-line ${typeClass}`}>
{line.timestamp && (
<span className="terminal-timestamp">{line.timestamp} </span>
)}
{line.type === "command" && <span className="terminal-prompt">$</span>}
{line.content}
</div>
))}
{waitingForInput && (
<div className="terminal-line">
<span className="terminal-prompt">Input:</span>
<input
type="text"
className="terminal-input"
value={userInput}
onChange={(e) => onUserInputChange && onUserInputChange(e.target.value)}
placeholder="Enter input for your program here..."
onKeyDown={(e) => {
if (e.key === 'Enter' && onInputSubmit) {
onInputSubmit();
}
}}
autoFocus
/>
</div>
)}
</>
) : (
// Default terminal content when no output
<>
<div className="terminal-line">
<span className="terminal-prompt">$</span> npm start
);
})}
{isRunning && (
<div className="terminal-line terminal-input-line">
<span className="terminal-prompt">$</span> {inputBuffer}
<span className="terminal-cursor"></span>
</div>
<div className="terminal-line terminal-output">Starting the development server...</div>
<div className="terminal-line terminal-output">Compiled successfully!</div>
<div className="terminal-line terminal-output">You can now view vscode-clone in the browser.</div>
<div className="terminal-line terminal-output">Local: http://localhost:3000</div>
<div className="terminal-line terminal-output">On Your Network: http://192.168.1.5:3000</div>
<div className="terminal-line">
<span className="terminal-prompt">$</span>
</div>
</>
)}
</div>
);
};
)}
</>
) : (
<div className="terminal-line">
<span className="terminal-prompt">$</span>
<span className="terminal-cursor"></span>
</div>
)}
</div>
);
const renderProblems = () => {
return (
<div className="panel-problems">
<div className="panel-empty-message">No problems have been detected in the workspace.</div>
</div>
);
};
// Render other tabs
const renderProblems = () => (
<div className="panel-problems">
<div className="panel-empty-message">No problems have been detected in the workspace.</div>
</div>
);
const renderOutput = () => {
return (
<div className="panel-output">
<div className="output-line">[Extension Host] Extension host started.</div>
<div className="output-line">[Language Server] Language server started.</div>
{activeRunningFile && (
<div className="output-line">[Running] {activeRunningFile}</div>
)}
</div>
);
};
const renderOutput = () => (
<div className="panel-output">
<div className="output-line">[Extension Host] Extension host started.</div>
<div className="output-line">[Language Server] Language server started.</div>
{activeRunningFile && (
<div className="output-line">[Running] {activeRunningFile}</div>
)}
</div>
);
const renderDebugConsole = () => (
<div className="panel-debug-console">
<div className="debug-line">Debug session not yet started.</div>
<div className="debug-line">Press F5 to start debugging.</div>
</div>
);
const renderPorts = () => (
<div className="panel-ports">
<div className="ports-line">No forwarded ports detected.</div>
</div>
);
const renderComments = () => (
<div className="panel-comments">
<div className="comments-line">No comments have been added to this workspace.</div>
</div>
);
// Get content for the active tab
const getTabContent = () => {
switch (activeTab) {
case "terminal":
@@ -99,6 +148,12 @@ const Panel = ({
return renderProblems();
case "output":
return renderOutput();
case "debug":
return renderDebugConsole();
case "ports":
return renderPorts();
case "comments":
return renderComments();
default:
return <div>Unknown tab</div>;
}
@@ -107,76 +162,29 @@ const Panel = ({
return (
<div className="panel" style={{ height: `${height}px` }}>
<div className="panel-tabs">
<div
className={`panel-tab ${activeTab === "problems" ? "active" : ""}`}
onClick={() => setActiveTab("problems")}
>
<span className="tab-icon">
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="12" cy="12" r="10"></circle>
<line x1="12" y1="8" x2="12" y2="12"></line>
<line x1="12" y1="16" x2="12.01" y2="16"></line>
</svg>
</span>
<span className="tab-name">Problems</span>
</div>
<div className={`panel-tab ${activeTab === "output" ? "active" : ""}`} onClick={() => setActiveTab("output")}>
<span className="tab-icon">
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="12" cy="12" r="10"></circle>
<line x1="12" y1="16" x2="12" y2="12"></line>
<line x1="12" y1="8" x2="12.01" y2="8"></line>
</svg>
</span>
<span className="tab-name">Output</span>
</div>
<div
className={`panel-tab ${activeTab === "terminal" ? "active" : ""}`}
onClick={() => setActiveTab("terminal")}
>
<span className="tab-icon">
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<polyline points="4 17 10 11 4 5"></polyline>
<line x1="12" y1="19" x2="20" y2="19"></line>
</svg>
</span>
<span className="tab-name">Terminal</span>
</div>
{["problems", "output", "debug", "terminal", "ports", "comments"].map((tab) => (
<div
key={tab}
className={`panel-tab ${activeTab === tab ? "active" : ""}`}
onClick={() => setActiveTab(tab)}
>
<span className="tab-name">{tab.toUpperCase()}</span>
</div>
))}
{/* Add close button */}
<div className="panel-actions">
{/* <button className="panel-action-btn">
<span className="current-terminal">node - frontend</span>
<ChevronDown size={16} />
</button>
<button className="panel-action-btn">
<Plus size={16} />
</button>
<button className="panel-action-btn">
<Maximize2 size={16} />
</button> */}
<button className="panel-close-btn" onClick={onClose}>
<X size={14} />
<X size={16} />
</button>
</div>
</div>
@@ -187,4 +195,3 @@ const Panel = ({
};
export default Panel;

View File

@@ -0,0 +1,21 @@
import { Navigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
const ProtectedRoute = ({ children }) => {
const { isAuthenticated, isLoading } = useAuth();
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center bg-black">
<div className="text-center">
<div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-white"></div>
<p className="mt-4 text-white">Loading...</p>
</div>
</div>
);
}
return isAuthenticated ? children : <Navigate to="/login" replace />;
};
export default ProtectedRoute;

View File

@@ -75,21 +75,6 @@ const Sidebar = ({
</svg>
)}
</span>
<span className="folder-icon">
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="#75beff"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path>
</svg>
</span>
<span className="folder-name">{name}</span>
</div>
{isExpanded && (
@@ -184,10 +169,38 @@ const Sidebar = ({
</div>
);
};
const getFileIcon = (fileName) => {
const extension = fileName.split('.').pop().toLowerCase();
if (fileName.toLowerCase() === 'readme.md') {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="#007acc" /* Blue color for the circle */
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="12" cy="12" r="10" fill="none" stroke="#007acc" />
<text
x="12"
y="15"
textAnchor="middle"
fontSize="10"
fill="#007acc"
fontFamily="Arial, sans-serif"
fontWeight="bold"
>
i
</text>
</svg>
);
}
if (['jsx', 'js', 'ts', 'tsx'].includes(extension)) {
return (
<svg

View File

@@ -1,10 +1,11 @@
import React from "react";
"use client"
const StatusBar = ({ togglePanel, panelVisible }) => {
return (
<div className="status-bar">
{/* Left Section of the Status Bar */}
<div className="status-bar-left">
{/* Branch Indicator */}
<div className="status-item">
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -16,6 +17,7 @@ const StatusBar = ({ togglePanel, panelVisible }) => {
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-label="Branch Icon"
>
<line x1="6" y1="3" x2="6" y2="15"></line>
<circle cx="18" cy="6" r="3"></circle>
@@ -25,6 +27,7 @@ const StatusBar = ({ togglePanel, panelVisible }) => {
<span>main</span>
</div>
{/* Error Indicator */}
<div className="status-item">
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -36,30 +39,14 @@ const StatusBar = ({ togglePanel, panelVisible }) => {
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-label="Error Icon"
>
<polyline points="20 6 9 17 4 12"></polyline>
</svg>
<span>0 errors</span>
</div>
<button className="status-item status-button" onClick={togglePanel}>
<span>{panelVisible ? "Hide Terminal" : "Show Terminal"}</span>
</button>
</div>
<div className="status-bar-right">
<div className="status-item">
<span>Ln 1, Col 1</span>
</div>
<div className="status-item">
<span>Spaces: 2</span>
</div>
<div className="status-item">
<span>UTF-8</span>
</div>
{/* Warning Indicator */}
<div className="status-item">
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -71,6 +58,65 @@ const StatusBar = ({ togglePanel, panelVisible }) => {
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-label="Warning Icon"
>
<path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path>
<line x1="12" y1="9" x2="12" y2="13"></line>
<line x1="12" y1="17" x2="12.01" y2="17"></line>
</svg>
<span>0 warnings</span>
</div>
{/* Toggle Terminal Button */}
<button
className="status-item status-button"
onClick={togglePanel}
aria-label="Toggle Terminal"
>
<span>{panelVisible ? "Hide Terminal" : "Show Terminal"}</span>
</button>
</div>
{/* Right Section of the Status Bar */}
<div className="status-bar-right">
{/* Line and Column Indicator */}
<div className="status-item">
<span>Ln 1, Col 1</span>
</div>
{/* Spaces Indicator */}
<div className="status-item">
<span>Spaces: 2</span>
</div>
{/* Encoding Indicator */}
<div className="status-item">
<span>UTF-8</span>
</div>
{/* Language Mode */}
<div className="status-item">
<span>JavaScript</span>
</div>
{/* EOL (End of Line) Indicator */}
<div className="status-item">
<span>LF</span>
</div>
{/* Connection Status */}
<div className="status-item">
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-label="Connection Icon"
>
<path d="M5 12.55a11 11 0 0 1 14.08 0"></path>
<path d="M1.42 9a16 16 0 0 1 21.16 0"></path>
@@ -80,6 +126,7 @@ const StatusBar = ({ togglePanel, panelVisible }) => {
<span>Connected</span>
</div>
{/* Bell Icon */}
<div className="status-item">
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -91,6 +138,7 @@ const StatusBar = ({ togglePanel, panelVisible }) => {
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-label="Bell Icon"
>
<path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path>
<path d="M13.73 21a2 2 0 0 1-3.46 0"></path>
@@ -98,8 +146,7 @@ const StatusBar = ({ togglePanel, panelVisible }) => {
</div>
</div>
</div>
)
}
export default StatusBar
);
};
export default StatusBar;

View File

@@ -0,0 +1,688 @@
/* TestList.css */
.test-list-container {
min-height: 100vh;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}
.dark .test-list-container {
background: linear-gradient(135deg, #1a1a1a 0%, #2d3748 100%);
}
.test-list-header {
background: white;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
border-bottom: 1px solid #e5e7eb;
padding: 1.5rem 0;
}
.dark .test-list-header {
background: #1f2937;
border-bottom-color: #374151;
}
.header-content {
max-width: 1280px;
margin: 0 auto;
padding: 0 1rem;
display: flex;
flex-direction: column;
gap: 1rem;
}
@media (min-width: 768px) {
.header-content {
flex-direction: row;
align-items: center;
justify-content: space-between;
}
}
.header-title {
font-size: 2rem;
font-weight: 700;
color: #111827;
margin: 0 0 0.5rem 0;
}
.dark .header-title {
color: white;
}
.header-subtitle {
color: #6b7280;
margin: 0;
}
.dark .header-subtitle {
color: #9ca3af;
}
.filter-tabs {
display: flex;
gap: 0.5rem;
background: #f3f4f6;
padding: 0.25rem;
border-radius: 0.5rem;
}
.dark .filter-tabs {
background: #374151;
}
.filter-tab {
padding: 0.5rem 1rem;
border-radius: 0.375rem;
font-size: 0.875rem;
font-weight: 500;
border: none;
background: transparent;
color: #6b7280;
cursor: pointer;
transition: all 0.2s;
}
.filter-tab:hover {
color: #111827;
}
.dark .filter-tab {
color: #9ca3af;
}
.dark .filter-tab:hover {
color: white;
}
.filter-tab.active {
background: white;
color: #2563eb;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}
.dark .filter-tab.active {
background: #4b5563;
color: #60a5fa;
}
.test-list-content {
max-width: 1280px;
margin: 0 auto;
padding: 2rem 1rem;
}
.tests-grid {
display: grid;
grid-template-columns: 1fr;
gap: 1.5rem;
}
@media (min-width: 768px) {
.tests-grid {
grid-template-columns: repeat(2, 1fr);
}
}
@media (min-width: 1024px) {
.tests-grid {
grid-template-columns: repeat(3, 1fr);
}
}
.test-card {
background: white;
border-radius: 0.75rem;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
overflow: hidden;
border: 1px solid #e5e7eb;
transition: all 0.3s;
}
.test-card:hover {
box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
border-color: #93c5fd;
transform: translateY(-2px);
}
.dark .test-card {
background: #1f2937;
border-color: #374151;
}
.dark .test-card:hover {
border-color: #3b82f6;
}
.test-card-stripe {
height: 0.5rem;
background: linear-gradient(90deg, #3b82f6 0%, #8b5cf6 100%);
}
.test-card-content {
padding: 1.5rem;
}
.test-card-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
margin-bottom: 1rem;
}
.test-title {
font-size: 1.25rem;
font-weight: 700;
color: #111827;
margin: 0;
transition: color 0.2s;
}
.test-card:hover .test-title {
color: #2563eb;
}
.dark .test-title {
color: white;
}
.dark .test-card:hover .test-title {
color: #60a5fa;
}
.status-badge {
padding: 0.25rem 0.75rem;
border-radius: 9999px;
font-size: 0.75rem;
font-weight: 600;
display: flex;
align-items: center;
gap: 0.25rem;
white-space: nowrap;
}
.status-dot {
width: 0.5rem;
height: 0.5rem;
border-radius: 9999px;
}
.status-active .status-dot {
background: #10b981;
animation: pulse 2s infinite;
}
.status-active {
background: #d1fae5;
color: #065f46;
}
.dark .status-active {
background: rgba(16, 185, 129, 0.2);
color: #6ee7b7;
}
.status-upcoming {
background: #dbeafe;
color: #1e40af;
}
.status-upcoming .status-dot {
background: #3b82f6;
}
.dark .status-upcoming {
background: rgba(59, 130, 246, 0.2);
color: #93c5fd;
}
.status-closed {
background: #f3f4f6;
color: #6b7280;
}
.status-closed .status-dot {
background: #9ca3af;
}
.dark .status-closed {
background: #374151;
color: #9ca3af;
}
.test-description {
color: #6b7280;
margin-bottom: 1.5rem;
min-height: 3rem;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.dark .test-description {
color: #9ca3af;
}
.test-details {
display: flex;
flex-direction: column;
gap: 0.75rem;
margin-bottom: 1.5rem;
}
.test-detail {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.875rem;
color: #374151;
}
.dark .test-detail {
color: #d1d5db;
}
.test-detail-icon {
width: 1.25rem;
height: 1.25rem;
flex-shrink: 0;
}
.icon-blue {
color: #3b82f6;
}
.icon-purple {
color: #8b5cf6;
}
.icon-amber {
color: #f59e0b;
}
.test-button {
width: 100%;
padding: 0.75rem 1rem;
border-radius: 0.5rem;
font-weight: 600;
border: none;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
transition: all 0.2s;
}
.test-button-active {
background: linear-gradient(90deg, #3b82f6 0%, #8b5cf6 100%);
color: white;
box-shadow: 0 4px 6px rgba(59, 130, 246, 0.3);
}
.test-button-active:hover {
transform: translateY(-1px);
box-shadow: 0 6px 8px rgba(59, 130, 246, 0.4);
}
.test-button-disabled {
background: #e5e7eb;
color: #9ca3af;
cursor: not-allowed;
}
.dark .test-button-disabled {
background: #374151;
color: #6b7280;
}
.loading-container,
.error-container {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}
.dark .loading-container,
.dark .error-container {
background: linear-gradient(135deg, #1a1a1a 0%, #2d3748 100%);
}
.loading-content {
text-align: center;
}
.spinner {
display: inline-block;
width: 3rem;
height: 3rem;
border: 0.25rem solid #e5e7eb;
border-top-color: #3b82f6;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-bottom: 1rem;
}
.loading-text {
color: #6b7280;
font-size: 1.125rem;
}
.dark .loading-text {
color: #9ca3af;
}
.error-box {
background: #fef2f2;
border: 1px solid #fecaca;
border-radius: 0.5rem;
padding: 1.5rem;
max-width: 28rem;
}
.dark .error-box {
background: rgba(220, 38, 38, 0.1);
border-color: #991b1b;
}
.error-content {
display: flex;
align-items: center;
gap: 0.75rem;
}
.error-icon {
width: 1.5rem;
height: 1.5rem;
color: #dc2626;
flex-shrink: 0;
}
.error-title {
font-weight: 600;
color: #991b1b;
margin: 0 0 0.25rem 0;
}
.dark .error-title {
color: #fca5a5;
}
.error-message {
color: #dc2626;
margin: 0;
}
.dark .error-message {
color: #fca5a5;
}
.empty-state {
text-align: center;
padding: 4rem 1rem;
}
.empty-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 4rem;
height: 4rem;
border-radius: 50%;
background: #e5e7eb;
margin-bottom: 1rem;
}
.dark .empty-icon {
background: #374151;
}
.empty-icon svg {
width: 2rem;
height: 2rem;
color: #9ca3af;
}
.empty-title {
font-size: 1.125rem;
font-weight: 600;
color: #111827;
margin: 0 0 0.5rem 0;
}
.dark .empty-title {
color: white;
}
.empty-message {
color: #6b7280;
margin: 0;
}
.dark .empty-message {
color: #9ca3af;
}
/* Modal */
.modal-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.6);
backdrop-filter: blur(4px);
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
z-index: 1000;
animation: fadeIn 0.3s;
}
.modal-content {
background: white;
border-radius: 1rem;
box-shadow: 0 20px 25px rgba(0, 0, 0, 0.3);
width: 100%;
max-width: 28rem;
animation: slideUp 0.3s;
}
.dark .modal-content {
background: #1f2937;
}
.modal-header {
border-bottom: 1px solid #e5e7eb;
padding: 1.5rem;
}
.dark .modal-header {
border-bottom-color: #374151;
}
.modal-header-content {
display: flex;
align-items: center;
gap: 0.75rem;
}
.modal-icon {
width: 3rem;
height: 3rem;
border-radius: 50%;
background: #dbeafe;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.dark .modal-icon {
background: rgba(59, 130, 246, 0.2);
}
.modal-icon svg {
width: 1.5rem;
height: 1.5rem;
color: #3b82f6;
}
.dark .modal-icon svg {
color: #60a5fa;
}
.modal-title {
font-size: 1.25rem;
font-weight: 700;
color: #111827;
margin: 0;
}
.dark .modal-title {
color: white;
}
.modal-subtitle {
font-size: 0.875rem;
color: #6b7280;
margin: 0;
}
.dark .modal-subtitle {
color: #9ca3af;
}
.modal-body {
padding: 1.5rem;
}
.modal-label {
display: block;
font-size: 0.875rem;
font-weight: 500;
color: #374151;
margin-bottom: 0.5rem;
}
.dark .modal-label {
color: #d1d5db;
}
.modal-input {
width: 100%;
padding: 0.75rem 1rem;
border: 1px solid #d1d5db;
border-radius: 0.5rem;
font-size: 1rem;
transition: all 0.2s;
box-sizing: border-box;
}
.modal-input:focus {
outline: none;
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
.dark .modal-input {
background: #374151;
border-color: #4b5563;
color: white;
}
.dark .modal-input:focus {
border-color: #3b82f6;
}
.modal-footer {
border-top: 1px solid #e5e7eb;
padding: 1.5rem;
display: flex;
gap: 0.75rem;
}
.dark .modal-footer {
border-top-color: #374151;
}
.modal-button {
flex: 1;
padding: 0.625rem 1rem;
border-radius: 0.5rem;
font-weight: 500;
border: none;
cursor: pointer;
transition: all 0.2s;
}
.modal-button-cancel {
background: #f3f4f6;
color: #374151;
}
.modal-button-cancel:hover {
background: #e5e7eb;
}
.dark .modal-button-cancel {
background: #374151;
color: #d1d5db;
}
.dark .modal-button-cancel:hover {
background: #4b5563;
}
.modal-button-submit {
background: linear-gradient(90deg, #3b82f6 0%, #8b5cf6 100%);
color: white;
}
.modal-button-submit:hover:not(:disabled) {
opacity: 0.9;
}
.modal-button-submit:disabled {
background: #9ca3af;
cursor: not-allowed;
}
.dark .modal-button-submit:disabled {
background: #4b5563;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@keyframes pulse {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.5;
}
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes slideUp {
from {
transform: translateY(1.25rem);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}

View File

@@ -0,0 +1,354 @@
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import './TestList.css';
const TestList = () => {
const [tests, setTests] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [showPasswordModal, setShowPasswordModal] = useState(false);
const [selectedTest, setSelectedTest] = useState(null);
const [password, setPassword] = useState('');
const [filterStatus, setFilterStatus] = useState('all');
const navigate = useNavigate();
const { token } = useAuth();
useEffect(() => {
fetchTests();
}, []);
const fetchTests = async () => {
try {
console.log('Fetching tests with token:', token?.substring(0, 50) + '...');
const API_URL = import.meta.env.VITE_FACULTY_API_URL || 'http://localhost:5000/api';
const response = await fetch(`${API_URL}/students/tests`, {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (!response.ok) {
if (response.status === 401) {
localStorage.removeItem('monaco_user');
localStorage.removeItem('monaco_token');
window.location.href = '/login';
return;
}
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (data.success) {
console.log('Tests received:', data.tests);
data.tests.forEach(test => {
console.log(`Test: ${test.title}, Status: ${test.status}, Start: ${test.start_time}, End: ${test.end_time}`);
});
setTests(data.tests);
} else {
setError(data.message || 'Failed to fetch tests');
}
} catch (error) {
setError('Failed to fetch tests');
console.error('Error:', error);
} finally {
setLoading(false);
}
};
const handleStartTest = async (test) => {
try {
const API_URL = import.meta.env.VITE_FACULTY_API_URL || 'http://localhost:5000/api';
const response = await fetch(`${API_URL}/students/tests/${test.id}/questions`, {
headers: {
'Authorization': `Bearer ${token}`
}
});
const data = await response.json();
if (data.success) {
localStorage.setItem('currentTest', JSON.stringify({
id: test.id,
title: test.title,
description: test.description,
duration_minutes: test.duration_minutes,
start_time: test.start_time,
end_time: test.end_time,
questions: data.questions,
currentQuestionIndex: 0
}));
navigate('/editor');
} else {
setError(data.message);
}
} catch (error) {
setError('Failed to start test');
console.error('Error:', error);
}
};
const handlePasswordSubmit = async () => {
if (!selectedTest || !password) return;
try {
const API_URL = import.meta.env.VITE_FACULTY_API_URL || 'http://localhost:5000/api';
const response = await fetch(`${API_URL}/students/tests/${selectedTest.id}/verify-password`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ password })
});
const data = await response.json();
if (data.success) {
setShowPasswordModal(false);
setPassword('');
handleStartTest(selectedTest);
} else {
setError('Invalid password');
}
} catch (error) {
setError('Failed to verify password');
console.error('Error:', error);
}
};
const handleTestClick = (test) => {
if (test.password_required) {
setSelectedTest(test);
setShowPasswordModal(true);
} else {
handleStartTest(test);
}
};
const filteredTests = tests.filter(test => {
if (filterStatus === 'all') return true;
return test.status.toLowerCase() === filterStatus.toLowerCase();
});
if (loading) {
return (
<div className="loading-container">
<div className="loading-content">
<div className="spinner"></div>
<p className="loading-text">Loading tests...</p>
</div>
</div>
);
}
if (error) {
return (
<div className="error-container">
<div className="error-box">
<div className="error-content">
<svg className="error-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<div>
<h3 className="error-title">Error</h3>
<p className="error-message">{error}</p>
</div>
</div>
</div>
</div>
);
}
return (
<div className="test-list-container">
{/* Header Section */}
<div className="test-list-header">
<div className="header-content">
<div>
<h1 className="header-title">
📝 Available Tests
</h1>
<p className="header-subtitle">
Select a test to start your coding challenge
</p>
</div>
{/* Filter Tabs */}
<div className="filter-tabs">
<button
onClick={() => setFilterStatus('all')}
className={`filter-tab ${filterStatus === 'all' ? 'active' : ''}`}
>
All Tests
</button>
<button
onClick={() => setFilterStatus('active')}
className={`filter-tab ${filterStatus === 'active' ? 'active' : ''}`}
>
Active
</button>
<button
onClick={() => setFilterStatus('upcoming')}
className={`filter-tab ${filterStatus === 'upcoming' ? 'active' : ''}`}
>
Upcoming
</button>
</div>
</div>
</div>
{/* Tests Grid */}
<div className="test-list-content">
{filteredTests.length === 0 ? (
<div className="empty-state">
<div className="empty-icon">
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
</div>
<h3 className="empty-title">No tests available</h3>
<p className="empty-message">Check back later for new tests</p>
</div>
) : (
<div className="tests-grid">
{filteredTests.map(test => (
<div key={test.id} className="test-card">
{/* Status Badge */}
<div className="test-card-stripe"></div>
<div className="test-card-content">
{/* Header */}
<div className="test-card-header">
<h2 className="test-title">
{test.title}
</h2>
<span className={`status-badge status-${test.status?.toLowerCase() || 'closed'}`}>
<span className="status-dot"></span>
{test.status}
</span>
</div>
{/* Description */}
<p className="test-description">
{test.description || 'No description available'}
</p>
{/* Test Details */}
<div className="test-details">
<div className="test-detail">
<svg className="test-detail-icon icon-blue" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span><strong>{test.duration_minutes}</strong> minutes</span>
</div>
{test.total_questions && (
<div className="test-detail">
<svg className="test-detail-icon icon-purple" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
</svg>
<span><strong>{test.total_questions}</strong> questions</span>
</div>
)}
{test.password_required && (
<div className="test-detail icon-amber">
<svg className="test-detail-icon icon-amber" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
</svg>
<span><strong>Password required</strong></span>
</div>
)}
</div>
{/* Action Button */}
<button
onClick={() => handleTestClick(test)}
disabled={test.status !== 'Active'}
className={`test-button ${
test.status === 'Active' ? 'test-button-active' : 'test-button-disabled'
}`}
>
{test.status === 'Active' ? (
<>
<span>Start Test</span>
<svg style={{width: '1.25rem', height: '1.25rem'}} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 7l5 5m0 0l-5 5m5-5H6" />
</svg>
</>
) : (
<>
<svg style={{width: '1.25rem', height: '1.25rem'}} fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
</svg>
<span>Not Available</span>
</>
)}
</button>
</div>
</div>
))}
</div>
)}
</div>
{/* Password Modal */}
{showPasswordModal && (
<div className="modal-overlay">
<div className="modal-content">
{/* Modal Header */}
<div className="modal-header">
<div className="modal-header-content">
<div className="modal-icon">
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
</svg>
</div>
<div>
<h2 className="modal-title">Protected Test</h2>
<p className="modal-subtitle">Enter password to continue</p>
</div>
</div>
</div>
{/* Modal Body */}
<div className="modal-body">
<label className="modal-label">
Test Password
</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handlePasswordSubmit()}
className="modal-input"
placeholder="Enter password"
autoFocus
/>
</div>
{/* Modal Footer */}
<div className="modal-footer">
<button
onClick={() => {
setShowPasswordModal(false);
setPassword('');
setError(null);
}}
className="modal-button modal-button-cancel"
>
Cancel
</button>
<button
onClick={handlePasswordSubmit}
disabled={!password}
className="modal-button modal-button-submit"
>
Submit
</button>
</div>
</div>
</div>
)}
</div>
);
};
export default TestList;

View File

@@ -0,0 +1,61 @@
import { useState, useEffect } from 'react';
const ThemeToggle = () => {
const [theme, setTheme] = useState('dark');
useEffect(() => {
// Check if there's a saved theme preference
const savedTheme = localStorage.getItem('monaco_theme');
if (savedTheme) {
setTheme(savedTheme);
} else {
// Check system preference
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
setTheme(prefersDark ? 'dark' : 'light');
}
}, []);
useEffect(() => {
// Update the HTML class and CSS variables
const root = document.documentElement;
root.className = theme;
// Save theme preference
localStorage.setItem('monaco_theme', theme);
}, [theme]);
const toggleTheme = () => {
setTheme(prevTheme => prevTheme === 'light' ? 'dark' : 'light');
};
return (
<button
onClick={toggleTheme}
className="relative p-2 rounded-md border border-gray-600 bg-gray-800 hover:bg-gray-700 transition-colors"
aria-label={`Switch to ${theme === 'light' ? 'dark' : 'light'} theme`}
>
{/* Sun Icon for Light Mode */}
<svg
className={`h-5 w-5 transition-all ${theme === 'dark' ? 'rotate-90 scale-0' : 'rotate-0 scale-100'}`}
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<circle cx="12" cy="12" r="5" />
<path d="M12 1v2m0 18v2M4.22 4.22l1.42 1.42m12.72 12.72l1.42 1.42M1 12h2m18 0h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42" />
</svg>
{/* Moon Icon for Dark Mode */}
<svg
className={`absolute top-2 left-2 h-5 w-5 transition-all ${theme === 'dark' ? 'rotate-0 scale-100' : 'rotate-90 scale-0'}`}
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
</svg>
</button>
);
};
export default ThemeToggle;

View File

@@ -0,0 +1,121 @@
import { createContext, useContext, useState, useEffect } from 'react';
const AuthContext = createContext();
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [token, setToken] = useState(null);
const [isLoading, setIsLoading] = useState(true);
// Check for existing session on app load
useEffect(() => {
const checkAuthStatus = () => {
try {
const savedUser = localStorage.getItem('monaco_user');
const savedToken = localStorage.getItem('monaco_token');
if (savedUser && savedToken) {
setUser(JSON.parse(savedUser));
setToken(savedToken);
}
} catch (error) {
console.error('Error checking auth status:', error);
localStorage.removeItem('monaco_user');
localStorage.removeItem('monaco_token');
} finally {
setIsLoading(false);
}
};
checkAuthStatus();
}, []);
const login = async (email, googleToken, userInfo = null) => {
// For Google OAuth login
if (googleToken && userInfo) {
// Exchange Google token for our JWT
const API_URL = import.meta.env.VITE_FACULTY_API_URL || 'http://localhost:5000/api';
const response = await fetch(`${API_URL}/students/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${googleToken}`
},
body: JSON.stringify({
email: email,
name: userInfo.name || email.split('@')[0]
})
});
if (!response.ok) {
throw new Error(`Server error: ${response.status} ${response.statusText}`);
}
const data = await response.json();
if (!data.success) {
throw new Error(data.message || 'Login failed');
}
const userData = {
id: userInfo.sub || Date.now(),
email: email,
name: userInfo.name || email.split('@')[0],
picture: userInfo.picture || null,
loginTime: new Date().toISOString(),
token: data.token // Store the JWT instead of Google token
};
setUser(userData);
localStorage.setItem('monaco_user', JSON.stringify(userData));
localStorage.setItem('monaco_token', userData.token);
setToken(userData.token);
return true;
}
// Fallback for demo purposes (though we're moving to Google-only)
if (email && email.includes('@')) {
const userData = {
id: Date.now(),
email: email,
name: email.split('@')[0],
loginTime: new Date().toISOString()
};
setUser(userData);
localStorage.setItem('monaco_user', JSON.stringify(userData));
localStorage.setItem('monaco_token', 'demo_token');
return true;
}
return false;
};
const logout = () => {
setUser(null);
setToken(null);
localStorage.removeItem('monaco_user');
localStorage.removeItem('monaco_token');
};
const value = {
user,
token,
login,
logout,
isAuthenticated: !!user,
isLoading
};
return (
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
);
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,51 @@
const API_URL = import.meta.env.VITE_FACULTY_API_URL || 'http://localhost:5000/api';
export const studentApi = {
async getTests() {
const response = await fetch(`${API_URL}/students/tests`, {
headers: {
'Authorization': `Bearer ${localStorage.getItem('monaco_token')}`
}
});
return await response.json();
},
async getTestQuestions(testId) {
const response = await fetch(`${API_URL}/students/tests/${testId}/questions`, {
headers: {
'Authorization': `Bearer ${localStorage.getItem('monaco_token')}`
}
});
return await response.json();
},
async verifyTestPassword(testId, password) {
const response = await fetch(`${API_URL}/students/tests/${testId}/verify-password`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${localStorage.getItem('monaco_token')}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ password })
});
return await response.json();
},
async submitAnswer(testId, questionId, code) {
const response = await fetch(`${API_URL}/students/submissions`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${localStorage.getItem('monaco_token')}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
testId,
answers: [{
questionId,
submittedAnswer: code
}]
})
});
return await response.json();
}
};

51
Frontend/start-tunnel.sh Normal file
View File

@@ -0,0 +1,51 @@
#!/bin/bash
# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color
echo -e "${GREEN}================================${NC}"
echo -e "${GREEN}Monaco Frontend Tunnel Setup${NC}"
echo -e "${GREEN}================================${NC}"
echo ""
# Check if credentials.json exists
if [ ! -f "credentials.json" ]; then
echo -e "${RED}Error: credentials.json not found!${NC}"
exit 1
fi
# Check if config.json exists
if [ ! -f "config.json" ]; then
echo -e "${RED}Error: config.json not found!${NC}"
exit 1
fi
echo -e "${YELLOW}Building Docker image...${NC}"
docker-compose -f docker-compose.tunnel.yml build
if [ $? -eq 0 ]; then
echo -e "${GREEN}Build successful!${NC}"
echo ""
echo -e "${YELLOW}Starting services...${NC}"
docker-compose -f docker-compose.tunnel.yml up -d
if [ $? -eq 0 ]; then
echo -e "${GREEN}Services started successfully!${NC}"
echo ""
echo -e "${GREEN}Frontend is now accessible at:${NC}"
echo -e " ${YELLOW}Local:${NC} http://localhost:8001"
echo -e " ${YELLOW}Tunnel:${NC} https://monaco.ishikabhoyar.tech"
echo ""
echo -e "${YELLOW}To view logs:${NC} docker-compose -f docker-compose.tunnel.yml logs -f"
echo -e "${YELLOW}To stop:${NC} docker-compose -f docker-compose.tunnel.yml down"
else
echo -e "${RED}Failed to start services!${NC}"
exit 1
fi
else
echo -e "${RED}Build failed!${NC}"
exit 1
fi

243
Readme.md
View File

@@ -1,22 +1,239 @@
# Monaco Code Execution Engine
Monaco is a secure, containerized code execution engine that allows you to run code in multiple programming languages through a simple REST API.
Monaco is a secure, containerized code execution engine that allows you to run code in multiple programming languages through a simple REST API and WebSocket connections for real-time terminal interaction. Gitea
## Features
- Multi-language support: Run code in Python, Java, C, and C++
- Secure execution: All code runs in isolated Docker containers
- Resource limits: Memory, CPU, and file descriptor limits to prevent abuse
- Concurrent processing: Efficient job queue for handling multiple requests
- Simple REST API: Easy to integrate with any frontend
- **Multi-language support**: Run code in Python, Java, C, and C++
- **Secure execution**: All code runs in isolated Docker containers
- **Resource limits**: Memory, CPU, and file descriptor limits to prevent abuse
- **Concurrent processing**: Efficient job queue for handling multiple requests
- **Simple REST API**: Easy to integrate with any frontend
- **Interactive terminal**: Real-time code execution with input/output via WebSockets
- **VS Code-like interface**: Modern editor with syntax highlighting and file management
## Architecture
Monaco consists of several components:
- HTTP Handlers (handler/handler.go): Processes API requests
- Execution Service (service/execution.go): Manages code execution in containers
- Job Queue (queue/queue.go): Handles concurrent execution of code submissions
- Submission Model (model/submission.go): Defines the data structure for code submissions
### Backend Components
- **HTTP Handlers** (`handler/handler.go`): Processes API requests and WebSocket connections
- **Execution Service** (`service/execution.go`): Manages code execution in containers
- **Job Queue** (`queue/queue.go`): Handles concurrent execution of code submissions
- **Submission Model** (`model/submission.go`): Defines the data structure for code submissions
### Frontend Components
- **Editor Area** (`EditorArea.jsx`): Main code editor with Monaco editor integration
- **Terminal Panel** (`Panel.jsx`): Interactive terminal for code execution and input
- **Sidebar** (`Sidebar.jsx`): File explorer and project structure navigation
- **Status Bar** (`StatusBar.jsx`): Information display and quick actions
### Communication Flow
1. Frontend submits code to backend via REST API
2. Backend assigns a unique ID and queues the execution
3. Frontend connects to WebSocket endpoint with the execution ID
4. Backend sends real-time execution output through WebSocket
5. Frontend can send user input back through WebSocket
6. Results are stored and retrievable via REST endpoints
## Requirements
- Go 1.22.3 or higher
- Docker
- Network connectivity for container image pulling
- **Backend**:
- Go 1.22.3 or higher
- Docker
- Network connectivity for container image pulling
- **Frontend**:
- Node.js and npm/yarn
- Modern web browser
## Installation
### Backend Setup
1. Clone the repository:
```bash
git clone https://github.com/arnab-afk/monaco.git
cd monaco/backend
2.Install Go dependencies:
```bash
go mod download
```
3.Build the application:
```bash
go build -o monaco
```
4.Run the service
```bash
./monaco
```
The backend service will start on port 8080 by default.
### Frontend Setup
1. Navigate to the Frontend directory:
```bash
cd Frontend
```
2. Install dependencies:
```bash
npm install
```
3. Set up environment variables: Create a ```.env``` or ```.env.local.``` file with:
```bash
VITE_API_URL=http://localhost:8080
```
4. Start the development server:
```bash
npm run dev
```
The frontend will be available at http://localhost:5173 by default.
### API Reference
### REST Endpoints
```POST /submit```
Submits code for execution
```json
{
"language": "python",
"code": "print('Hello, World!')",
"input": ""
}
```
Response:
```json
{
"id": "6423259c-ee14-c5aa-1c90-d5e989f92aa1"
}
```
```GET /status?id={submissionId}```
Checks the status of submission:
```json
{
"id": "6423259c-ee14-c5aa-1c90-d5e989f92aa1",
"status": "completed",
"queuedAt": "2025-03-25T14:30:00Z",
"startedAt": "2025-03-25T14:30:01Z",
"completedAt": "2025-03-25T14:30:02Z",
"executionTime": 1000
}
```
```GET /result?id={submissionId}```
Gets the execution result of a submission.
Response:
```json
{
"id": "6423259c-ee14-c5aa-1c90-d5e989f92aa1",
"status": "completed",
"language": "python",
"output": "Hello, World!",
"queuedAt": "2025-03-25T14:30:00Z",
"startedAt": "2025-03-25T14:30:01Z",
"completedAt": "2025-03-25T14:30:02Z",
"executionTime": 1000,
"executionTimeFormatted": "1.0s",
"totalTime": 2000,
"totalTimeFormatted": "2.0s"
}
```
```GET /queue-stats```
Gets the statistics about the job queue.
Response:
```json
{
"queue_stats": {
"queue_length": 5,
"max_workers": 3,
"running_jobs": 3
},
"submissions": 42
}
```
### WebSocket Endpoints
```ws://localhost:8080/ws/terminal?id={submissionId}```
Establishes a real-time connection for terminal interaction.
- The server sends execution output as plain text messages.
- The client can send input as plain text messages (with newline).
- Connection automatically closes when execution completes or fails.
### Terminal Input Handling
The system supports interactive programs requiring user input:
1. The frontend detects possible input prompts by looking for patterns
2. When detected, it focuses the terminal and allows user input
3. User input is captured in the terminal component's inputBuffer
4. When the user presses Enter, the input is:
- Sent to the backend via WebSocket.
- Displayed in the terminal.
- Buffer is cleared for next input.
5. The input is processed by the running program in real-time.
Troubleshooting tips:
- Ensure WebSocket connection is established before sending input
- Check for WebSocket errors in console
- Verify input reaches the backend by checking server logs
- Ensure newline characters are properly appended to input.
### Language Support
### Python
- **Version**: Python 3.9
- **Input Handling**: Direct stdin piping
- **Limitations**: No file I/O, no package imports outside standard library
- **Resource Limits**: 100MB memory, 10% CPU
### Java
- **Version**: Java 11 (Eclipse Temurin)
- **Class Detection**: Extracts class name from code using regex.
- **Memory Settings**: 64MB min heap, 256MB max heap
- **Resource Limits**: 400MB memory, 50% CPU
C
- **Version**: Latest GCC
- **Compilation Flags**: Default GCC settings
- **Resource Limits**: 100MB memory, 10% CPU
### C++
- **Version**: Latest G++
- **Standard**: C++17
- **Resource Limits**: 100MB memory, 10% CPU
### Security Considerations
All code execution happens within isolated Docker containers with:
- No network access (```--network=none```)
- Limited CPU and memory resources
- Limited file system access
- No persistent storage
- Execution time limits (10-15 seconds)
### Debugging
Check backend logs for execution details
Use browser developer tools to debug WebSocket connections
Terminal panel shows WebSocket connection status and errors
Check Docker logs for container-related issues.
### Contributing
Contributions are welcome! Please feel free to submit a Pull Request :).

147
UI_MODERNIZATION_SUMMARY.md Normal file
View File

@@ -0,0 +1,147 @@
# UI Modernization Summary
## Overview
Successfully modernized the entire UI to match a clean, professional exam interface design while preserving all existing functionalities.
## Key Changes
### 🎨 Code Challenge Page (Editor Interface)
#### 1. **Modern Header**
- Added left section with emoji icon (📝) and exam title
- Created sophisticated timer display with:
- Time Remaining label
- Separate blocks for Hours : Minutes : Seconds
- Color-coded with soft red background (#fee2e2)
- Labels below timer blocks
- Added user profile avatar with gradient background
- Clean white background with subtle shadow
#### 2. **Question Palette (Left Sidebar)**
- Transformed from vertical tabs to a modern grid layout
- Added "Question Palette" header
- 4-column grid of question buttons (20 questions)
- Current question highlighted in blue (#2563eb)
- Added legend at bottom:
- Current (blue dot)
- Answered (green dot)
- Not Visited (gray dot)
- Clean spacing and rounded corners
#### 3. **Problem Content Area**
- Added question header showing "Question X of Y | 10 Points"
- Modern test case cards with:
- Gray header labels (Example 1, Example 2)
- Bordered code blocks for input/output
- Clean, readable typography
- Added action buttons at bottom:
- "Clear Response" with reset icon
- "Mark for Review" with checkmark icon
- Better spacing and visual hierarchy
#### 4. **Editor Section**
- Modernized language selector dropdown
- Updated Run and Submit buttons:
- Run: Green (#10b981) with play icon
- Submit: Blue (#2563eb) with send icon
- Smooth hover effects with shadows
- Better padding and spacing
#### 5. **Terminal/Console Section**
- Added tab navigation (Console / Testcases)
- Active tab highlighted in blue
- Empty state placeholder: "Console output will appear here..."
- Modern terminal prompt with white background box
- Improved readability with better colors
#### 6. **Footer Action Bar**
- New fixed footer with:
- "Run Code" button (outline style)
- "Save & Next" button (primary blue)
- "Submit Test" button (success green)
- "All changes saved" indicator with checkmark
- Professional shadow and spacing
### 🎯 Test List Page
Already had modern styling with:
- Gradient backgrounds
- Card-based layout
- Status badges
- Smooth animations
- Clean modals
## Color Scheme
### Primary Colors
- **Blue**: #2563eb (Primary actions, active states)
- **Green**: #10b981 (Success, Run button)
- **Red**: #dc2626 (Timer, errors)
### Neutral Colors
- **Background**: #ffffff (White)
- **Secondary BG**: #f9fafb (Light gray)
- **Borders**: #e5e7eb (Light gray borders)
- **Text Primary**: #111827 (Dark gray)
- **Text Secondary**: #6b7280 (Medium gray)
- **Text Muted**: #9ca3af (Light gray)
### Accent Colors
- Timer blocks: #fee2e2 (Light red)
- User avatar: Linear gradient (#667eea to #764ba2)
- Status badges: Various semantic colors
## Typography
- **Font Family**: System fonts (-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto)
- **Code Font**: 'Consolas', 'Monaco', monospace
- **Font Sizes**:
- Headers: 18-20px
- Body: 14px
- Small text: 12-13px
- **Font Weights**: 400 (normal), 500 (medium), 600 (semi-bold), 700 (bold)
## Spacing & Layout
- Consistent padding: 12px, 16px, 24px
- Gap spacing: 6px, 8px, 12px
- Border radius: 6px, 8px
- Box shadows for depth
## Interactive Elements
- Smooth transitions (0.2s ease)
- Hover states with background changes
- Active states clearly distinguished
- Disabled states with reduced opacity
- Button hover effects with subtle shadows
## Responsive Behavior
- Flexbox layouts for adaptability
- Grid systems for question palette
- Scrollable content areas
- Fixed header and footer
## Accessibility Features
- Proper color contrast
- Clear visual feedback
- Semantic HTML structure
- Keyboard navigable elements
- Focus states preserved
## All Functionalities Preserved
✅ Timer countdown
✅ Question navigation
✅ Code execution
✅ WebSocket terminal communication
✅ Code submission
✅ Language selection
✅ Test case display
✅ User authentication flow
✅ Test list filtering
✅ Password-protected tests
✅ Auto-save submissions
## Files Modified
1. `/Frontend/src/index.css` - Complete UI styling overhaul
2. `/Frontend/src/components/CodeChallenge.jsx` - Updated JSX structure for new components
3. All existing functionality remains intact
## Result
A clean, modern, and professional examination interface that matches industry standards while maintaining all existing features and functionality.

View File

@@ -1,487 +0,0 @@
# Monaco Backend - Code Execution Service
## Table of Contents
1. Introduction
2. Architecture
3. Installation
4. API Reference
5. Code Execution
6. Job Queue System
7. Language Support
8. Security Considerations
9. Configuration
10. Testing
11. Performance Tuning
12. Troubleshooting
## Introduction
Monaco is a secure, containerized code execution backend service designed to run user-submitted code in multiple programming languages. It features a job queue system to manage execution resources, containerized execution environments for security, and a RESTful API for submission and monitoring.
**Key Features:**
- Multi-language support (Python, Java, C, C++)
- Secure containerized execution using Docker
- Resource limiting to prevent abuse
- Job queuing for managing concurrent executions
- Detailed execution statistics and monitoring
- Support for user input via stdin
- CORS support for browser-based clients
## Architecture
### Component Overview
Monaco follows a layered architecture with the following key components:
1. **HTTP Handlers** (handler package) - Processes incoming HTTP requests
2. **Execution Service** (service package) - Manages code execution in containers
3. **Job Queue** (queue package) - Controls concurrent execution
4. **Data Models** (model package) - Defines data structures
### Request Flow
1. Client submits code via `/submit` endpoint
2. Request is validated and assigned a unique ID
3. Submission is added to the job queue
4. Worker picks job from queue when available
5. Code is executed in appropriate Docker container
6. Results are stored and available via `/result` endpoint
### Dependency Diagram
```
Client Request → HTTP Handlers → Execution Service → Job Queue → Docker Containers
Data Models
```
## Installation
### Prerequisites
- Go 1.22+
- Docker Engine
- Docker images for supported languages:
- `python:3.9`
- `eclipse-temurin:11-jdk-alpine`
- `gcc:latest`
### Setup Instructions
1. Clone the repository:
```bash
git clone https://github.com/arnab-afk/monaco.git
cd monaco/backend
```
2. Install Go dependencies:
```bash
go mod download
```
3. Build the application:
```bash
go build -o monaco main.go
```
4. Run the service:
```bash
./monaco
```
The service will start on port 8080 by default.
## API Reference
### Endpoints
#### `POST /submit`
Submits code for execution.
**Request Body:**
```json
{
"language": "python", // Required: "python", "java", "c", or "cpp"
"code": "print('Hello, World!')", // Required: source code to execute
"input": "optional input string" // Optional: input to stdin
}
```
**Response:**
```json
{
"id": "6423259c-ee14-c5aa-1c90-d5e989f92aa1" // Unique ID for this submission
}
```
**Status Codes:**
- 202 Accepted - Code accepted for execution
- 400 Bad Request - Invalid request (e.g., unsupported language)
#### `GET /status?id={submissionId}`
Checks the status of a submission.
**Response:**
```json
{
"id": "6423259c-ee14-c5aa-1c90-d5e989f92aa1",
"status": "completed", // "pending", "queued", "running", "completed", "failed"
"queuedAt": "2025-03-25T14:30:00Z",
"startedAt": "2025-03-25T14:30:01Z", // Only present if status is "running", "completed", or "failed"
"completedAt": "2025-03-25T14:30:02Z", // Only present if status is "completed" or "failed"
"executionTime": 1000 // Execution time in milliseconds (only if completed)
}
```
**Status Codes:**
- 200 OK - Status retrieved successfully
- 400 Bad Request - Missing ID parameter
- 404 Not Found - Submission with given ID not found
#### `GET /result?id={submissionId}`
Gets the execution result of a submission.
**Response:**
```json
{
"id": "6423259c-ee14-c5aa-1c90-d5e989f92aa1",
"status": "completed",
"language": "python",
"output": "Hello, World!",
"queuedAt": "2025-03-25T14:30:00Z",
"startedAt": "2025-03-25T14:30:01Z",
"completedAt": "2025-03-25T14:30:02Z",
"executionTime": 1000,
"executionTimeFormatted": "1.0s",
"totalTime": 2000,
"totalTimeFormatted": "2.0s"
}
```
**Status Codes:**
- 200 OK - Result retrieved successfully
- 400 Bad Request - Missing ID parameter
- 404 Not Found - Submission with given ID not found
#### `GET /queue-stats`
Gets statistics about the job queue.
**Response:**
```json
{
"queue_stats": {
"queue_length": 5,
"max_workers": 3,
"running_jobs": 3
},
"submissions": 42
}
```
## Code Execution
### Execution Process
1. **Language Detection**: The system identifies the programming language of the submission.
2. **Environment Setup**: A temporary directory is created for compiled languages.
3. **Container Setup**: Docker containers are configured with resource limits.
4. **Compilation**: For compiled languages (Java, C, C++), code is compiled first.
5. **Execution**: The program is executed with the provided input.
6. **Resource Monitoring**: Memory and CPU usage are limited during execution.
7. **Result Collection**: Output and errors are captured and stored.
### Language-Specific Processing
#### Python
- Directly executes Python code using the `-c` flag
- Uses `python:3.9` Docker image
- Resource limits: 100MB memory, 10% CPU
#### Java
- Detects class name using regex pattern matching
- Compiles with `javac` and runs with optimized JVM settings
- Uses `eclipse-temurin:11-jdk-alpine` Docker image
- Resource limits: 400MB memory, 50% CPU
- JVM flags: `-XX:+TieredCompilation`, `-XX:TieredStopAtLevel=1`, `-Xverify:none`
#### C/C++
- Saves code to a file in a temporary directory
- Compiles with `gcc`/`g++` and runs the executable
- Uses `gcc:latest` Docker image
- Resource limits: 100MB memory, 10% CPU
### Timeout Handling
All executions have a timeout limit:
- Python: 10 seconds
- Java: 15 seconds
- C/C++: 10 seconds
If execution exceeds this limit, the process is killed and an error is returned.
## Job Queue System
### Worker Pool
Monaco uses a worker pool to manage concurrent code executions:
- Default pool size: 20 workers (configurable)
- Maximum queue capacity: 100 jobs
- FIFO (First-In-First-Out) processing order
### Job Lifecycle
1. **Creation**: Job created when code is submitted
2. **Queuing**: Job added to queue with `queued` status
3. **Execution**: Worker picks job from queue and changes status to `running`
4. **Completion**: Job finishes with either `completed` or `failed` status
### Performance Metrics
The queue tracks and reports:
- Current queue length
- Number of running jobs
- Maximum worker count
- Total number of submissions
## Language Support
### Python
- **Version**: Python 3.9
- **Input Handling**: Direct stdin piping
- **Limitations**: No file I/O, no package imports outside standard library
### Java
- **Version**: Java 11 (Eclipse Temurin)
- **Class Detection**: Extracts class name from code using regex
- **Memory Settings**: 64MB min heap, 256MB max heap
- **Best Practices**: Use `public class` with the main method
### C
- **Version**: Latest GCC
- **Compilation Flags**: Default GCC settings
- **Execution**: Compiled binary
### C++
- **Version**: Latest G++
- **Standard**: C++17
- **Execution**: Compiled binary
## Security Considerations
### Containerization
All code execution happens within isolated Docker containers with:
- No network access (`--network=none`)
- Limited CPU and memory resources
- Limited file system access
- No persistent storage
### Resource Limiting
- **Memory Limits**: 100-400MB depending on language
- **CPU Limits**: 10-50% of CPU depending on language
- **File Descriptors**: Limited to 64 for Python
- **Execution Time**: Enforced timeouts (10-15 seconds)
### Known Limitations
- Container escape vulnerabilities
- Docker daemon security depends on host configuration
- Resource limits can be circumvented with certain techniques
## Configuration
The service can be configured through environment variables:
- `PORT`: HTTP port (default: 8080)
- `MAX_WORKERS`: Maximum concurrent executions (default: 3)
- `QUEUE_SIZE`: Maximum queue size (default: 100)
- `DEFAULT_LANGUAGE`: Default language if none specified (default: "python")
## Testing
### Unit Tests
Run unit tests with:
```bash
go test ./...
```
# Monaco Backend Test Plan
## Overview
This test plan outlines the testing approach for the Monaco code execution backend service.
## Test Environment
- Development: Local workstations with Docker and Go
- Testing: Dedicated test server with Docker
- Production-like: Staging environment with similar resources to production
## Test Types
### Unit Tests
- **Purpose**: Verify individual components work as expected
- **Components to Test**:
- Handler package
- Queue package
- Execution service
- Models
- **Tools**: Go testing framework
### Integration Tests
- **Purpose**: Verify components work together correctly
- **Focus Areas**:
- API endpoints
- End-to-end code execution flow
- Error handling
- **Tools**: Go testing framework, HTTP test utilities
### Load Tests
- **Purpose**: Verify system performance under load
- **Scenarios**:
- Concurrent submissions
- Mixed language workloads
- Queue saturation
- **Metrics**:
- Request throughput
- Response times
- Success rates
- Resource utilization
- **Tools**: Custom Python test scripts
## Test Data
- Simple programs in each language
- Programs with input requirements
- Programs with compile errors
- Programs with runtime errors
- Programs with timeouts
## Test Execution
1. Run unit tests on every code change
2. Run integration tests before merging to main branch
3. Run load tests weekly and before major releases
## Success Criteria
- All unit tests pass
- Integration tests complete successfully
- Load tests show acceptable performance metrics:
- 95% of requests complete successfully
- 95th percentile response time < 5 seconds
- System can handle 20 concurrent users
## Reporting
- Test results stored in CI/CD pipeline
- Performance metrics graphed over time
- Issues logged in GitHub issues
### Load Testing
A Python script (`test.py`) is included for load testing:
```bash
python test.py
```
This script sends 500 requests concurrently and reports performance metrics.
### Manual Testing with Curl
#### Python Example
```bash
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{
"language": "python",
"code": "print(\"Hello, World!\")\nfor i in range(5):\n print(f\"Number: {i}\")",
"input": ""
}'
```
#### Java Example
```bash
curl -X POST http://localhost:8080/submit \
-H "Content-Type: application/json" \
-d '{
"language": "java",
"code": "public class Solution {\n public static void main(String[] args) {\n System.out.println(\"Hello, World!\");\n for (int i = 0; i < 5; i++) {\n System.out.println(\"Number: \" + i);\n }\n }\n}",
"input": ""
}'
```
## Performance Tuning
### Optimizing Worker Count
The optimal worker count depends on:
- CPU cores available
- Memory available
- Docker container startup time
For most single-server deployments, 3-5 workers is optimal.
### Memory Considerations
Each language has different memory requirements:
- Python: ~50-100MB per instance
- Java: ~200-400MB per instance
- C/C++: ~50-100MB per instance
Calculate total memory needs as: `(Python instances × 100MB) + (Java instances × 400MB) + (C/C++ instances × 100MB)`
### Disk Space Management
Temporary files are cleaned up after execution, but with high request volumes, ensure adequate disk space for concurrent operations (approximately 1-5MB per request for compiled languages).
## Troubleshooting
### Common Issues
#### Docker Connection Errors
```
Error: Cannot connect to the Docker daemon
```
**Solution**: Ensure Docker daemon is running with `systemctl start docker` or `docker --version`
#### Permissions Issues
```
Error: Permission denied while trying to connect to the Docker daemon socket
```
**Solution**: Add user to docker group: `sudo usermod -aG docker $USER`
#### Container Resource Limits
```
Error: Container killed due to memory limit
```
**Solution**: Increase memory limits in execution service or optimize submitted code
#### File Not Found Errors
```
Error: Failed to write Java file
```
**Solution**: Check temporary directory permissions and disk space
### Logs
The service provides structured logs with prefixes for easier filtering:
- `[HTTP]` - API requests
- `[QUEUE]` - Queue operations
- `[WORKER-n]` - Worker activities
- `[EXEC-id]` - Execution details
- `[PYTHON/JAVA/C/CPP-id]` - Language-specific logs
- `[TIMEOUT-id]` - Timeout events
- `[RESULT-id]` - Execution results
---
## License
This project is licensed under the MIT License - see the LICENSE file for details.
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.

View File

@@ -1,56 +0,0 @@
import os
import aiohttp
import asyncio
from datetime import datetime, timedelta
# Base URL template
BASE_URL = "https://bhuvan-app3.nrsc.gov.in/isroeodatadownloadutility/tiledownloadnew_cfr_new.php?f=nices_ssm2_{}_{}.zip&se=NICES&u=arnabafk"
# Directory to save files
SAVE_DIR = "data"
os.makedirs(SAVE_DIR, exist_ok=True)
async def download_file(session, file_url, file_path):
"""Download a file asynchronously."""
print(f"Downloading {file_url}...")
try:
async with session.get(file_url) as response:
if response.status == 200:
with open(file_path, 'wb') as file:
while chunk := await response.content.read(1024):
file.write(chunk)
print(f"Downloaded: {file_path}")
else:
print(f"Failed to download: {file_path}, Status Code: {response.status}")
except Exception as e:
print(f"Error downloading {file_url}: {e}")
async def fetch_data_for_year(session, year):
"""Fetch and download data for a given year."""
year_dir = os.path.join(SAVE_DIR, str(year))
os.makedirs(year_dir, exist_ok=True)
start_date = datetime(year, 1, 1)
end_date = datetime(year, 12, 31)
delta = timedelta(days=2)
tasks = []
date = start_date
while date <= end_date:
date_str = date.strftime("%Y%m%d")
file_url = BASE_URL.format(date_str, "NICES")
file_name = f"nices_ssm2_{date_str}.zip"
file_path = os.path.join(year_dir, file_name)
tasks.append(download_file(session, file_url, file_path))
date += delta
await asyncio.gather(*tasks)
async def main():
"""Main function to download data for multiple years."""
async with aiohttp.ClientSession() as session:
await asyncio.gather(*(fetch_data_for_year(session, year) for year in range(2002, 2025)))
if __name__ == "__main__":
asyncio.run(main())

File diff suppressed because one or more lines are too long

View File

@@ -1,131 +0,0 @@
project_name: monaco
release:
github:
owner: Arnab-Afk
name: monaco
name_template: '{{.Tag}}'
builds:
- id: monaco
goos:
- linux
- darwin
- windows
goarch:
- amd64
- arm64
- "386"
goamd64:
- v1
go386:
- sse2
goarm:
- "6"
goarm64:
- v8.0
gomips:
- hardfloat
goppc64:
- power8
goriscv64:
- rva20u64
targets:
- linux_amd64_v1
- linux_arm64_v8.0
- linux_386_sse2
- darwin_amd64_v1
- darwin_arm64_v8.0
- windows_amd64_v1
- windows_arm64_v8.0
- windows_386_sse2
dir: .
main: .
binary: monaco
builder: go
tool: go
command: build
ldflags:
- -s -w -X main.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{.Date}} -X main.builtBy=goreleaser
archives:
- id: default
builds_info:
mode: 493
name_template: '{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ with .Arm }}v{{ . }}{{ end }}{{ with .Mips }}_{{ . }}{{ end }}{{ if not (eq .Amd64 "v1") }}{{ .Amd64 }}{{ end }}'
formats:
- tar.gz
files:
- src: license*
- src: LICENSE*
- src: readme*
- src: README*
- src: changelog*
- src: CHANGELOG*
snapshot:
version_template: '{{ .Version }}-SNAPSHOT-{{ .ShortCommit }}'
checksum:
name_template: '{{ .ProjectName }}_{{ .Version }}_checksums.txt'
algorithm: sha256
changelog:
format: '{{ .SHA }} {{ .Message }}'
dist: dist
env_files:
github_token: ~/.config/goreleaser/github_token
gitlab_token: ~/.config/goreleaser/gitlab_token
gitea_token: ~/.config/goreleaser/gitea_token
source:
name_template: '{{ .ProjectName }}-{{ .Version }}'
format: tar.gz
gomod:
gobinary: go
announce:
twitter:
message_template: '{{ .ProjectName }} {{ .Tag }} is out! Check it out at {{ .ReleaseURL }}'
mastodon:
message_template: '{{ .ProjectName }} {{ .Tag }} is out! Check it out at {{ .ReleaseURL }}'
server: ""
reddit:
title_template: '{{ .ProjectName }} {{ .Tag }} is out!'
url_template: '{{ .ReleaseURL }}'
slack:
message_template: '{{ .ProjectName }} {{ .Tag }} is out! Check it out at {{ .ReleaseURL }}'
username: GoReleaser
discord:
message_template: '{{ .ProjectName }} {{ .Tag }} is out! Check it out at {{ .ReleaseURL }}'
author: GoReleaser
color: "3888754"
icon_url: https://goreleaser.com/static/avatar.png
teams:
title_template: '{{ .ProjectName }} {{ .Tag }} is out!'
message_template: '{{ .ProjectName }} {{ .Tag }} is out! Check it out at {{ .ReleaseURL }}'
color: '#2D313E'
icon_url: https://goreleaser.com/static/avatar.png
smtp:
subject_template: '{{ .ProjectName }} {{ .Tag }} is out!'
body_template: 'You can view details from: {{ .ReleaseURL }}'
mattermost:
message_template: '{{ .ProjectName }} {{ .Tag }} is out! Check it out at {{ .ReleaseURL }}'
title_template: '{{ .ProjectName }} {{ .Tag }} is out!'
username: GoReleaser
linkedin:
message_template: '{{ .ProjectName }} {{ .Tag }} is out! Check it out at {{ .ReleaseURL }}'
telegram:
message_template: '{{ mdv2escape .ProjectName }} {{ mdv2escape .Tag }} is out{{ mdv2escape "!" }} Check it out at {{ mdv2escape .ReleaseURL }}'
parse_mode: MarkdownV2
webhook:
message_template: '{ "message": "{{ .ProjectName }} {{ .Tag }} is out! Check it out at {{ .ReleaseURL }}"}'
content_type: application/json; charset=utf-8
expected_status_codes:
- 200
- 201
- 202
- 204
opencollective:
title_template: '{{ .Tag }}'
message_template: '{{ .ProjectName }} {{ .Tag }} is out!<br/>Check it out at <a href="{{ .ReleaseURL }}">{{ .ReleaseURL }}</a>'
bluesky:
message_template: '{{ .ProjectName }} {{ .Tag }} is out! Check it out at {{ .ReleaseURL }}'
git:
tag_sort: -version:refname
github_urls:
download: https://github.com
gitlab_urls:
download: https://gitlab.com

View File

@@ -1 +0,0 @@
{"project_name":"monaco","tag":"v0.0.0","previous_tag":"","version":"0.0.0-SNAPSHOT-574f754","commit":"574f7549406a4faa0d84d53eb201ae7ebd1edc1a","date":"2025-03-26T20:50:22.2203996+05:30","runtime":{"goos":"windows","goarch":"amd64"}}

View File

@@ -1,8 +0,0 @@
41202196ac39bef7e0fdb394f838967c82dd4429245c5e4c720d849bc8b73c2d monaco_0.0.0-SNAPSHOT-574f754_darwin_amd64.tar.gz
c69d1632f0c2bb6df9fa5bf33ac892596bf69cd994ee022dfc4659a2c8df4000 monaco_0.0.0-SNAPSHOT-574f754_darwin_arm64.tar.gz
b1b7bd54911686aa5c8539e9fbb4b5c4ac7ba5609eb9df32976edf14821acd59 monaco_0.0.0-SNAPSHOT-574f754_linux_386.tar.gz
b078183b95e9088a3cd9814113a98197a44cf93bb14e27a148f2ccc5d5a2db27 monaco_0.0.0-SNAPSHOT-574f754_linux_amd64.tar.gz
9fed0feae759d5731b4ea347d239cc559008bde1ff3c4afdcc27a89260696c92 monaco_0.0.0-SNAPSHOT-574f754_linux_arm64.tar.gz
dc8e6b76317db38904f1899d8895ed4a361cca931224b48875ed1cef2604ce59 monaco_0.0.0-SNAPSHOT-574f754_windows_386.tar.gz
86b9667a338fa80bb6a175fbb881f7eb02f2a31378c1a76f3b92671f2c24f845 monaco_0.0.0-SNAPSHOT-574f754_windows_amd64.tar.gz
642cf9946261558515db88540cf7ecb92859c73afd1600c0441605dd68518757 monaco_0.0.0-SNAPSHOT-574f754_windows_arm64.tar.gz

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -1,14 +0,0 @@
module github.com/arnab-afk/monaco
go 1.22.3
require github.com/stretchr/testify v1.9.0
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/kr/pretty v0.3.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rogpeppe/go-internal v1.12.0 // indirect
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

View File

@@ -1,23 +0,0 @@
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -1,185 +0,0 @@
package handler
import (
"encoding/json"
"net/http"
"sync"
"time"
"github.com/arnab-afk/monaco/model"
"github.com/arnab-afk/monaco/service"
)
// Handler manages HTTP requests for code submissions
type Handler struct {
executionService *service.ExecutionService
mu sync.Mutex
submissions map[string]*model.CodeSubmission
}
// NewHandler creates a new handler instance
func NewHandler() *Handler {
return &Handler{
executionService: service.NewExecutionService(),
submissions: make(map[string]*model.CodeSubmission),
}
}
// SubmitHandler handles code submission requests
func (h *Handler) SubmitHandler(w http.ResponseWriter, r *http.Request) {
var submission model.CodeSubmission
if err := json.NewDecoder(r.Body).Decode(&submission); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Set default language if not provided
if submission.Language == "" {
submission.Language = "python" // Default to Python
}
// Validate language
supportedLanguages := map[string]bool{
"python": true,
"java": true,
"c": true,
"cpp": true,
}
if !supportedLanguages[submission.Language] {
http.Error(w, "Unsupported language: "+submission.Language, http.StatusBadRequest)
return
}
h.mu.Lock()
submission.ID = h.generateID()
submission.Status = "pending"
h.submissions[submission.ID] = &submission
h.mu.Unlock()
go h.executionService.ExecuteCode(&submission)
w.WriteHeader(http.StatusAccepted)
json.NewEncoder(w).Encode(map[string]string{"id": submission.ID})
}
// StatusHandler handles status check requests
func (h *Handler) StatusHandler(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
if id == "" {
http.Error(w, "ID is required", http.StatusBadRequest)
return
}
h.mu.Lock()
submission, exists := h.submissions[id]
h.mu.Unlock()
if !exists {
http.Error(w, "Submission not found", http.StatusNotFound)
return
}
// Return status with time information
response := map[string]interface{}{
"id": submission.ID,
"status": submission.Status,
}
// Add time information based on status
if !submission.QueuedAt.IsZero() {
response["queuedAt"] = submission.QueuedAt.Format(time.RFC3339)
}
if submission.Status == "running" && !submission.StartedAt.IsZero() {
response["startedAt"] = submission.StartedAt.Format(time.RFC3339)
response["runningFor"] = time.Since(submission.StartedAt).String()
}
if submission.Status == "completed" || submission.Status == "failed" {
if !submission.CompletedAt.IsZero() && !submission.StartedAt.IsZero() {
response["executionTime"] = submission.CompletedAt.Sub(submission.StartedAt).Milliseconds()
response["completedAt"] = submission.CompletedAt.Format(time.RFC3339)
}
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, "Failed to serialize response: "+err.Error(), http.StatusInternalServerError)
return
}
}
// ResultHandler handles result requests
func (h *Handler) ResultHandler(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
if id == "" {
http.Error(w, "ID is required", http.StatusBadRequest)
return
}
h.mu.Lock()
submission, exists := h.submissions[id]
h.mu.Unlock()
if !exists {
http.Error(w, "Submission not found", http.StatusNotFound)
return
}
// Prepare response with safe time handling
response := map[string]interface{}{
"id": submission.ID,
"status": submission.Status,
"output": submission.Output,
"language": submission.Language,
}
// Only include time fields if they're set
if !submission.QueuedAt.IsZero() {
response["queuedAt"] = submission.QueuedAt.Format(time.RFC3339)
}
if !submission.StartedAt.IsZero() {
response["startedAt"] = submission.StartedAt.Format(time.RFC3339)
}
if !submission.CompletedAt.IsZero() {
response["completedAt"] = submission.CompletedAt.Format(time.RFC3339)
// Calculate times only if we have valid timestamps
if !submission.StartedAt.IsZero() {
executionTime := submission.CompletedAt.Sub(submission.StartedAt)
response["executionTime"] = executionTime.Milliseconds() // Use milliseconds for frontend
response["executionTimeFormatted"] = executionTime.String()
}
if !submission.QueuedAt.IsZero() {
totalTime := submission.CompletedAt.Sub(submission.QueuedAt)
response["totalTime"] = totalTime.Milliseconds() // Use milliseconds for frontend
response["totalTimeFormatted"] = totalTime.String()
}
}
// Return full submission details
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, "Failed to serialize response: "+err.Error(), http.StatusInternalServerError)
return
}
}
// QueueStatsHandler provides information about the job queue
func (h *Handler) QueueStatsHandler(w http.ResponseWriter, r *http.Request) {
stats := h.executionService.GetQueueStats()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"queue_stats": stats,
"submissions": len(h.submissions),
})
}
// generateID creates a unique ID for submissions
func (h *Handler) generateID() string {
return service.GenerateUUID()
}

View File

@@ -1,154 +0,0 @@
package handler
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/arnab-afk/monaco/model"
"github.com/stretchr/testify/assert"
)
func TestSubmitHandler(t *testing.T) {
h := NewHandler()
// Test valid Python submission
body := map[string]string{
"language": "python",
"code": "print('Hello, World!')",
}
bodyBytes, _ := json.Marshal(body)
req := httptest.NewRequest("POST", "/submit", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
h.SubmitHandler(w, req)
assert.Equal(t, http.StatusAccepted, w.Code)
var response map[string]string
err := json.Unmarshal(w.Body.Bytes(), &response)
assert.NoError(t, err)
assert.NotEmpty(t, response["id"])
// Test invalid language
body["language"] = "invalid"
bodyBytes, _ = json.Marshal(body)
req = httptest.NewRequest("POST", "/submit", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
w = httptest.NewRecorder()
h.SubmitHandler(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
assert.Contains(t, w.Body.String(), "Unsupported language")
}
func TestStatusHandler(t *testing.T) {
h := NewHandler()
// Create a test submission
submission := &model.CodeSubmission{
ID: "test-id",
Language: "python",
Code: "print('Hello')",
Status: "completed",
QueuedAt: time.Now().Add(-2 * time.Second),
StartedAt: time.Now().Add(-1 * time.Second),
CompletedAt: time.Now(),
Output: "Hello",
}
h.submissions["test-id"] = submission
// Test valid status request
req := httptest.NewRequest("GET", "/status?id=test-id", nil)
w := httptest.NewRecorder()
h.StatusHandler(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var response map[string]interface{}
err := json.Unmarshal(w.Body.Bytes(), &response)
assert.NoError(t, err)
assert.Equal(t, "test-id", response["id"])
assert.Equal(t, "completed", response["status"])
// Test missing ID
req = httptest.NewRequest("GET", "/status", nil)
w = httptest.NewRecorder()
h.StatusHandler(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
assert.Contains(t, w.Body.String(), "ID is required")
// Test non-existent ID
req = httptest.NewRequest("GET", "/status?id=nonexistent", nil)
w = httptest.NewRecorder()
h.StatusHandler(w, req)
assert.Equal(t, http.StatusNotFound, w.Code)
assert.Contains(t, w.Body.String(), "Submission not found")
}
func TestResultHandler(t *testing.T) {
h := NewHandler()
// Create a test submission
submission := &model.CodeSubmission{
ID: "test-id",
Language: "python",
Code: "print('Hello')",
Status: "completed",
QueuedAt: time.Now().Add(-2 * time.Second),
StartedAt: time.Now().Add(-1 * time.Second),
CompletedAt: time.Now(),
Output: "Hello",
}
h.submissions["test-id"] = submission
// Test valid result request
req := httptest.NewRequest("GET", "/result?id=test-id", nil)
w := httptest.NewRecorder()
h.ResultHandler(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var response map[string]interface{}
err := json.Unmarshal(w.Body.Bytes(), &response)
assert.NoError(t, err)
assert.Equal(t, "test-id", response["id"])
assert.Equal(t, "completed", response["status"])
assert.Equal(t, "Hello", response["output"])
}
func TestQueueStatsHandler(t *testing.T) {
h := NewHandler()
// Add some test submissions
h.submissions["test-id1"] = &model.CodeSubmission{ID: "test-id1"}
h.submissions["test-id2"] = &model.CodeSubmission{ID: "test-id2"}
req := httptest.NewRequest("GET", "/queue-stats", nil)
w := httptest.NewRecorder()
h.QueueStatsHandler(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var response map[string]interface{}
err := json.Unmarshal(w.Body.Bytes(), &response)
assert.NoError(t, err)
stats, ok := response["queue_stats"].(map[string]interface{})
assert.True(t, ok)
assert.Contains(t, stats, "queue_length")
assert.Contains(t, stats, "max_workers")
assert.Contains(t, stats, "running_jobs")
assert.Equal(t, float64(2), response["submissions"])
}

View File

@@ -1,58 +0,0 @@
package main
import (
"log"
"net/http"
"os"
"time"
"github.com/arnab-afk/monaco/handler"
)
func main() {
// Configure logging with timestamps and file locations
log.SetFlags(log.LstdFlags | log.Lshortfile)
log.SetOutput(os.Stdout)
log.Println("Starting Monaco code execution backend...")
h := handler.NewHandler()
// Create a middleware for request logging
loggingMiddleware := func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
log.Printf("[HTTP] %s %s %s", r.Method, r.URL.Path, r.RemoteAddr)
next(w, r)
log.Printf("[HTTP] %s %s completed in %v", r.Method, r.URL.Path, time.Since(startTime))
}
}
// Create a middleware for CORS - allow all origins
corsMiddleware := func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Set CORS headers to allow any origin
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
w.Header().Set("Access-Control-Max-Age", "3600")
// Handle preflight OPTIONS requests
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
next(w, r)
}
}
// Register handlers with logging and CORS middleware
http.HandleFunc("/submit", corsMiddleware(loggingMiddleware(h.SubmitHandler)))
http.HandleFunc("/status", corsMiddleware(loggingMiddleware(h.StatusHandler)))
http.HandleFunc("/result", corsMiddleware(loggingMiddleware(h.ResultHandler)))
http.HandleFunc("/queue-stats", corsMiddleware(loggingMiddleware(h.QueueStatsHandler)))
port := ":8080"
log.Printf("Server started at %s", port)
log.Fatal(http.ListenAndServe(port, nil))
}

View File

@@ -1,16 +0,0 @@
package model
import "time"
// CodeSubmission represents a code submission for execution
type CodeSubmission struct {
ID string `json:"id"`
Code string `json:"code"`
Language string `json:"language"`
Input string `json:"input"` // Added input field for stdin
Status string `json:"status"` // "queued", "running", "completed", "failed"
QueuedAt time.Time `json:"queuedAt"`
StartedAt time.Time `json:"startedAt,omitempty"`
CompletedAt time.Time `json:"completedAt,omitempty"`
Output string `json:"output"`
}

View File

@@ -1,71 +0,0 @@
package model
import (
"encoding/json"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestCodeSubmissionSerialization(t *testing.T) {
// Create a submission
now := time.Now()
submission := CodeSubmission{
ID: "test-id",
Code: "print('Hello, World!')",
Language: "python",
Input: "test input",
Status: "completed",
QueuedAt: now.Add(-2 * time.Second),
StartedAt: now.Add(-1 * time.Second),
CompletedAt: now,
Output: "Hello, World!",
}
// Serialize to JSON
jsonBytes, err := json.Marshal(submission)
assert.NoError(t, err)
assert.NotNil(t, jsonBytes)
// Deserialize back
var decoded CodeSubmission
err = json.Unmarshal(jsonBytes, &decoded)
assert.NoError(t, err)
// Verify fields match
assert.Equal(t, submission.ID, decoded.ID)
assert.Equal(t, submission.Code, decoded.Code)
assert.Equal(t, submission.Language, decoded.Language)
assert.Equal(t, submission.Input, decoded.Input)
assert.Equal(t, submission.Status, decoded.Status)
assert.Equal(t, submission.Output, decoded.Output)
// Time fields need special handling due to JSON serialization
assert.Equal(t, submission.QueuedAt.Format(time.RFC3339), decoded.QueuedAt.Format(time.RFC3339))
assert.Equal(t, submission.StartedAt.Format(time.RFC3339), decoded.StartedAt.Format(time.RFC3339))
assert.Equal(t, submission.CompletedAt.Format(time.RFC3339), decoded.CompletedAt.Format(time.RFC3339))
}
func TestCodeSubmissionDefaults(t *testing.T) {
// Test that zero time values work correctly
submission := CodeSubmission{
ID: "test-id",
Code: "print('Hello')",
Language: "python",
Status: "pending",
}
assert.True(t, submission.QueuedAt.IsZero())
assert.True(t, submission.StartedAt.IsZero())
assert.True(t, submission.CompletedAt.IsZero())
// Test JSON marshaling with zero time values
jsonBytes, err := json.Marshal(submission)
assert.NoError(t, err)
// The zero time values should still be included in the JSON
jsonStr := string(jsonBytes)
assert.Contains(t, jsonStr, `"id":"test-id"`)
assert.Contains(t, jsonStr, `"status":"pending"`)
}

View File

@@ -1,96 +0,0 @@
package queue
import (
"log"
"sync"
"time"
)
// Job represents a task that can be executed
type Job interface {
Execute()
}
// JobQueue manages the execution of jobs with limited concurrency
type JobQueue struct {
jobs chan Job
maxWorkers int
wg sync.WaitGroup
running int
mu sync.Mutex
}
// NewJobQueue creates a new job queue with specified max concurrent workers
func NewJobQueue(maxWorkers int) *JobQueue {
log.Printf("[QUEUE] Initializing job queue with %d workers and buffer size 100", maxWorkers)
jq := &JobQueue{
jobs: make(chan Job, 100), // Buffer size of 100 jobs
maxWorkers: maxWorkers,
}
jq.start()
return jq
}
// start initializes the worker pool
func (jq *JobQueue) start() {
// Start the workers
for i := 0; i < jq.maxWorkers; i++ {
workerId := i + 1
log.Printf("[WORKER-%d] Starting worker", workerId)
jq.wg.Add(1)
go func(id int) {
defer jq.wg.Done()
for job := range jq.jobs {
jq.mu.Lock()
jq.running++
queueLen := len(jq.jobs)
jq.mu.Unlock()
log.Printf("[WORKER-%d] Processing job (running: %d, queued: %d)",
id, jq.running, queueLen)
startTime := time.Now()
job.Execute()
elapsed := time.Since(startTime)
jq.mu.Lock()
jq.running--
jq.mu.Unlock()
log.Printf("[WORKER-%d] Completed job in %v (running: %d, queued: %d)",
id, elapsed, jq.running, len(jq.jobs))
}
log.Printf("[WORKER-%d] Worker shutting down", id)
}(workerId)
}
}
// Enqueue adds a job to the queue
func (jq *JobQueue) Enqueue(job Job) {
jq.mu.Lock()
queueLen := len(jq.jobs)
jq.mu.Unlock()
log.Printf("[QUEUE] Job enqueued (queue length: %d, running: %d)", queueLen, jq.running)
jq.jobs <- job
}
// Stop gracefully shuts down the job queue
func (jq *JobQueue) Stop() {
log.Println("[QUEUE] Stopping job queue, waiting for running jobs to complete")
close(jq.jobs)
jq.wg.Wait()
log.Println("[QUEUE] Job queue shutdown complete")
}
// QueueStats returns statistics about the queue
func (jq *JobQueue) QueueStats() map[string]int {
jq.mu.Lock()
defer jq.mu.Unlock()
return map[string]int{
"queue_length": len(jq.jobs),
"max_workers": jq.maxWorkers,
"running_jobs": jq.running,
}
}

View File

@@ -1,112 +0,0 @@
package queue
import (
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
// Mock job for testing
type MockJob struct {
executed bool
executeTime time.Duration
mu sync.Mutex
}
func (j *MockJob) Execute() {
j.mu.Lock()
defer j.mu.Unlock()
time.Sleep(j.executeTime)
j.executed = true
}
func (j *MockJob) IsExecuted() bool {
j.mu.Lock()
defer j.mu.Unlock()
return j.executed
}
func TestJobQueueCreation(t *testing.T) {
// Test with different numbers of workers
jq := NewJobQueue(5)
assert.NotNil(t, jq)
assert.Equal(t, 5, jq.maxWorkers)
stats := jq.QueueStats()
assert.Equal(t, 0, stats["queue_length"])
assert.Equal(t, 5, stats["max_workers"])
assert.Equal(t, 0, stats["running_jobs"])
}
func TestJobExecution(t *testing.T) {
jq := NewJobQueue(2)
// Create test jobs
job1 := &MockJob{executeTime: 10 * time.Millisecond}
job2 := &MockJob{executeTime: 10 * time.Millisecond}
// Enqueue jobs
jq.Enqueue(job1)
jq.Enqueue(job2)
// Wait for execution
time.Sleep(50 * time.Millisecond)
// Verify both jobs executed
assert.True(t, job1.IsExecuted())
assert.True(t, job2.IsExecuted())
}
func TestConcurrentJobsExecution(t *testing.T) {
// Test that only maxWorkers jobs run concurrently
jq := NewJobQueue(2)
var mu sync.Mutex
runningCount := 0
maxObservedRunning := 0
wg := sync.WaitGroup{}
// Create long running jobs to test concurrency
for i := 0; i < 5; i++ {
wg.Add(1)
job := &MockJob{
executeTime: 100 * time.Millisecond,
}
// Wrap the job to monitor concurrency
wrappedJob := JobFunc(func() {
mu.Lock()
runningCount++
if runningCount > maxObservedRunning {
maxObservedRunning = runningCount
}
mu.Unlock()
job.Execute()
mu.Lock()
runningCount--
mu.Unlock()
wg.Done()
})
jq.Enqueue(wrappedJob)
}
wg.Wait()
jq.Stop()
// Verify max concurrent jobs is respected
assert.LessOrEqual(t, maxObservedRunning, 2)
}
// Define JobFunc type for easier job creation in tests
type JobFunc func()
func (f JobFunc) Execute() {
f()
}

View File

@@ -1,485 +0,0 @@
package service
import (
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"github.com/arnab-afk/monaco/model"
"github.com/arnab-afk/monaco/queue"
)
// ExecutionService handles code execution for multiple languages
type ExecutionService struct {
mu sync.Mutex
queue *queue.JobQueue
}
// NewExecutionService creates a new execution service
func NewExecutionService() *ExecutionService {
log.Println("Initializing execution service with 3 concurrent workers")
return &ExecutionService{
queue: queue.NewJobQueue(35), // 3 concurrent executions max
}
}
// CodeExecutionJob represents a job to execute code
type CodeExecutionJob struct {
service *ExecutionService
submission *model.CodeSubmission
}
// NewCodeExecutionJob creates a new code execution job
func NewCodeExecutionJob(service *ExecutionService, submission *model.CodeSubmission) *CodeExecutionJob {
return &CodeExecutionJob{
service: service,
submission: submission,
}
}
// Execute runs the code execution job
func (j *CodeExecutionJob) Execute() {
submission := j.submission
submission.Status = "running"
submission.StartedAt = time.Now()
log.Printf("[JOB-%s] Starting execution for language: %s",
submission.ID, submission.Language)
j.service.executeLanguageSpecific(submission)
}
// ExecuteCode adds the submission to the execution queue
func (s *ExecutionService) ExecuteCode(submission *model.CodeSubmission) {
submission.Status = "queued"
submission.QueuedAt = time.Now()
log.Printf("[SUBMISSION-%s] Code submission queued for language: %s (Queue length: %d)",
submission.ID, submission.Language, s.queue.QueueStats()["queue_length"])
// Log if input is provided
if len(submission.Input) > 0 {
inputLen := len(submission.Input)
previewLen := 30
if inputLen > previewLen {
log.Printf("[INPUT-%s] Input provided (%d bytes): %s...",
submission.ID, inputLen, submission.Input[:previewLen])
} else {
log.Printf("[INPUT-%s] Input provided (%d bytes): %s",
submission.ID, inputLen, submission.Input)
}
}
job := NewCodeExecutionJob(s, submission)
s.queue.Enqueue(job)
}
// executeLanguageSpecific runs code in the appropriate language container
func (s *ExecutionService) executeLanguageSpecific(submission *model.CodeSubmission) {
log.Printf("[EXEC-%s] Selecting execution environment for language: %s",
submission.ID, submission.Language)
switch submission.Language {
case "python":
log.Printf("[EXEC-%s] Executing Python code", submission.ID)
s.executePython(submission)
case "java":
log.Printf("[EXEC-%s] Executing Java code", submission.ID)
s.executeJava(submission)
case "c":
log.Printf("[EXEC-%s] Executing C code", submission.ID)
s.executeC(submission)
case "cpp":
log.Printf("[EXEC-%s] Executing C++ code", submission.ID)
s.executeCpp(submission)
default:
log.Printf("[EXEC-%s] ERROR: Unsupported language: %s", submission.ID, submission.Language)
submission.Status = "failed"
submission.Output = "Unsupported language: " + submission.Language
}
}
// executeWithInput runs a command with a timeout and provides input
func (s *ExecutionService) executeWithInput(cmd *exec.Cmd, input string, timeout time.Duration, submissionID string) ([]byte, error) {
log.Printf("[TIMEOUT-%s] Setting execution timeout: %v", submissionID, timeout)
// Set up input pipe if input is provided
if input != "" {
stdin, err := cmd.StdinPipe()
if err != nil {
log.Printf("[ERROR-%s] Failed to create stdin pipe: %v", submissionID, err)
return nil, err
}
// Write input in a goroutine to avoid blocking
go func() {
defer stdin.Close()
io.WriteString(stdin, input)
}()
log.Printf("[INPUT-%s] Providing input to process", submissionID)
}
done := make(chan struct{})
var output []byte
var err error
go func() {
log.Printf("[EXEC-%s] Starting command execution: %v", submissionID, cmd.Args)
output, err = cmd.CombinedOutput()
close(done)
}()
select {
case <-time.After(timeout):
log.Printf("[TIMEOUT-%s] Execution timed out after %v seconds", submissionID, timeout.Seconds())
if err := cmd.Process.Kill(); err != nil {
log.Printf("[TIMEOUT-%s] Failed to kill process: %v", submissionID, err)
return nil, fmt.Errorf("timeout reached but failed to kill process: %v", err)
}
return nil, fmt.Errorf("execution timed out after %v seconds", timeout.Seconds())
case <-done:
if err != nil {
log.Printf("[EXEC-%s] Command execution failed: %v", submissionID, err)
} else {
log.Printf("[EXEC-%s] Command execution completed successfully", submissionID)
}
return output, err
}
}
// executePython runs Python code in a container
func (s *ExecutionService) executePython(submission *model.CodeSubmission) {
log.Printf("[PYTHON-%s] Preparing Python execution environment", submission.ID)
startTime := time.Now()
cmd := exec.Command("docker", "run", "--rm", "-i",
"--network=none", // No network access
"--memory=100m", // Memory limit
"--cpu-period=100000", // CPU quota period
"--cpu-quota=10000", // 10% CPU
"--ulimit", "nofile=64:64", // File descriptor limits
"python:3.9", "python", "-c", submission.Code)
log.Printf("[PYTHON-%s] Executing Python code with timeout: 10s", submission.ID)
var output []byte
var err error
if submission.Input != "" {
cmd.Stdin = strings.NewReader(submission.Input)
output, err = cmd.CombinedOutput()
} else {
output, err = s.executeWithTimeout(cmd, 10*time.Second, submission.ID)
}
elapsed := time.Since(startTime)
log.Printf("[PYTHON-%s] Python execution completed in %v", submission.ID, elapsed)
s.updateSubmissionResult(submission, output, err)
}
// extractClassName extracts the Java class name from code
func extractClassName(code string) string {
// Default class name as fallback
defaultClass := "Solution"
// Look for public class
re := regexp.MustCompile(`public\s+class\s+(\w+)`)
matches := re.FindStringSubmatch(code)
if len(matches) > 1 {
return matches[1]
}
// Look for any class if no public class
re = regexp.MustCompile(`class\s+(\w+)`)
matches = re.FindStringSubmatch(code)
if len(matches) > 1 {
return matches[1]
}
return defaultClass
}
// executeJava runs Java code in a container
func (s *ExecutionService) executeJava(submission *model.CodeSubmission) {
log.Printf("[JAVA-%s] Preparing Java execution environment", submission.ID)
startTime := time.Now()
// Extract class name from code
className := extractClassName(submission.Code)
log.Printf("[JAVA-%s] Detected class name: %s", submission.ID, className)
// Create temp directory for Java files
tempDir, err := os.MkdirTemp("", "java-execution-"+submission.ID)
if err != nil {
log.Printf("[JAVA-%s] Failed to create temp directory: %v", submission.ID, err)
submission.Status = "failed"
submission.Output = "Failed to create temp directory: " + err.Error()
return
}
defer os.RemoveAll(tempDir)
log.Printf("[JAVA-%s] Created temp directory: %s", submission.ID, tempDir)
// Write Java code to file with detected class name
javaFilePath := filepath.Join(tempDir, className+".java")
if err := os.WriteFile(javaFilePath, []byte(submission.Code), 0644); err != nil {
log.Printf("[JAVA-%s] Failed to write Java file: %v", submission.ID, err)
submission.Status = "failed"
submission.Output = "Failed to write Java file: " + err.Error()
return
}
log.Printf("[JAVA-%s] Wrote code to file: %s", submission.ID, javaFilePath)
// First compile without running
compileCmd := exec.Command("docker", "run", "--rm",
"-v", tempDir+":/code", // Mount code directory
"eclipse-temurin:11-jdk-alpine",
"javac", "/code/"+className+".java")
log.Printf("[JAVA-%s] Compiling Java code", submission.ID)
compileOutput, compileErr := compileCmd.CombinedOutput()
if compileErr != nil {
log.Printf("[JAVA-%s] Compilation failed: %v", submission.ID, compileErr)
submission.Status = "failed"
submission.Output = "Compilation error:\n" + string(compileOutput)
return
}
log.Printf("[JAVA-%s] Compilation successful", submission.ID)
// Now run the compiled class
runCmd := exec.Command("docker", "run", "--rm", "-i",
"--network=none", // No network access
"--memory=400m", // Memory limit
"--cpu-period=100000", // CPU quota period
"--cpu-quota=50000", // 50% CPU
"-v", tempDir+":/code", // Mount code directory
"eclipse-temurin:11-jdk-alpine",
"java", "-XX:+TieredCompilation", "-XX:TieredStopAtLevel=1",
"-Xverify:none", "-Xms64m", "-Xmx256m",
"-cp", "/code", className)
// Add input if provided
var output []byte
if submission.Input != "" {
log.Printf("[JAVA-%s] Executing Java code with input", submission.ID)
runCmd.Stdin = strings.NewReader(submission.Input)
output, err = runCmd.CombinedOutput()
} else {
log.Printf("[JAVA-%s] Executing Java code without input", submission.ID)
output, err = s.executeWithTimeout(runCmd, 15*time.Second, submission.ID)
}
elapsed := time.Since(startTime)
log.Printf("[JAVA-%s] Java execution completed in %v", submission.ID, elapsed)
s.updateSubmissionResult(submission, output, err)
}
// executeC runs C code in a container with improved file handling
func (s *ExecutionService) executeC(submission *model.CodeSubmission) {
log.Printf("[C-%s] Preparing C execution environment", submission.ID)
startTime := time.Now()
// Create unique temp directory for C files
tempDir, err := os.MkdirTemp("", "c-execution-"+submission.ID)
if err != nil {
log.Printf("[C-%s] Failed to create temp directory: %v", submission.ID, err)
submission.Status = "failed"
submission.Output = "Failed to create temp directory: " + err.Error()
return
}
defer os.RemoveAll(tempDir)
log.Printf("[C-%s] Created temp directory: %s", submission.ID, tempDir)
// Write C code to file
cFilePath := filepath.Join(tempDir, "solution.c")
if err := os.WriteFile(cFilePath, []byte(submission.Code), 0644); err != nil {
log.Printf("[C-%s] Failed to write C file: %v", submission.ID, err)
submission.Status = "failed"
submission.Output = "Failed to write C file: " + err.Error()
return
}
log.Printf("[C-%s] Wrote code to file: %s", submission.ID, cFilePath)
// Compile C code first
compileCmd := exec.Command("docker", "run", "--rm",
"-v", tempDir+":/code", // Mount code directory
"gcc:latest", "gcc", "-o", "/code/solution", "/code/solution.c")
compileOutput, compileErr := compileCmd.CombinedOutput()
if compileErr != nil {
log.Printf("[C-%s] Compilation failed: %v", submission.ID, compileErr)
submission.Status = "failed"
submission.Output = "Compilation error:\n" + string(compileOutput)
return
}
log.Printf("[C-%s] Compilation successful", submission.ID)
// Run C executable
runCmd := exec.Command("docker", "run", "--rm", "-i",
"--network=none", // No network access
"--memory=100m", // Memory limit
"--cpu-period=100000", // CPU quota period
"--cpu-quota=10000", // 10% CPU
"-v", tempDir+":/code", // Mount code directory
"gcc:latest", "/code/solution")
// Add input if provided
var output []byte
// Don't redeclare err here - use the existing variable
if submission.Input != "" {
log.Printf("[C-%s] Executing C code with input", submission.ID)
runCmd.Stdin = strings.NewReader(submission.Input)
output, err = runCmd.CombinedOutput() // Use the existing err variable
} else {
log.Printf("[C-%s] Executing C code without input", submission.ID)
output, err = s.executeWithTimeout(runCmd, 10*time.Second, submission.ID) // Use the existing err variable
}
elapsed := time.Since(startTime)
log.Printf("[C-%s] C execution completed in %v", submission.ID, elapsed)
s.updateSubmissionResult(submission, output, err)
}
// executeCpp runs C++ code in a container with improved file handling
func (s *ExecutionService) executeCpp(submission *model.CodeSubmission) {
log.Printf("[CPP-%s] Preparing C++ execution environment", submission.ID)
startTime := time.Now()
// Create unique temp directory for C++ files
tempDir, err := os.MkdirTemp("", "cpp-execution-"+submission.ID)
if err != nil {
log.Printf("[CPP-%s] Failed to create temp directory: %v", submission.ID, err)
submission.Status = "failed"
submission.Output = "Failed to create temp directory: " + err.Error()
return
}
defer os.RemoveAll(tempDir)
log.Printf("[CPP-%s] Created temp directory: %s", submission.ID, tempDir)
// Write C++ code to file
cppFilePath := filepath.Join(tempDir, "solution.cpp")
if err := os.WriteFile(cppFilePath, []byte(submission.Code), 0644); err != nil {
log.Printf("[CPP-%s] Failed to write C++ file: %v", submission.ID, err)
submission.Status = "failed"
submission.Output = "Failed to write C++ file: " + err.Error()
return
}
log.Printf("[CPP-%s] Wrote code to file: %s", submission.ID, cppFilePath)
// Compile C++ code first
compileCmd := exec.Command("docker", "run", "--rm",
"-v", tempDir+":/code", // Mount code directory
"gcc:latest", "g++", "-o", "/code/solution", "/code/solution.cpp")
compileOutput, compileErr := compileCmd.CombinedOutput()
if compileErr != nil {
log.Printf("[CPP-%s] Compilation failed: %v", submission.ID, compileErr)
submission.Status = "failed"
submission.Output = "Compilation error:\n" + string(compileOutput)
return
}
log.Printf("[CPP-%s] Compilation successful", submission.ID)
// Run C++ executable
runCmd := exec.Command("docker", "run", "--rm", "-i",
"--network=none", // No network access
"--memory=100m", // Memory limit
"--cpu-period=100000", // CPU quota period
"--cpu-quota=10000", // 10% CPU
"-v", tempDir+":/code", // Mount code directory
"gcc:latest", "/code/solution")
// Add input if provided
var output []byte
if submission.Input != "" {
log.Printf("[CPP-%s] Executing C++ code with input", submission.ID)
runCmd.Stdin = strings.NewReader(submission.Input)
output, err = runCmd.CombinedOutput()
} else {
log.Printf("[CPP-%s] Executing C++ code without input", submission.ID)
output, err = s.executeWithTimeout(runCmd, 10*time.Second, submission.ID)
}
elapsed := time.Since(startTime)
log.Printf("[CPP-%s] C++ execution completed in %v", submission.ID, elapsed)
s.updateSubmissionResult(submission, output, err)
}
// executeWithTimeout runs a command with a timeout
func (s *ExecutionService) executeWithTimeout(cmd *exec.Cmd, timeout time.Duration, submissionID string) ([]byte, error) {
log.Printf("[TIMEOUT-%s] Setting execution timeout: %v", submissionID, timeout)
done := make(chan error, 1)
var output []byte
var err error
go func() {
log.Printf("[EXEC-%s] Starting command execution: %v", submissionID, cmd.Args)
output, err = cmd.CombinedOutput()
done <- err
}()
select {
case <-time.After(timeout):
log.Printf("[TIMEOUT-%s] Execution timed out after %v seconds", submissionID, timeout.Seconds())
if err := cmd.Process.Kill(); err != nil {
log.Printf("[TIMEOUT-%s] Failed to kill process: %v", submissionID, err)
return nil, fmt.Errorf("timeout reached but failed to kill process: %v", err)
}
return nil, fmt.Errorf("execution timed out after %v seconds", timeout.Seconds())
case err := <-done:
if err != nil {
log.Printf("[EXEC-%s] Command execution failed: %v", submissionID, err)
} else {
log.Printf("[EXEC-%s] Command execution completed successfully", submissionID)
}
return output, err
}
}
// updateSubmissionResult updates the submission with execution results
func (s *ExecutionService) updateSubmissionResult(submission *model.CodeSubmission, output []byte, err error) {
s.mu.Lock()
defer s.mu.Unlock()
submission.CompletedAt = time.Now()
executionTime := submission.CompletedAt.Sub(submission.StartedAt)
totalTime := submission.CompletedAt.Sub(submission.QueuedAt)
if err != nil {
submission.Status = "failed"
submission.Output = string(output) + "\n" + err.Error()
log.Printf("[RESULT-%s] Execution FAILED in %v (total time: %v, including queue: %v)",
submission.ID, executionTime, totalTime, totalTime-executionTime)
} else {
submission.Status = "completed"
submission.Output = string(output)
log.Printf("[RESULT-%s] Execution COMPLETED in %v (total time: %v, including queue: %v)",
submission.ID, executionTime, totalTime, totalTime-executionTime)
}
}
// GetQueueStats returns statistics about the job queue
func (s *ExecutionService) GetQueueStats() map[string]int {
stats := s.queue.QueueStats()
log.Printf("[QUEUE] Stats - Jobs in queue: %d, Running jobs: %d, Max workers: %d",
stats["queue_length"], stats["running_jobs"], stats["max_workers"])
return stats
}

View File

@@ -1,115 +0,0 @@
package service
import (
"os"
"testing"
"time"
"github.com/arnab-afk/monaco/model"
"github.com/stretchr/testify/assert"
)
// TestExecutionServiceCreation tests that the service is created properly
func TestExecutionServiceCreation(t *testing.T) {
service := NewExecutionService()
assert.NotNil(t, service)
assert.NotNil(t, service.queue)
}
// TestExtractClassName tests the class name extraction for Java code
func TestExtractClassName(t *testing.T) {
tests := []struct {
name string
code string
expected string
}{
{
name: "Public class",
code: "public class MyClass { public static void main(String[] args) {} }",
expected: "MyClass",
},
{
name: "Regular class",
code: "class RegularClass { public static void main(String[] args) {} }",
expected: "RegularClass",
},
{
name: "Multiple classes",
code: "class Class1 {} public class MainClass {} class Class2 {}",
expected: "MainClass",
},
{
name: "No class",
code: "// Just a comment",
expected: "Solution", // Default class name
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := extractClassName(tt.code)
assert.Equal(t, tt.expected, result)
})
}
}
// MockDockerExec is a function that can be used to mock Docker exec commands
type MockDockerExec func(cmd string, args ...string) ([]byte, error)
// TestUpdateSubmissionResult tests the submission result update logic
func TestUpdateSubmissionResult(t *testing.T) {
service := NewExecutionService()
// Test successful execution
submission := &model.CodeSubmission{
ID: "test-id",
Status: "running",
StartedAt: time.Now().Add(-500 * time.Millisecond),
QueuedAt: time.Now().Add(-1 * time.Second),
}
output := []byte("Hello, World!")
service.updateSubmissionResult(submission, output, nil)
assert.Equal(t, "completed", submission.Status)
assert.Equal(t, "Hello, World!", submission.Output)
assert.False(t, submission.CompletedAt.IsZero())
// Test failed execution
submission = &model.CodeSubmission{
ID: "test-id-2",
Status: "running",
StartedAt: time.Now().Add(-500 * time.Millisecond),
QueuedAt: time.Now().Add(-1 * time.Second),
}
output = []byte("Compilation error")
err := os.ErrInvalid // Any error will do for testing
service.updateSubmissionResult(submission, output, err)
assert.Equal(t, "failed", submission.Status)
assert.Contains(t, submission.Output, "Compilation error")
assert.Contains(t, submission.Output, err.Error())
assert.False(t, submission.CompletedAt.IsZero())
}
// TestCodeExecutionJob tests the job execution logic
func TestCodeExecutionJob(t *testing.T) {
service := NewExecutionService()
submission := &model.CodeSubmission{
ID: "test-id",
Language: "python",
Code: "print('test')",
Status: "queued",
QueuedAt: time.Now(),
}
job := NewCodeExecutionJob(service, submission)
assert.NotNil(t, job)
assert.Equal(t, submission, job.submission)
assert.Equal(t, service, job.service)
// We can't easily test the actual execution because it depends on Docker
// In a real test environment, you would mock the Docker calls
}

View File

@@ -1,17 +0,0 @@
package service
import (
"crypto/rand"
"fmt"
"time"
)
// GenerateUUID creates a random UUID
func GenerateUUID() string {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
return fmt.Sprintf("%d", time.Now().UnixNano())
}
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
}

View File

@@ -1,96 +0,0 @@
import requests
import concurrent.futures
import time
# Define the endpoint URLs
POST_URL = "http://localhost:8080/submit"
GET_URL = "http://localhost:8080/result?id={}"
# Define the request bodies
cpp_payload = {
"language": "cpp",
"code": """#include <iostream>\n#include <string>\n\nint main() {\n std::string name;\n std::cout << \"Enter your name: \";\n std::cin >> name;\n std::cout << \"Hello, \" << name << \"!\" << std::endl;\n return 0;\n}""",
"input": "Alice"
}
java_payload = {
"language": "java",
"code": """import java.util.Scanner;\n\npublic class Solution {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n System.out.print(\"Enter your name: \");\n String name = scanner.nextLine();\n System.out.println(\"Hello, \" + name + \"!\");\n scanner.close();\n }\n}""",
"input": "Jane"
}
def send_request(index):
"""Sends a POST request and returns the task ID."""
payload = cpp_payload if index % 2 == 0 else java_payload
for _ in range(3): # Retry up to 3 times
try:
response = requests.post(POST_URL, json=payload, timeout=10)
if response.status_code == 200:
task_id = response.json().get("id")
print(f"Request {index} sent. Task ID: {task_id}")
return task_id
except requests.exceptions.RequestException as e:
print(f"Request {index} failed: {e}")
time.sleep(1)
return None
def get_result(task_id):
"""Polls the result endpoint until completion."""
if not task_id:
return None
max_retries = 50 # Prevent infinite loop
retries = 0
while retries < max_retries:
try:
response = requests.get(GET_URL.format(task_id), timeout=10)
if response.status_code == 200:
result = response.json()
if result.get("status") == "completed":
print(f"Task {task_id} completed.")
return result
time.sleep(1) # Poll every second
retries += 1
except requests.exceptions.RequestException as e:
print(f"Error fetching result for {task_id}: {e}")
print(f"Task {task_id} did not complete in time.")
return None
def main():
start_time = time.time()
task_ids = []
print("Sending 500 requests...")
# Send 500 requests concurrently
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
futures = {executor.submit(send_request, i): i for i in range(500)}
for future in concurrent.futures.as_completed(futures):
task_id = future.result()
if task_id:
task_ids.append(task_id)
print(f"Sent {len(task_ids)} requests. Waiting for results...")
# Fetch results
results = []
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
futures = {executor.submit(get_result, task_id): task_id for task_id in task_ids}
for future in concurrent.futures.as_completed(futures):
result = future.result()
if result:
results.append(result)
# Calculate execution stats
total_time = time.time() - start_time
waiting_times = [r["totalTime"] for r in results if "totalTime" in r]
avg_waiting_time = sum(waiting_times) / len(waiting_times) if waiting_times else 0
print("\nExecution Stats:")
print(f"Total Execution Time: {total_time:.2f}s")
print(f"Total Requests Processed: {len(results)}/{len(task_ids)}")
print(f"Average Waiting Time: {avg_waiting_time:.2f}ms")
print(f"Min Waiting Time: {min(waiting_times, default=0)}ms")
print(f"Max Waiting Time: {max(waiting_times, default=0)}ms")
if __name__ == "__main__":
main()

View File

@@ -1,195 +0,0 @@
package tests
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/arnab-afk/monaco/handler"
"github.com/stretchr/testify/assert"
)
func setupTestServer() *httptest.Server {
h := handler.NewHandler()
mux := http.NewServeMux()
mux.HandleFunc("/submit", h.SubmitHandler)
mux.HandleFunc("/status", h.StatusHandler)
mux.HandleFunc("/result", h.ResultHandler)
mux.HandleFunc("/queue-stats", h.QueueStatsHandler)
return httptest.NewServer(mux)
}
func TestAPIIntegration(t *testing.T) {
server := setupTestServer()
defer server.Close()
// Test: Submit code, check status, and get results
// 1. Submit a Python job
submitURL := server.URL + "/submit"
body := map[string]string{
"language": "python",
"code": "print('Hello, Integration Test!')",
}
bodyBytes, _ := json.Marshal(body)
resp, err := http.Post(submitURL, "application/json", bytes.NewReader(bodyBytes))
assert.NoError(t, err)
assert.Equal(t, http.StatusAccepted, resp.StatusCode)
// Get the job ID
var submitResp map[string]string
json.NewDecoder(resp.Body).Decode(&submitResp)
resp.Body.Close()
jobID := submitResp["id"]
assert.NotEmpty(t, jobID)
// 2. Check status
statusURL := server.URL + "/status?id=" + jobID
// Wait for job to complete (try multiple times)
var statusResp map[string]interface{}
maxRetries := 10
for i := 0; i < maxRetries; i++ {
resp, err = http.Get(statusURL)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
json.NewDecoder(resp.Body).Decode(&statusResp)
resp.Body.Close()
// If job completed or failed, break
status, _ := statusResp["status"].(string)
if status == "completed" || status == "failed" {
break
}
// Wait before next retry
time.Sleep(200 * time.Millisecond)
}
// 3. Get results
resultURL := server.URL + "/result?id=" + jobID
resp, err = http.Get(resultURL)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var resultResp map[string]interface{}
json.NewDecoder(resp.Body).Decode(&resultResp)
resp.Body.Close()
assert.Equal(t, jobID, resultResp["id"])
assert.Contains(t, resultResp["output"], "Hello, Integration Test!")
// 4. Check queue stats
statsURL := server.URL + "/queue-stats"
resp, err = http.Get(statsURL)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
var statsResp map[string]interface{}
json.NewDecoder(resp.Body).Decode(&statsResp)
resp.Body.Close()
assert.Contains(t, statsResp, "queue_stats")
assert.Contains(t, statsResp, "submissions")
}
func TestMultipleLanguageSubmissions(t *testing.T) {
server := setupTestServer()
defer server.Close()
// Test submissions for different languages
languages := []string{"python", "java", "c", "cpp"}
codes := map[string]string{
"python": "print('Hello from Python')",
"java": "public class Solution { public static void main(String[] args) { System.out.println(\"Hello from Java\"); } }",
"c": "#include <stdio.h>\nint main() { printf(\"Hello from C\\n\"); return 0; }",
"cpp": "#include <iostream>\nint main() { std::cout << \"Hello from C++\" << std::endl; return 0; }",
}
submitURL := server.URL + "/submit"
for _, lang := range languages {
body := map[string]string{
"language": lang,
"code": codes[lang],
}
bodyBytes, _ := json.Marshal(body)
resp, err := http.Post(submitURL, "application/json", bytes.NewReader(bodyBytes))
assert.NoError(t, err)
assert.Equal(t, http.StatusAccepted, resp.StatusCode)
var submitResp map[string]string
json.NewDecoder(resp.Body).Decode(&submitResp)
resp.Body.Close()
jobID := submitResp["id"]
assert.NotEmpty(t, jobID)
// We don't wait for completion in this test
// This is just to verify submission acceptance for all languages
}
}
func TestInputHandling(t *testing.T) {
server := setupTestServer()
defer server.Close()
// Test code submission with input
submitURL := server.URL + "/submit"
body := map[string]string{
"language": "python",
"code": "name = input('Enter name: ')\nprint('Hello, ' + name + '!')",
"input": "Integration Test",
}
bodyBytes, _ := json.Marshal(body)
resp, err := http.Post(submitURL, "application/json", bytes.NewReader(bodyBytes))
assert.NoError(t, err)
assert.Equal(t, http.StatusAccepted, resp.StatusCode)
var submitResp map[string]string
json.NewDecoder(resp.Body).Decode(&submitResp)
resp.Body.Close()
jobID := submitResp["id"]
assert.NotEmpty(t, jobID)
// Wait for job to complete and check result
resultURL := server.URL + "/result?id=" + jobID
// Poll for results
var resultResp map[string]interface{}
maxRetries := 10
for i := 0; i < maxRetries; i++ {
time.Sleep(300 * time.Millisecond)
resp, err = http.Get(resultURL)
assert.NoError(t, err)
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
continue
}
json.NewDecoder(resp.Body).Decode(&resultResp)
resp.Body.Close()
status, _ := resultResp["status"].(string)
if status == "completed" || status == "failed" {
break
}
}
// Verify output contains the greeting with input
assert.Contains(t, resultResp["output"], "Hello, Integration Test!")
}

View File

@@ -1,278 +0,0 @@
import requests
import concurrent.futures
import time
import statistics
import matplotlib.pyplot as plt
import numpy as np
# Define the endpoint URLs
POST_URL = "http://localhost:8080/submit"
GET_URL_STATUS = "http://localhost:8080/status?id={}"
GET_URL_RESULT = "http://localhost:8080/result?id={}"
GET_URL_STATS = "http://localhost:8080/queue-stats"
# Test payloads for different languages
PAYLOADS = {
"python": {
"language": "python",
"code": "print('Hello, Load Test!')",
},
"java": {
"language": "java",
"code": "public class Solution { public static void main(String[] args) { System.out.println(\"Hello, Load Test!\"); } }",
},
"c": {
"language": "c",
"code": "#include <stdio.h>\nint main() { printf(\"Hello, Load Test!\\n\"); return 0; }",
},
"cpp": {
"language": "cpp",
"code": "#include <iostream>\nint main() { std::cout << \"Hello, Load Test!\" << std::endl; return 0; }",
}
}
def send_request(language, index):
"""Sends a POST request and returns (task_id, time_taken)."""
payload = PAYLOADS[language]
start_time = time.time()
try:
response = requests.post(POST_URL, json=payload, timeout=10)
end_time = time.time()
if response.status_code == 202:
return response.json().get("id"), end_time - start_time
else:
print(f"Request {index} failed with status {response.status_code}")
return None, end_time - start_time
except requests.exceptions.RequestException as e:
end_time = time.time()
print(f"Request {index} error: {e}")
return None, end_time - start_time
def wait_for_result(task_id, index):
"""Waits for a result and returns (result, time_taken)."""
if not task_id:
return None, 0
start_time = time.time()
max_retries = 30
retry_interval = 0.5 # seconds
for _ in range(max_retries):
try:
response = requests.get(GET_URL_RESULT.format(task_id), timeout=10)
if response.status_code == 200:
result = response.json()
if result.get("status") in ["completed", "failed"]:
end_time = time.time()
return result, end_time - start_time
time.sleep(retry_interval)
except requests.exceptions.RequestException as e:
print(f"Error checking result for task {index}: {e}")
end_time = time.time()
print(f"Timed out waiting for result of task {index}")
return None, end_time - start_time
def run_test(concurrency, requests_per_language):
"""Runs a load test with the specified parameters."""
languages = list(PAYLOADS.keys())
all_results = {lang: [] for lang in languages}
submit_times = {lang: [] for lang in languages}
wait_times = {lang: [] for lang in languages}
success_rates = {lang: 0 for lang in languages}
# Keep track of all submissions for each language
total_per_language = {lang: 0 for lang in languages}
successful_per_language = {lang: 0 for lang in languages}
start_time = time.time()
# Create a list of tasks
tasks = []
for lang in languages:
for i in range(requests_per_language):
tasks.append((lang, i))
print(f"Running load test with {concurrency} concurrent connections")
print(f"Sending {requests_per_language} requests per language ({len(languages)} languages)")
# Submit all tasks
task_ids = {}
with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as executor:
future_to_task = {executor.submit(send_request, lang, i): (lang, i) for lang, i in tasks}
for future in concurrent.futures.as_completed(future_to_task):
lang, i = future_to_task[future]
total_per_language[lang] += 1
try:
task_id, submit_time = future.result()
if task_id:
task_ids[(lang, i)] = task_id
submit_times[lang].append(submit_time)
except Exception as e:
print(f"Error submitting {lang} task {i}: {e}")
print(f"Submitted {len(task_ids)} tasks successfully")
# Wait for all results
with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as executor:
future_to_task = {executor.submit(wait_for_result, task_ids.get((lang, i)), i): (lang, i)
for lang, i in tasks if (lang, i) in task_ids}
for future in concurrent.futures.as_completed(future_to_task):
lang, i = future_to_task[future]
try:
result, wait_time = future.result()
if result and result.get("status") == "completed":
successful_per_language[lang] += 1
all_results[lang].append(result)
wait_times[lang].append(wait_time)
except Exception as e:
print(f"Error waiting for {lang} task {i}: {e}")
end_time = time.time()
total_time = end_time - start_time
# Calculate success rates
for lang in languages:
if total_per_language[lang] > 0:
success_rates[lang] = (successful_per_language[lang] / total_per_language[lang]) * 100
else:
success_rates[lang] = 0
# Calculate statistics
stats = {
"total_time": total_time,
"requests_per_second": len(task_ids) / total_time if total_time > 0 else 0,
"success_rate": sum(success_rates.values()) / len(success_rates) if success_rates else 0,
"submit_times": {
lang: {
"avg": statistics.mean(times) if times else 0,
"min": min(times) if times else 0,
"max": max(times) if times else 0,
"p95": np.percentile(times, 95) if times else 0
} for lang, times in submit_times.items()
},
"wait_times": {
lang: {
"avg": statistics.mean(times) if times else 0,
"min": min(times) if times else 0,
"max": max(times) if times else 0,
"p95": np.percentile(times, 95) if times else 0
} for lang, times in wait_times.items()
},
"success_rates": success_rates
}
return stats, all_results
def print_stats(stats):
"""Prints test statistics."""
print("\n=== Load Test Results ===")
print(f"Total time: {stats['total_time']:.2f}s")
print(f"Requests per second: {stats['requests_per_second']:.2f}")
print(f"Overall success rate: {stats['success_rate']:.2f}%")
print("\n== Submit Times (seconds) ==")
for lang, times in stats["submit_times"].items():
print(f"{lang:<6}: avg={times['avg']:.4f}, min={times['min']:.4f}, max={times['max']:.4f}, p95={times['p95']:.4f}")
print("\n== Wait Times (seconds) ==")
for lang, times in stats["wait_times"].items():
print(f"{lang:<6}: avg={times['avg']:.4f}, min={times['min']:.4f}, max={times['max']:.4f}, p95={times['p95']:.4f}")
print("\n== Success Rates ==")
for lang, rate in stats["success_rates"].items():
print(f"{lang:<6}: {rate:.2f}%")
def plot_results(stats):
"""Creates visualizations of test results."""
languages = list(stats["submit_times"].keys())
# Plot submit times
plt.figure(figsize=(12, 10))
plt.subplot(2, 2, 1)
plt.title("Average Submit Time by Language")
avg_times = [stats["submit_times"][lang]["avg"] for lang in languages]
plt.bar(languages, avg_times)
plt.ylabel("Time (seconds)")
plt.subplot(2, 2, 2)
plt.title("Average Wait Time by Language")
avg_wait_times = [stats["wait_times"][lang]["avg"] for lang in languages]
plt.bar(languages, avg_wait_times)
plt.ylabel("Time (seconds)")
plt.subplot(2, 2, 3)
plt.title("Success Rate by Language")
success_rates = [stats["success_rates"][lang] for lang in languages]
plt.bar(languages, success_rates)
plt.ylabel("Success Rate (%)")
plt.ylim(0, 100)
plt.subplot(2, 2, 4)
plt.title("95th Percentile Wait Time by Language")
p95_times = [stats["wait_times"][lang]["p95"] for lang in languages]
plt.bar(languages, p95_times)
plt.ylabel("Time (seconds)")
plt.tight_layout()
plt.savefig("load_test_results.png")
print("Results saved to load_test_results.png")
def main():
# Run tests with different concurrency levels
concurrency_levels = [10, 20, 30]
requests_per_language = 10
all_stats = []
for concurrency in concurrency_levels:
stats, results = run_test(concurrency, requests_per_language)
all_stats.append((concurrency, stats))
print_stats(stats)
# Create comparison visualization
plt.figure(figsize=(12, 8))
plt.subplot(2, 2, 1)
plt.title("Requests per Second vs Concurrency")
plt.plot([s[0] for s in all_stats], [s[1]["requests_per_second"] for s in all_stats], "o-")
plt.xlabel("Concurrency Level")
plt.ylabel("Requests per Second")
plt.subplot(2, 2, 2)
plt.title("Success Rate vs Concurrency")
plt.plot([s[0] for s in all_stats], [s[1]["success_rate"] for s in all_stats], "o-")
plt.xlabel("Concurrency Level")
plt.ylabel("Success Rate (%)")
plt.ylim(0, 100)
plt.subplot(2, 2, 3)
plt.title("Average Submit Time vs Concurrency")
for lang in PAYLOADS.keys():
plt.plot([s[0] for s in all_stats],
[s[1]["submit_times"][lang]["avg"] for s in all_stats],
"o-", label=lang)
plt.xlabel("Concurrency Level")
plt.ylabel("Average Submit Time (s)")
plt.legend()
plt.subplot(2, 2, 4)
plt.title("Average Wait Time vs Concurrency")
for lang in PAYLOADS.keys():
plt.plot([s[0] for s in all_stats],
[s[1]["wait_times"][lang]["avg"] for s in all_stats],
"o-", label=lang)
plt.xlabel("Concurrency Level")
plt.ylabel("Average Wait Time (s)")
plt.legend()
plt.tight_layout()
plt.savefig("concurrency_comparison.png")
print("Concurrency comparison saved to concurrency_comparison.png")
# Plot detailed results for the highest concurrency test
plot_results(all_stats[-1][1])
if __name__ == "__main__":
main()

View File

@@ -1 +0,0 @@
exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1

37
new-backend/Dockerfile Normal file
View File

@@ -0,0 +1,37 @@
FROM golang:1.19-alpine AS builder
# Install git and required dependencies
RUN apk update && apk add --no-cache git
# Set working directory
WORKDIR /app
# Copy go mod and sum files
COPY go.mod go.sum* ./
# Download dependencies
RUN go mod download
# Copy source code
COPY . .
# Build the application with optimizations
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags="-s -w" -o monaco-backend .
# Use a smaller image for the final container
FROM alpine:latest
# Install Docker client (required for container-in-container execution)
RUN apk update && apk add --no-cache docker-cli
# Create a non-root user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
# Copy the binary from builder
COPY --from=builder /app/monaco-backend /monaco-backend
# Use non-root user
USER appuser
# Run the binary
ENTRYPOINT ["/monaco-backend"]

View File

@@ -0,0 +1,74 @@
FROM golang:1.19-alpine AS builder
# Install git and required dependencies
RUN apk update && apk add --no-cache git
# Set working directory
WORKDIR /app
# Copy go mod and sum files
COPY go.mod go.sum* ./
# Download dependencies
RUN go mod download
# Copy source code
COPY . .
# Build the application with optimizations
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags="-s -w" -o monaco-backend .
# Final stage
FROM alpine:latest
# Install Docker client and supervisor
RUN apk update && apk add --no-cache docker-cli supervisor wget
# Get cloudflared directly from GitHub (more reliable than the tarball)
RUN wget -O cloudflared https://github.com/cloudflare/cloudflared/releases/download/2023.5.0/cloudflared-linux-amd64 && \
chmod +x cloudflared && \
mv cloudflared /usr/local/bin/
# Create directories for cloudflared
RUN mkdir -p /etc/cloudflared
# Copy the certificate file and config
COPY cert.pem /etc/cloudflared/cert.pem
COPY credentials.json /etc/cloudflared/credentials.json
COPY config.json /etc/cloudflared/config.json
# Setup DNS routing for the tunnel (only needs to be done once)
RUN cloudflared tunnel route dns 5d2682ef-0b5b-47e5-b0fa-ad48968ce016 api.ishikabhoyar.tech || echo "DNS routing already set up or failed - continuing anyway"
# Copy the binary from builder
COPY --from=builder /app/monaco-backend /monaco-backend
# Create supervisord config
RUN mkdir -p /etc/supervisor/conf.d/
RUN echo "[supervisord]" > /etc/supervisor/conf.d/supervisord.conf && \
echo "nodaemon=true" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "user=root" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "[program:backend]" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "command=/monaco-backend" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "autostart=true" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "autorestart=true" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "stdout_logfile=/dev/stdout" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "stdout_logfile_maxbytes=0" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "stderr_logfile=/dev/stderr" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "stderr_logfile_maxbytes=0" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "[program:cloudflared]" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "command=cloudflared tunnel --config /etc/cloudflared/config.json run" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "autostart=true" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "autorestart=true" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "stdout_logfile=/dev/stdout" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "stdout_logfile_maxbytes=0" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "stderr_logfile=/dev/stderr" >> /etc/supervisor/conf.d/supervisord.conf && \
echo "stderr_logfile_maxbytes=0" >> /etc/supervisor/conf.d/supervisord.conf
# Expose port for local access
EXPOSE 8080
# Use supervisord to manage processes
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]

View File

@@ -0,0 +1,24 @@
# Tunnel-only Dockerfile - Backend runs outside Docker on port 9090
FROM alpine:latest
# Install wget to download cloudflared
RUN apk update && apk add --no-cache wget ca-certificates
# Get cloudflared directly from GitHub
RUN wget -O cloudflared https://github.com/cloudflare/cloudflared/releases/download/2023.5.0/cloudflared-linux-amd64 && \
chmod +x cloudflared && \
mv cloudflared /usr/local/bin/
# Create directories for cloudflared
RUN mkdir -p /etc/cloudflared
# Copy the certificate file and config
COPY cert.pem /etc/cloudflared/cert.pem
COPY credentials.json /etc/cloudflared/credentials.json
COPY config.tunnel-only.json /etc/cloudflared/config.json
# Setup DNS routing for the tunnel (only needs to be done once)
RUN cloudflared tunnel route dns 5d2682ef-0b5b-47e5-b0fa-ad48968ce016 api.ishikabhoyar.tech || echo "DNS routing already set up or failed - continuing anyway"
# Run cloudflared tunnel
CMD ["cloudflared", "tunnel", "--config", "/etc/cloudflared/config.json", "run"]

View File

@@ -0,0 +1,24 @@
# Tunnel-only Dockerfile V2 - Uses localhost with host network mode
FROM alpine:latest
# Install wget to download cloudflared
RUN apk update && apk add --no-cache wget ca-certificates
# Get cloudflared directly from GitHub
RUN wget -O cloudflared https://github.com/cloudflare/cloudflared/releases/download/2023.5.0/cloudflared-linux-amd64 && \
chmod +x cloudflared && \
mv cloudflared /usr/local/bin/
# Create directories for cloudflared
RUN mkdir -p /etc/cloudflared
# Copy the certificate file and config
COPY cert.pem /etc/cloudflared/cert.pem
COPY credentials.json /etc/cloudflared/credentials.json
COPY config.tunnel-only-v2.json /etc/cloudflared/config.json
# Setup DNS routing for the tunnel (only needs to be done once)
RUN cloudflared tunnel route dns 5d2682ef-0b5b-47e5-b0fa-ad48968ce016 api.ishikabhoyar.tech || echo "DNS routing already set up or failed - continuing anyway"
# Run cloudflared tunnel
CMD ["cloudflared", "tunnel", "--config", "/etc/cloudflared/config.json", "run"]

View File

@@ -0,0 +1,66 @@
FROM golang:1.19-alpine AS builder
# Install git and required dependencies
RUN apk update && apk add --no-cache git
# Set working directory
WORKDIR /app
# Copy go mod and sum files
COPY go.mod go.sum* ./
# Download dependencies
RUN go mod download
# Copy source code
COPY . .
# Build the application with optimizations
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags="-s -w" -o monaco-backend .
# Final stage
FROM alpine:latest
# Install Docker client and tools
RUN apk update && apk add --no-cache docker-cli bash wget
# Get cloudflared directly
RUN wget -O cloudflared https://github.com/cloudflare/cloudflared/releases/download/2023.7.3/cloudflared-linux-amd64 && \
chmod +x cloudflared && \
mv cloudflared /usr/local/bin/
# Create directories for cloudflared
RUN mkdir -p /etc/cloudflared
# Copy the certificate file and config
COPY cert.pem /etc/cloudflared/cert.pem
COPY config.json /etc/cloudflared/config.json
# Copy the binary from builder
COPY --from=builder /app/monaco-backend /monaco-backend
# Create a simple bash script to run both services
RUN echo '#!/bin/bash\n\
# Start the backend in the background\n\
/monaco-backend &\n\
BACKEND_PID=$!\n\
echo "Backend started with PID: $BACKEND_PID"\n\
\n\
# Wait for backend to start\n\
echo "Waiting for backend to initialize..."\n\
sleep 5\n\
\n\
# Start cloudflared with proper arguments\n\
echo "Starting Cloudflare tunnel to api.ishikabhoyar.tech..."\n\
# Use the specific tunnel name from config.json\n\
cloudflared tunnel run monaco-backend-tunnel\n\
\n\
# If cloudflared exits, kill the backend\n\
kill $BACKEND_PID\n\
' > /start.sh && chmod +x /start.sh
# Expose port for local access
EXPOSE 8080
# Run the startup script
CMD ["/start.sh"]

21
new-backend/Makefile Normal file
View File

@@ -0,0 +1,21 @@
.PHONY: build run run-detached stop logs
# Build the image
build:
docker-compose -f docker-compose.tunnel.yml build
# Run the container
run: build
docker-compose -f docker-compose.tunnel.yml up
# Run in detached mode
run-detached: build
docker-compose -f docker-compose.tunnel.yml up -d
# Stop the container
stop:
docker-compose -f docker-compose.tunnel.yml down
# View logs
logs:
docker-compose -f docker-compose.tunnel.yml logs -f

93
new-backend/README.md Normal file
View File

@@ -0,0 +1,93 @@
# Monaco Code Execution Backend
A modern, secure, and efficient code execution backend inspired by online code editors like Programiz. This backend is written in Go and uses Docker containers for secure code execution.
## Features
- **Multi-language Support**: Execute code in Python, Java, C, C++, JavaScript, and Go
- **Real-time Output**: Stream code execution output via WebSockets
- **Interactive Input**: Send input to running programs via WebSockets
- **Secure Execution**: All code runs in isolated Docker containers
- **Resource Limits**: Memory, CPU, and execution time limits
- **Scalable Architecture**: Concurrent execution with configurable worker pools
## Requirements
- Go 1.19+
- Docker
- Git (for development)
## Getting Started
### Running Locally
1. Clone the repository:
```bash
git clone https://github.com/your-username/monaco.git
cd monaco/new-backend
```
2. Install dependencies:
```bash
go mod download
```
3. Build and run:
```bash
go run main.go
```
The server will start on `http://localhost:8080` by default.
### Using Docker
Build and run using Docker:
```bash
docker build -t monaco-backend .
docker run -p 8080:8080 -v /var/run/docker.sock:/var/run/docker.sock monaco-backend
```
Note: Mounting the Docker socket is necessary for container-in-container execution.
## API Endpoints
- `POST /api/submit`: Submit code for execution
- `GET /api/status/{id}`: Get execution status
- `GET /api/result/{id}`: Get complete execution result
- `GET /api/languages`: List supported languages
- `GET /api/health`: Health check endpoint
- `WS /api/ws/terminal/{id}`: WebSocket for real-time output
## WebSocket Communication
The `/api/ws/terminal/{id}` endpoint supports these message types:
- `output`: Code execution output
- `input`: User input to the program
- `input_prompt`: Input prompt detected
- `status`: Execution status updates
- `error`: Error messages
## Configuration
Configuration is handled through environment variables:
- `PORT`: Server port (default: 8080)
- `CONCURRENT_EXECUTIONS`: Number of concurrent executions (default: 5)
- `QUEUE_CAPACITY`: Execution queue capacity (default: 100)
- `DEFAULT_TIMEOUT`: Default execution timeout in seconds (default: 30)
See `config/config.go` for more configuration options.
## Security Considerations
- All code execution happens in isolated Docker containers
- Network access is disabled in execution containers
- Memory and CPU limits are enforced
- Process limits prevent fork bombs
- Execution timeouts prevent infinite loops
## License
MIT

View File

@@ -0,0 +1,115 @@
# Monaco Backend - Tunnel Only Setup
This setup runs **only the Cloudflare tunnel** in Docker, while the backend runs **outside Docker on port 9090**.
## Prerequisites
1. Backend must be running on port 9090 on your local machine
2. Required files in this directory:
- `cert.pem` - Cloudflare tunnel certificate
- `credentials.json` - Cloudflare tunnel credentials
- `config.tunnel-only.json` - Tunnel configuration (points to port 9090)
## Setup
### 1. Start your backend on port 9090
Run your Go backend locally:
```bash
# Option 1: Run directly
PORT=9090 go run main.go
# Option 2: Build and run
go build -o main
PORT=9090 ./main
```
### 2. Start the tunnel
In this directory, run:
```bash
docker-compose -f docker-compose.tunnel-only.yml up --build
```
Or run in detached mode:
```bash
docker-compose -f docker-compose.tunnel-only.yml up --build -d
```
### 3. Check logs
```bash
docker-compose -f docker-compose.tunnel-only.yml logs -f
```
## How It Works
1. The tunnel container runs only `cloudflared`
2. It connects to Cloudflare's edge network
3. Traffic from `api.ishikabhoyar.tech` is routed through the tunnel
4. The tunnel forwards requests to `host.docker.internal:9090` (your local backend)
5. Your backend on port 9090 handles the requests and sends responses back
## Configuration
The tunnel is configured in `config.tunnel-only.json`:
```json
{
"tunnel": "5d2682ef-0b5b-47e5-b0fa-ad48968ce016",
"credentials-file": "/etc/cloudflared/credentials.json",
"ingress": [
{
"hostname": "api.ishikabhoyar.tech",
"service": "http://host.docker.internal:9090"
},
{
"service": "http_status:404"
}
],
"protocol": "http2",
"loglevel": "info"
}
```
## Troubleshooting
### Tunnel can't reach backend
- Make sure your backend is running on port 9090
- Test locally: `curl http://localhost:9090`
- Check firewall settings
### Tunnel connection issues
- Verify `credentials.json` and `cert.pem` are valid
- Check tunnel status in Cloudflare dashboard
- Review logs: `docker-compose -f docker-compose.tunnel-only.yml logs -f`
### DNS not resolving
- DNS routing should be set up during first build
- Verify in Cloudflare dashboard under Zero Trust > Networks > Tunnels
## Stop the tunnel
```bash
docker-compose -f docker-compose.tunnel-only.yml down
```
## Architecture
```
Internet
Cloudflare Edge (api.ishikabhoyar.tech)
Cloudflare Tunnel (in Docker)
host.docker.internal:9090
Your Backend (running locally)
```
## Notes
- The tunnel only forwards traffic; it doesn't run the backend
- Backend must be started before or after the tunnel (order doesn't matter)
- If backend restarts, tunnel will automatically reconnect
- Port 9090 is not exposed to the internet, only accessible via the tunnel

View File

@@ -0,0 +1,46 @@
# Backend with Cloudflare Tunnel
This setup runs the Monaco backend service and establishes a Cloudflare tunnel, exposing the service to the internet securely via api.ishikabhoyar.tech.
## Prerequisites
- Docker and Docker Compose installed
- The Cloudflare tunnel certificate (cert.pem) in the same directory as the Dockerfile.tunnel
## Files
- `Dockerfile.tunnel`: Dockerfile that builds the backend and sets up Cloudflare tunnel
- `cert.pem`: Cloudflare tunnel certificate
- `config.json`: Cloudflare tunnel configuration that routes traffic to api.ishikabhoyar.tech
- `docker-compose.tunnel.yml`: Docker Compose configuration for easy deployment
## How to Run
```bash
# Build and start the container
docker-compose -f docker-compose.tunnel.yml up -d
# Check logs
docker-compose -f docker-compose.tunnel.yml logs -f
```
## How it Works
1. The Dockerfile builds the Go backend application
2. It installs the Cloudflare tunnel client (cloudflared)
3. On container start:
- The backend server starts on port 8080
- The Cloudflare tunnel connects to Cloudflare's edge network using the config.json
- External traffic to api.ishikabhoyar.tech is routed through the tunnel to the backend
- The cloudflared runs entirely within the container, isolated from any host cloudflared instance
## Environment Variables
You can customize the behavior by modifying the environment variables in the docker-compose.tunnel.yml file:
- `PORT`: The port the backend server listens on (default: 8080)
- `CONCURRENT_EXECUTIONS`: Number of concurrent code executions (default: 5)
- `QUEUE_CAPACITY`: Maximum queue capacity for code executions (default: 100)
- `DEFAULT_TIMEOUT`: Default timeout for code execution in seconds (default: 30)
- `SANDBOX_NETWORK_DISABLED`: Whether to disable network in sandbox containers (default: true)
- `SANDBOX_PIDS_LIMIT`: Process ID limit for sandbox containers (default: 50)

View File

@@ -0,0 +1,123 @@
# Tunnel Connection Options - Troubleshooting Guide
## The Problem
When the tunnel runs in Docker and tries to reach your backend on the host, there are different ways to address the host machine. The method that works depends on your Docker setup.
## Solution 1: Direct Bridge IP (config.tunnel-only.json) ✅ WORKING
**Files:**
- `Dockerfile.tunnel-only`
- `docker-compose.tunnel-only.yml`
- `config.tunnel-only.json` (updated to use `172.18.0.1:9090`)
**How it works:**
- Uses the Docker bridge network IP directly
- You verified this works: `curl 172.18.0.1:9090`
**Usage:**
```bash
docker-compose -f docker-compose.tunnel-only.yml up --build
```
**Config:**
```json
"service": "http://172.18.0.1:9090"
```
## Solution 2: Host Network Mode (NEW - Recommended for Linux)
**Files:**
- `Dockerfile.tunnel-only-v2`
- `docker-compose.tunnel-only-v2.yml`
- `config.tunnel-only-v2.json` (uses `localhost:9090`)
**How it works:**
- Container runs in host network mode
- Can access `localhost:9090` directly as if running on host
**Usage:**
```bash
docker-compose -f docker-compose.tunnel-only-v2.yml up --build
```
**Config:**
```json
"service": "http://localhost:9090"
```
**Note:** Host network mode works best on Linux. May have limitations on Windows/Mac.
## Quick Test Guide
### 1. Rebuild and restart with updated config (Solution 1)
```bash
# Stop current tunnel
docker-compose -f docker-compose.tunnel-only.yml down
# Rebuild with updated config (now uses 172.18.0.1)
docker-compose -f docker-compose.tunnel-only.yml up --build
```
### 2. Or try host network mode (Solution 2)
```bash
docker-compose -f docker-compose.tunnel-only-v2.yml up --build
```
## Expected Success Output
```
INF Registered tunnel connection connIndex=0 connection=xxx event=0 ip=xxx location=bom protocol=http2
INF Registered tunnel connection connIndex=1 connection=xxx event=0 ip=xxx location=bom protocol=http2
INF Registered tunnel connection connIndex=2 connection=xxx event=0 ip=xxx location=bom protocol=http2
INF Registered tunnel connection connIndex=3 connection=xxx event=0 ip=xxx location=bom protocol=http2
```
**No "Unable to reach the origin service" errors!**
## Test the Connection
### From outside Docker (your current working test):
```bash
curl 172.18.0.1:9090
# Should return: Monaco Code Execution Server v1.0.0
```
### From the tunnel (once running):
```bash
# Test via the public URL
curl https://api.ishikabhoyar.tech
```
## Troubleshooting
### If Solution 1 still doesn't work:
1. Check if Docker bridge IP changed:
```bash
docker network inspect bridge | grep Gateway
```
2. Update `config.tunnel-only.json` with the correct IP
### If Solution 2 doesn't work:
- Host network mode may not be fully supported on your OS
- Fall back to Solution 1 with correct bridge IP
### Check tunnel logs:
```bash
docker-compose -f docker-compose.tunnel-only.yml logs -f
```
### Verify backend is accessible from Docker:
```bash
docker run --rm alpine/curl:latest curl http://172.18.0.1:9090
```
## Summary
**Current Status:** ✅ Config updated to use `172.18.0.1:9090`
**Next Step:** Rebuild and restart the tunnel:
```bash
docker-compose -f docker-compose.tunnel-only.yml down
docker-compose -f docker-compose.tunnel-only.yml up --build
```
The tunnel should now successfully connect to your backend! 🎉

View File

@@ -0,0 +1,69 @@
# Quick Start - Tunnel Only Mode
## What This Does
- Runs **only** the Cloudflare tunnel in Docker
- Your backend runs **outside Docker** on port 9090
- Tunnel forwards traffic from `api.ishikabhoyar.tech` to your local backend
## Quick Start
### Step 1: Start your backend on port 9090
```bash
PORT=9090 go run main.go
```
### Step 2: Start the tunnel
**Windows (PowerShell):**
```powershell
.\start-tunnel-only.ps1
```
**Linux/Mac:**
```bash
chmod +x start-tunnel-only.sh
./start-tunnel-only.sh
```
**Or manually:**
```bash
docker-compose -f docker-compose.tunnel-only.yml up --build
```
## Files Created
1. **Dockerfile.tunnel-only** - Lightweight Docker image with only cloudflared
2. **docker-compose.tunnel-only.yml** - Docker Compose config for tunnel only
3. **config.tunnel-only.json** - Cloudflare tunnel config pointing to port 9090
4. **start-tunnel-only.ps1** - PowerShell helper script
5. **start-tunnel-only.sh** - Bash helper script
6. **README.tunnel-only.md** - Detailed documentation
## Test It
1. Start backend: `PORT=9090 go run main.go`
2. Start tunnel: `docker-compose -f docker-compose.tunnel-only.yml up --build`
3. Test: `curl https://api.ishikabhoyar.tech`
## Stop
```bash
docker-compose -f docker-compose.tunnel-only.yml down
```
## Troubleshooting
**Backend not reachable?**
- Check backend is running: `curl http://localhost:9090`
- Check tunnel logs: `docker-compose -f docker-compose.tunnel-only.yml logs -f`
**Tunnel not connecting?**
- Verify credentials.json and cert.pem are valid
- Check Cloudflare dashboard
## Original Files (Unchanged)
The original tunnel setup files are still available:
- `Dockerfile.tunnel` - Backend + Tunnel in one container
- `docker-compose.tunnel.yml` - Original compose file
- These files still point to port 8080

175
new-backend/api/handler.go Normal file
View File

@@ -0,0 +1,175 @@
package api
import (
"encoding/json"
"log"
"net/http"
"time"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/ishikabhoyar/monaco/new-backend/executor"
"github.com/ishikabhoyar/monaco/new-backend/models"
)
// Handler manages all API routes
type Handler struct {
executor *executor.CodeExecutor
upgrader websocket.Upgrader
}
// NewHandler creates a new API handler
func NewHandler(executor *executor.CodeExecutor) *Handler {
return &Handler{
executor: executor,
upgrader: websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true // Allow all origins for development
},
HandshakeTimeout: 10 * time.Second,
},
}
}
// RegisterRoutes sets up all API routes
func (h *Handler) RegisterRoutes(router *mux.Router) {
// Code execution endpoints
router.HandleFunc("/api/submit", h.SubmitCodeHandler).Methods("POST")
router.HandleFunc("/api/status/{id}", h.StatusHandler).Methods("GET")
router.HandleFunc("/api/result/{id}", h.ResultHandler).Methods("GET")
// WebSocket endpoint for real-time output
router.HandleFunc("/api/ws/terminal/{id}", h.TerminalWebSocketHandler)
// Language support endpoint
router.HandleFunc("/api/languages", h.SupportedLanguagesHandler).Methods("GET")
// Health check
router.HandleFunc("/api/health", h.HealthCheckHandler).Methods("GET")
}
// SubmitCodeHandler handles code submission requests
func (h *Handler) SubmitCodeHandler(w http.ResponseWriter, r *http.Request) {
// Parse request
var submission models.CodeSubmission
if err := json.NewDecoder(r.Body).Decode(&submission); err != nil {
http.Error(w, "Invalid request format", http.StatusBadRequest)
return
}
// Validate request
if submission.Code == "" {
http.Error(w, "Code cannot be empty", http.StatusBadRequest)
return
}
if submission.Language == "" {
http.Error(w, "Language must be specified", http.StatusBadRequest)
return
}
// Generate ID if not provided
if submission.ID == "" {
submission.ID = uuid.New().String()
}
// Submit code for execution
id := h.executor.SubmitCode(&submission)
// Return response
response := models.SubmissionResponse{
ID: id,
Status: "queued",
Message: "Code submission accepted and queued for execution",
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
// StatusHandler returns the current status of a code execution
func (h *Handler) StatusHandler(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
id := params["id"]
submission, exists := h.executor.GetSubmission(id)
if !exists {
http.Error(w, "Submission not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"id": submission.ID,
"status": submission.Status,
})
}
// ResultHandler returns the complete result of a code execution
func (h *Handler) ResultHandler(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
id := params["id"]
submission, exists := h.executor.GetSubmission(id)
if !exists {
http.Error(w, "Submission not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(submission)
}
// TerminalWebSocketHandler handles WebSocket connections for real-time output
func (h *Handler) TerminalWebSocketHandler(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
id := params["id"]
// Check if submission exists
if _, exists := h.executor.GetSubmission(id); !exists {
http.Error(w, "Submission not found", http.StatusNotFound)
return
}
// Upgrade connection to WebSocket
conn, err := h.upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("WebSocket upgrade failed: %v", err)
return
}
log.Printf("WebSocket connection established for submission %s", id)
// Register connection
h.executor.RegisterTerminalConnection(id, conn)
// Connection will be handled by the executor
}
// SupportedLanguagesHandler returns a list of supported languages
func (h *Handler) SupportedLanguagesHandler(w http.ResponseWriter, r *http.Request) {
// This is a placeholder - in a real implementation, you'd get this from the config
languages := []map[string]string{
{"id": "python", "name": "Python", "version": "3.9"},
{"id": "java", "name": "Java", "version": "11"},
{"id": "c", "name": "C", "version": "GCC 10.2"},
{"id": "cpp", "name": "C++", "version": "GCC 10.2"},
{"id": "javascript", "name": "JavaScript", "version": "Node.js 16"},
{"id": "golang", "name": "Go", "version": "1.19"},
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(languages)
}
// HealthCheckHandler provides a simple health check endpoint
func (h *Handler) HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"status": "ok",
"time": time.Now().Format(time.RFC3339),
})
}

15
new-backend/config.json Normal file
View File

@@ -0,0 +1,15 @@
{
"tunnel": "5d2682ef-0b5b-47e5-b0fa-ad48968ce016",
"credentials-file": "/etc/cloudflared/credentials.json",
"ingress": [
{
"hostname": "api.ishikabhoyar.tech",
"service": "http://host.docker.internal:8080"
},
{
"service": "http_status:404"
}
],
"protocol": "http2",
"loglevel": "info"
}

View File

@@ -0,0 +1,13 @@
{
"tunnel": "monaco-backend-tunnel",
"credentials-file": "/etc/cloudflared/cert.pem",
"ingress": [
{
"hostname": "api.ishikabhoyar.tech",
"service": "http://localhost:8080"
},
{
"service": "http_status:404"
}
]
}

View File

@@ -0,0 +1,15 @@
{
"tunnel": "5d2682ef-0b5b-47e5-b0fa-ad48968ce016",
"credentials-file": "/etc/cloudflared/credentials.json",
"ingress": [
{
"hostname": "api.ishikabhoyar.tech",
"service": "http://localhost:9090"
},
{
"service": "http_status:404"
}
],
"protocol": "http2",
"loglevel": "info"
}

View File

@@ -0,0 +1,15 @@
{
"tunnel": "5d2682ef-0b5b-47e5-b0fa-ad48968ce016",
"credentials-file": "/etc/cloudflared/credentials.json",
"ingress": [
{
"hostname": "api.ishikabhoyar.tech",
"service": "http://172.18.0.1:9090"
},
{
"service": "http_status:404"
}
],
"protocol": "http2",
"loglevel": "info"
}

View File

@@ -0,0 +1,168 @@
package config
import (
"os"
"strconv"
"time"
)
// Config holds all configuration for the application
type Config struct {
Server ServerConfig
Executor ExecutorConfig
Languages map[string]LanguageConfig
Sandbox SandboxConfig
}
// ServerConfig holds server-related configurations
type ServerConfig struct {
Port string
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
}
// ExecutorConfig holds executor-related configurations
type ExecutorConfig struct {
ConcurrentExecutions int
QueueCapacity int
DefaultTimeout time.Duration
}
// LanguageConfig holds language-specific configurations
type LanguageConfig struct {
Name string
Image string
MemoryLimit string
CPULimit string
TimeoutSec int
CompileCmd []string
RunCmd []string
FileExt string
VersionCmd []string
}
// SandboxConfig holds sandbox-related configurations
type SandboxConfig struct {
NetworkDisabled bool
MemorySwapLimit string
PidsLimit int64
}
// GetConfig returns the application configuration
func GetConfig() *Config {
return &Config{
Server: ServerConfig{
Port: getEnv("PORT", "8080"),
ReadTimeout: time.Duration(getEnvAsInt("READ_TIMEOUT", 15)) * time.Second,
WriteTimeout: time.Duration(getEnvAsInt("WRITE_TIMEOUT", 15)) * time.Second,
IdleTimeout: time.Duration(getEnvAsInt("IDLE_TIMEOUT", 90)) * time.Second,
},
Executor: ExecutorConfig{
ConcurrentExecutions: getEnvAsInt("CONCURRENT_EXECUTIONS", 100),
QueueCapacity: getEnvAsInt("QUEUE_CAPACITY", 1000),
DefaultTimeout: time.Duration(getEnvAsInt("DEFAULT_TIMEOUT", 30)) * time.Second,
},
Languages: getLanguageConfigs(),
Sandbox: SandboxConfig{
NetworkDisabled: getEnvAsBool("SANDBOX_NETWORK_DISABLED", true),
MemorySwapLimit: getEnv("SANDBOX_MEMORY_SWAP_LIMIT", "0"),
PidsLimit: int64(getEnvAsInt("SANDBOX_PIDS_LIMIT", 50)),
},
}
}
// getLanguageConfigs returns configurations for all supported languages
func getLanguageConfigs() map[string]LanguageConfig {
return map[string]LanguageConfig{
"python": {
Name: "Python",
Image: "python:3.9-slim",
MemoryLimit: "100m",
CPULimit: "0.1",
TimeoutSec: 90,
RunCmd: []string{"python", "-c"},
FileExt: ".py",
VersionCmd: []string{"python", "--version"},
},
"java": {
Name: "Java",
Image: "eclipse-temurin:11-jdk",
MemoryLimit: "400m",
CPULimit: "0.5",
TimeoutSec: 100,
CompileCmd: []string{"javac"},
RunCmd: []string{"java"},
FileExt: ".java",
VersionCmd: []string{"java", "-version"},
},
"c": {
Name: "C",
Image: "gcc:latest",
MemoryLimit: "100m",
CPULimit: "0.1",
TimeoutSec: 90,
CompileCmd: []string{"gcc", "-o", "program"},
RunCmd: []string{"./program"},
FileExt: ".c",
VersionCmd: []string{"gcc", "--version"},
},
"cpp": {
Name: "C++",
Image: "gcc:latest",
MemoryLimit: "100m",
CPULimit: "0.1",
TimeoutSec: 90,
CompileCmd: []string{"g++", "-o", "program"},
RunCmd: []string{"./program"},
FileExt: ".cpp",
VersionCmd: []string{"g++", "--version"},
},
"javascript": {
Name: "JavaScript",
Image: "node:16-alpine",
MemoryLimit: "100m",
CPULimit: "0.1",
TimeoutSec: 90,
RunCmd: []string{"node", "-e"},
FileExt: ".js",
VersionCmd: []string{"node", "--version"},
},
"golang": {
Name: "Go",
Image: "golang:1.19-alpine",
MemoryLimit: "100m",
CPULimit: "0.1",
TimeoutSec: 90,
CompileCmd: []string{"go", "build", "-o", "program"},
RunCmd: []string{"./program"},
FileExt: ".go",
VersionCmd: []string{"go", "version"},
},
}
}
// Helper functions to get environment variables with defaults
func getEnv(key, defaultValue string) string {
value := os.Getenv(key)
if value == "" {
return defaultValue
}
return value
}
func getEnvAsInt(key string, defaultValue int) int {
valueStr := getEnv(key, "")
if value, err := strconv.Atoi(valueStr); err == nil {
return value
}
return defaultValue
}
func getEnvAsBool(key string, defaultValue bool) bool {
valueStr := getEnv(key, "")
if value, err := strconv.ParseBool(valueStr); err == nil {
return value
}
return defaultValue
}

View File

@@ -0,0 +1 @@
{"AccountTag":"453afb9373a00a55876e6127cf0efd97","TunnelSecret":"02VClcBt+1nxxu8ioUzw/UizXtKKh4X7UUpneVbfB/Y=","TunnelID":"5d2682ef-0b5b-47e5-b0fa-ad48968ce016"}

View File

@@ -0,0 +1,11 @@
services:
tunnel:
build:
context: .
dockerfile: Dockerfile.tunnel-only
restart: unless-stopped
# Use host network mode to directly access localhost:9090
network_mode: "host"
environment:
- TUNNEL_ORIGIN_CERT=/etc/cloudflared/cert.pem
- NO_AUTOUPDATE=true

View File

@@ -0,0 +1,18 @@
services:
tunnel:
build:
context: .
dockerfile: Dockerfile.tunnel-only
restart: unless-stopped
extra_hosts:
- "host.docker.internal:host-gateway"
environment:
- TUNNEL_ORIGIN_CERT=/etc/cloudflared/cert.pem
- NO_AUTOUPDATE=true
# Isolated network
networks:
- monaco-tunnel-network
networks:
monaco-tunnel-network:
driver: bridge

View File

@@ -0,0 +1,30 @@
services:
backend:
build:
context: .
dockerfile: Dockerfile.tunnel
restart: unless-stopped
extra_hosts:
- "host.docker.internal:host-gateway"
volumes:
- //var/run/docker.sock:/var/run/docker.sock
# No need to expose ports - traffic comes through the tunnel
# ports:
# - "127.0.0.1:8080:8080"
environment:
- PORT=8080
- CONCURRENT_EXECUTIONS=5
- QUEUE_CAPACITY=100
- DEFAULT_TIMEOUT=30
- SANDBOX_NETWORK_DISABLED=true
- SANDBOX_PIDS_LIMIT=50
# Define cloudflared environment variables
- TUNNEL_ORIGIN_CERT=/etc/cloudflared/cert.pem
- NO_AUTOUPDATE=true
# Isolated network to prevent conflicts with host cloudflared
networks:
- monaco-backend-network
networks:
monaco-backend-network:
driver: bridge

View File

@@ -0,0 +1,654 @@
package executor
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"github.com/ishikabhoyar/monaco/new-backend/config"
"github.com/ishikabhoyar/monaco/new-backend/models"
)
// SafeWebSocketConn wraps a WebSocket connection with a mutex for thread-safe writes
type SafeWebSocketConn struct {
conn *websocket.Conn
mutex sync.Mutex
}
// WriteJSON writes JSON to the WebSocket connection in a thread-safe manner
func (s *SafeWebSocketConn) WriteJSON(v interface{}) error {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.conn.WriteJSON(v)
}
// CodeExecutor handles code execution for all languages
type CodeExecutor struct {
config *config.Config
execQueue chan *models.CodeSubmission
submissions map[string]*models.CodeSubmission
submissionsMutex sync.RWMutex
terminalConnections map[string][]*SafeWebSocketConn
terminalMutex sync.RWMutex
inputChannels map[string]chan string
inputMutex sync.RWMutex
}
// NewCodeExecutor creates a new code executor with specified capacity
func NewCodeExecutor(cfg *config.Config) *CodeExecutor {
executor := &CodeExecutor{
config: cfg,
execQueue: make(chan *models.CodeSubmission, cfg.Executor.QueueCapacity),
submissions: make(map[string]*models.CodeSubmission),
terminalConnections: make(map[string][]*SafeWebSocketConn),
inputChannels: make(map[string]chan string),
}
// Start worker goroutines
for i := 0; i < cfg.Executor.ConcurrentExecutions; i++ {
go executor.worker(i)
}
log.Printf("Started %d code execution workers", cfg.Executor.ConcurrentExecutions)
return executor
}
// SubmitCode adds a code submission to the execution queue
func (e *CodeExecutor) SubmitCode(submission *models.CodeSubmission) string {
// Generate ID if not provided
if submission.ID == "" {
submission.ID = uuid.New().String()
}
submission.Status = "queued"
submission.QueuedAt = time.Now()
// Store submission
e.submissionsMutex.Lock()
e.submissions[submission.ID] = submission
e.submissionsMutex.Unlock()
// Send to execution queue
e.execQueue <- submission
log.Printf("Submission queued: %s, language: %s", submission.ID, submission.Language)
return submission.ID
}
// GetSubmission returns a submission by ID
func (e *CodeExecutor) GetSubmission(id string) (*models.CodeSubmission, bool) {
e.submissionsMutex.RLock()
defer e.submissionsMutex.RUnlock()
submission, exists := e.submissions[id]
return submission, exists
}
// RegisterTerminalConnection registers a WebSocket connection for streaming output
func (e *CodeExecutor) RegisterTerminalConnection(submissionID string, conn *websocket.Conn) {
e.terminalMutex.Lock()
defer e.terminalMutex.Unlock()
safeConn := &SafeWebSocketConn{conn: conn}
e.terminalConnections[submissionID] = append(e.terminalConnections[submissionID], safeConn)
log.Printf("WebSocket connection registered for submission %s (total: %d)",
submissionID, len(e.terminalConnections[submissionID]))
// Set up a reader to handle input from WebSocket
go e.handleTerminalInput(submissionID, conn)
}
// UnregisterTerminalConnection removes a WebSocket connection
func (e *CodeExecutor) UnregisterTerminalConnection(submissionID string, conn *websocket.Conn) {
e.terminalMutex.Lock()
defer e.terminalMutex.Unlock()
connections := e.terminalConnections[submissionID]
for i, c := range connections {
if c.conn == conn {
// Remove the connection
e.terminalConnections[submissionID] = append(connections[:i], connections[i+1:]...)
break
}
}
// Clean up if no more connections
if len(e.terminalConnections[submissionID]) == 0 {
delete(e.terminalConnections, submissionID)
}
log.Printf("WebSocket connection unregistered for submission %s", submissionID)
}
// handleTerminalInput reads input from the WebSocket and forwards it to the running process
func (e *CodeExecutor) handleTerminalInput(submissionID string, conn *websocket.Conn) {
for {
_, message, err := conn.ReadMessage()
if err != nil {
log.Printf("Error reading WebSocket message: %v", err)
break
}
// Try to parse the message as JSON first
var inputMessage struct {
Type string `json:"type"`
Content string `json:"content"`
}
inputText := string(message)
if err := json.Unmarshal(message, &inputMessage); err == nil && inputMessage.Type == "input" {
// It's a structured input message
inputText = inputMessage.Content
}
// Now get the input channel
e.inputMutex.Lock()
inputChan, exists := e.inputChannels[submissionID]
e.inputMutex.Unlock()
if exists {
select {
case inputChan <- inputText:
log.Printf("Input sent to process: %s", inputText)
default:
log.Printf("Failed to send input: channel full or closed")
}
} else {
log.Printf("No input channel for submission %s", submissionID)
}
}
// When connection is closed, unregister it
e.UnregisterTerminalConnection(submissionID, conn)
}
// sendToTerminals sends output to all registered WebSocket connections
func (e *CodeExecutor) sendToTerminals(submissionID string, message models.WebSocketMessage) {
e.terminalMutex.RLock()
connections := e.terminalConnections[submissionID]
e.terminalMutex.RUnlock()
if len(connections) == 0 {
return
}
for _, conn := range connections {
err := conn.WriteJSON(message)
if err != nil {
log.Printf("WebSocket write error: %v", err)
// Consider unregistering the connection on error
}
}
}
// worker processes code execution jobs from the queue
func (e *CodeExecutor) worker(id int) {
log.Printf("Worker %d started", id)
for submission := range e.execQueue {
log.Printf("Worker %d processing submission %s (%s)", id, submission.ID, submission.Language)
// Update status to running
submission.Status = "running"
submission.StartedAt = time.Now()
e.sendToTerminals(submission.ID, models.NewStatusMessage("running", "", ""))
// Execute the code according to language
e.executeCode(submission)
// Update completion time
submission.CompletedAt = time.Now()
executionTime := submission.CompletedAt.Sub(submission.StartedAt).Seconds()
submission.ExecutionTime = executionTime
// Send completion status
e.sendToTerminals(submission.ID, models.NewStatusMessage(submission.Status, "", ""))
// Send a notification that terminal will close soon
e.sendToTerminals(submission.ID, models.NewSystemMessage("Connection will close in 5 seconds"))
// Add delay to keep the connection open longer
time.Sleep(5 * time.Second)
log.Printf("Worker %d completed submission %s in %.2f seconds", id, submission.ID, executionTime)
}
}
// executeCode orchestrates the execution of code for different languages
func (e *CodeExecutor) executeCode(submission *models.CodeSubmission) {
langConfig, exists := e.config.Languages[strings.ToLower(submission.Language)]
if !exists {
submission.Status = "failed"
submission.Output = "Unsupported language: " + submission.Language
return
}
// Create a temporary directory for this submission
tempDir, err := os.MkdirTemp("", fmt.Sprintf("%s-code-%s-", submission.Language, submission.ID))
if err != nil {
submission.Status = "failed"
submission.Output = "Failed to create execution environment: " + err.Error()
return
}
defer os.RemoveAll(tempDir)
// Choose execution strategy based on language
switch strings.ToLower(submission.Language) {
case "python":
e.executePython(submission, tempDir, langConfig)
case "java":
e.executeJava(submission, tempDir, langConfig)
case "c":
e.executeC(submission, tempDir, langConfig)
case "cpp":
e.executeCpp(submission, tempDir, langConfig)
case "javascript":
e.executeJavaScript(submission, tempDir, langConfig)
case "golang":
e.executeGolang(submission, tempDir, langConfig)
default:
submission.Status = "failed"
submission.Output = "Unsupported language: " + submission.Language
}
}
// executePython executes Python code
func (e *CodeExecutor) executePython(submission *models.CodeSubmission, tempDir string, langConfig config.LanguageConfig) {
// Write code to file
codeFile := filepath.Join(tempDir, "code"+langConfig.FileExt)
if err := os.WriteFile(codeFile, []byte(submission.Code), 0644); err != nil {
submission.Status = "failed"
submission.Output = "Failed to write code file: " + err.Error()
return
}
// Setup Docker run command with unbuffered Python output
cmd := exec.Command(
"docker", "run", "--rm", "-i",
"--network=none",
"--memory="+langConfig.MemoryLimit,
"--cpu-quota="+fmt.Sprintf("%d", int(float64(100000)*0.1)), // 10% CPU
"--pids-limit=20",
"-v", tempDir+":/code",
"-e", "PYTHONUNBUFFERED=1", // Force Python to be unbuffered
langConfig.Image,
"python", "-u", "/code/code.py", // Add -u flag for unbuffered I/O
)
// Execute with increased timeout for interactive programs
e.executeWithIO(cmd, submission, time.Duration(langConfig.TimeoutSec)*time.Second)
}
// executeJava executes Java code
func (e *CodeExecutor) executeJava(submission *models.CodeSubmission, tempDir string, langConfig config.LanguageConfig) {
// Extract class name from code
className := extractJavaClassName(submission.Code)
// Write code to file
codeFile := filepath.Join(tempDir, className+langConfig.FileExt)
if err := os.WriteFile(codeFile, []byte(submission.Code), 0644); err != nil {
submission.Status = "failed"
submission.Output = "Failed to write code file: " + err.Error()
return
}
// Compile Java code
compileCmd := exec.Command(
"docker", "run", "--rm",
"-v", tempDir+":/code",
langConfig.Image,
"javac", "/code/"+className+".java",
)
compileOutput, compileErr := compileCmd.CombinedOutput()
if compileErr != nil {
submission.Status = "failed"
submission.Output = "Compilation error:\n" + string(compileOutput)
e.sendToTerminals(submission.ID, models.NewOutputMessage(string(compileOutput), true))
return
}
// Setup Docker run command for execution
cmd := exec.Command(
"docker", "run", "--rm", "-i",
"--network=none",
"--memory="+langConfig.MemoryLimit,
"--cpu-quota="+fmt.Sprintf("%d", int(float64(100000)*0.5)), // 50% CPU
"--pids-limit=20",
"-v", tempDir+":/code",
langConfig.Image,
"java", "-XX:+TieredCompilation", "-XX:TieredStopAtLevel=1",
"-Xms64m", "-Xmx256m",
"-cp", "/code", className,
)
// Execute the code with input handling
e.executeWithIO(cmd, submission, time.Duration(langConfig.TimeoutSec)*time.Second)
}
// executeC executes C code
func (e *CodeExecutor) executeC(submission *models.CodeSubmission, tempDir string, langConfig config.LanguageConfig) {
// Write code to file exactly as submitted by user
codeFile := filepath.Join(tempDir, "code"+langConfig.FileExt)
if err := os.WriteFile(codeFile, []byte(submission.Code), 0644); err != nil {
submission.Status = "failed"
submission.Output = "Failed to write code file: " + err.Error()
return
}
// Compile C code
compileCmd := exec.Command(
"docker", "run", "--rm",
"-v", tempDir+":/code",
langConfig.Image,
"gcc", "-o", "/code/program", "/code/code.c",
)
compileOutput, compileErr := compileCmd.CombinedOutput()
if compileErr != nil {
submission.Status = "failed"
submission.Output = "Compilation error:\n" + string(compileOutput)
e.sendToTerminals(submission.ID, models.NewOutputMessage(string(compileOutput), true))
return
}
// Setup Docker run command with stdbuf to force line buffering
cmd := exec.Command(
"docker", "run", "--rm", "-i",
"--network=none",
"--memory="+langConfig.MemoryLimit,
"--cpu-quota="+fmt.Sprintf("%d", int(float64(100000)*0.1)), // 10% CPU
"--pids-limit=20",
"-v", tempDir+":/code",
langConfig.Image,
"stdbuf", "-oL", "-eL", "/code/program",
)
// Execute the code with input handling
e.executeWithIO(cmd, submission, time.Duration(langConfig.TimeoutSec)*time.Second)
}
// executeCpp executes C++ code
func (e *CodeExecutor) executeCpp(submission *models.CodeSubmission, tempDir string, langConfig config.LanguageConfig) {
// Write code to file
codeFile := filepath.Join(tempDir, "code"+langConfig.FileExt)
if err := os.WriteFile(codeFile, []byte(submission.Code), 0644); err != nil {
submission.Status = "failed"
submission.Output = "Failed to write code file: " + err.Error()
return
}
// Compile C++ code
compileCmd := exec.Command(
"docker", "run", "--rm",
"-v", tempDir+":/code",
langConfig.Image,
"g++", "-o", "/code/program", "/code/code.cpp",
)
compileOutput, compileErr := compileCmd.CombinedOutput()
if compileErr != nil {
submission.Status = "failed"
submission.Output = "Compilation error:\n" + string(compileOutput)
e.sendToTerminals(submission.ID, models.NewOutputMessage(string(compileOutput), true))
return
}
// Setup Docker run command with stdbuf to force line buffering
cmd := exec.Command(
"docker", "run", "--rm", "-i",
"--network=none",
"--memory="+langConfig.MemoryLimit,
"--cpu-quota="+fmt.Sprintf("%d", int(float64(100000)*0.1)), // 10% CPU
"--pids-limit=20",
"-v", tempDir+":/code",
langConfig.Image,
"stdbuf", "-oL", "-eL", "/code/program",
)
// Execute the code with input handling
e.executeWithIO(cmd, submission, time.Duration(langConfig.TimeoutSec)*time.Second)
}
// executeJavaScript executes JavaScript code
func (e *CodeExecutor) executeJavaScript(submission *models.CodeSubmission, tempDir string, langConfig config.LanguageConfig) {
// Write code to file
codeFile := filepath.Join(tempDir, "code"+langConfig.FileExt)
if err := os.WriteFile(codeFile, []byte(submission.Code), 0644); err != nil {
submission.Status = "failed"
submission.Output = "Failed to write code file: " + err.Error()
return
}
// Setup Docker run command
cmd := exec.Command(
"docker", "run", "--rm", "-i",
"--network=none",
"--memory="+langConfig.MemoryLimit,
"--cpu-quota="+fmt.Sprintf("%d", int(float64(100000)*0.1)), // 10% CPU
"--pids-limit=20",
"-v", tempDir+":/code",
langConfig.Image,
"node", "/code/code.js",
)
// Execute the code with input handling
e.executeWithIO(cmd, submission, time.Duration(langConfig.TimeoutSec)*time.Second)
}
// executeGolang executes Go code
func (e *CodeExecutor) executeGolang(submission *models.CodeSubmission, tempDir string, langConfig config.LanguageConfig) {
// Write code to file
codeFile := filepath.Join(tempDir, "code"+langConfig.FileExt)
if err := os.WriteFile(codeFile, []byte(submission.Code), 0644); err != nil {
submission.Status = "failed"
submission.Output = "Failed to write code file: " + err.Error()
return
}
// Setup Docker run command to compile and run in one step
cmd := exec.Command(
"docker", "run", "--rm", "-i",
"--network=none",
"--memory="+langConfig.MemoryLimit,
"--cpu-quota="+fmt.Sprintf("%d", int(float64(100000)*0.1)), // 10% CPU
"--pids-limit=20",
"-v", tempDir+":/code",
"-w", "/code",
langConfig.Image,
"go", "run", "/code/code.go",
)
// Execute the code with input handling
e.executeWithIO(cmd, submission, time.Duration(langConfig.TimeoutSec)*time.Second)
}
// executeWithIO runs a command with input/output handling through WebSockets
func (e *CodeExecutor) executeWithIO(cmd *exec.Cmd, submission *models.CodeSubmission, timeout time.Duration) {
// Create pipes for stdin, stdout and stderr
stdin, err := cmd.StdinPipe()
if err != nil {
submission.Status = "failed"
submission.Output = "Failed to create stdin pipe: " + err.Error()
return
}
stdout, err := cmd.StdoutPipe()
if err != nil {
submission.Status = "failed"
submission.Output = "Failed to create stdout pipe: " + err.Error()
return
}
stderr, err := cmd.StderrPipe()
if err != nil {
submission.Status = "failed"
submission.Output = "Failed to create stderr pipe: " + err.Error()
return
}
// Create an input channel for this submission
inputChan := make(chan string, 10)
e.inputMutex.Lock()
e.inputChannels[submission.ID] = inputChan
e.inputMutex.Unlock()
// Clean up when done
defer func() {
e.inputMutex.Lock()
delete(e.inputChannels, submission.ID)
e.inputMutex.Unlock()
close(inputChan)
}()
// Start the command
if err := cmd.Start(); err != nil {
submission.Status = "failed"
submission.Output = "Failed to start process: " + err.Error()
return
}
// Output buffer to collect all output
var outputBuffer bytes.Buffer
// Send initial input if provided
if submission.Input != "" {
io.WriteString(stdin, submission.Input+"\n")
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
// Handle stdout in a goroutine
go func() {
buffer := make([]byte, 1024)
for {
n, err := stdout.Read(buffer)
if n > 0 {
data := buffer[:n]
outputBuffer.Write(data)
// Send real-time output to terminals
e.sendToTerminals(submission.ID, models.NewOutputMessage(string(data), false))
}
if err != nil {
if err != io.EOF {
log.Printf("Stdout read error: %v", err)
}
break
}
}
}()
// Handle stderr in a goroutine
go func() {
buffer := make([]byte, 1024)
for {
n, err := stderr.Read(buffer)
if n > 0 {
data := buffer[:n]
outputBuffer.Write(data)
// Send real-time error output to terminals
e.sendToTerminals(submission.ID, models.NewOutputMessage(string(data), true))
}
if err != nil {
if err != io.EOF {
log.Printf("Stderr read error: %v", err)
}
break
}
}
}()
// Listen for input from WebSocket
go func() {
for {
select {
case input, ok := <-inputChan:
if !ok {
return
}
log.Printf("Received input from WebSocket: %s", input)
// Write input with a single newline - don't add extra newlines
_, err := stdin.Write([]byte(input + "\n"))
if err != nil {
log.Printf("Error writing to stdin: %v", err)
e.sendToTerminals(submission.ID, models.NewErrorMessage("input_error", "Failed to send input to process"))
}
case <-ctx.Done():
return
}
}
}()
// Wait for command to complete or timeout
done := make(chan error)
go func() {
done <- cmd.Wait()
}()
// Wait for completion or timeout
select {
case <-ctx.Done():
// Process timed out
if ctx.Err() == context.DeadlineExceeded {
log.Printf("Process timed out for submission %s", submission.ID)
submission.Status = "failed"
submission.Output = outputBuffer.String() + "\nExecution timed out after " + timeout.String()
e.sendToTerminals(submission.ID, models.NewErrorMessage("timeout", "Execution timed out after "+timeout.String()))
// Attempt to kill the process
if err := cmd.Process.Kill(); err != nil {
log.Printf("Failed to kill process: %v", err)
}
}
case err := <-done:
// Process completed
if err != nil {
log.Printf("Process error: %v", err)
submission.Status = "failed"
// Don't overwrite output, as stderr has already been captured
} else {
submission.Status = "completed"
}
}
// Store the complete output
submission.Output = outputBuffer.String()
}
// Helper function to extract Java class name
func extractJavaClassName(code string) string {
// Default class name as fallback
defaultClass := "Solution"
// Look for public class
re := regexp.MustCompile(`public\s+class\s+(\w+)`)
matches := re.FindStringSubmatch(code)
if len(matches) > 1 {
return matches[1]
}
// Look for any class if no public class
re = regexp.MustCompile(`class\s+(\w+)`)
matches = re.FindStringSubmatch(code)
if len(matches) > 1 {
return matches[1]
}
return defaultClass
}

10
new-backend/go.mod Normal file
View File

@@ -0,0 +1,10 @@
module github.com/ishikabhoyar/monaco/new-backend
go 1.19
require (
github.com/google/uuid v1.3.0
github.com/gorilla/mux v1.8.0
github.com/gorilla/websocket v1.5.0
github.com/rs/cors v1.8.3
)

8
new-backend/go.sum Normal file
View File

@@ -0,0 +1,8 @@
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo=
github.com/rs/cors v1.8.3/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=

Some files were not shown because too many files have changed in this diff Show More