Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-webmvc")

compileOnly("org.projectlombok:lombok:1.18.46")
annotationProcessor("org.projectlombok:lombok:1.18.46")

testCompileOnly("org.projectlombok:lombok:1.18.46")
testAnnotationProcessor("org.projectlombok:lombok:1.18.46")


runtimeOnly("com.h2database:h2")
testImplementation("org.springframework.boot:spring-boot-starter-data-jpa-test")
testImplementation("org.springframework.boot:spring-boot-starter-security-test")
Expand Down
4 changes: 4 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@ services:
ports:
- "8080:8080"

runner:
build: ./runner

frontend:
build: ./frontend
ports:
- "80:80"
depends_on:
- backend
- runner
5 changes: 5 additions & 0 deletions frontend/nginx.conf
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ server {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

location /runner/ {
proxy_pass http://runner:5000/;
}


location / {
try_files $uri /index.html;
}
Expand Down
80 changes: 75 additions & 5 deletions frontend/src/pages/ChallengePage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,16 @@ import { useParams, Link } from 'react-router-dom'
import Editor from '@monaco-editor/react'
import api from '../api/axios'

function sortKeys(val) {
if (Array.isArray(val)) return val.map(sortKeys)
if (val && typeof val === 'object') {
return Object.fromEntries(Object.keys(val).sort().map(k => [k, sortKeys(val[k])]))
}
return val
}

function deepEqual(a, b) {
return JSON.stringify(a) === JSON.stringify(b)
return JSON.stringify(sortKeys(a)) === JSON.stringify(sortKeys(b))
}

function sortBySource(arr) {
Expand Down Expand Up @@ -56,6 +64,17 @@ export default function ChallengePage() {
const [running, setRunning] = useState(false)
const [results, setResults] = useState(null)
const codeRef = useRef('')
const [language, setLanguage] = useState('javascript')
const availableLanguages = challenge ? ['javascript',
...challenge.variants.map(v => v.language)]
: ['javascript']
useEffect(() => {
if (!challenge) return
const starterCode = language === 'javascript'
? challenge.starterCode
: challenge.variants.find(v => v.language === language)?.starterCode ?? ''
codeRef.current = starterCode
}, [language, challenge])

useEffect(() => {
api.get(`/challenges/${id}`)
Expand All @@ -77,7 +96,27 @@ export default function ChallengePage() {
for (const tc of visibleTests) {
const input = JSON.parse(tc.inputJson)
const expected = JSON.parse(tc.expectedJson)
const response = await runWorker(challenge.harnessCode, codeRef.current, input)
let response

if (language === 'javascript') {
response = await runWorker(challenge.harnessCode, codeRef.current, input)
} else {
const variant = challenge.variants.find(v => v.language === language)
try {
const res = await fetch('/runner/run', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
code: codeRef.current,
input,
harnessTemplate: variant.harnessTemplate,
}),
})
response = await res.json()
} catch (err) {
response = { ok: false, error: err.message }
}
}

if (!response.ok) {
testResults.push({ description: tc.description, pass: false, actual: null, expected, error: response.error })
Expand All @@ -97,7 +136,7 @@ export default function ChallengePage() {
code: codeRef.current,
status: 'PASS',
testResults: JSON.stringify(testResults),
}).catch(() => {})
}).catch(() => { })
}
}

Expand Down Expand Up @@ -172,11 +211,42 @@ export default function ChallengePage() {

{/* Right column */}
<div style={{ width: '40%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>

<div style={{
padding: '8px 16px',
borderBottom: '1px solid #2d3748', display: 'flex', gap: 8
}}>
{availableLanguages.map(lang => (
<button
key={lang}
onClick={() => setLanguage(lang)}
style={{
padding: 'rpx 12px',
fontSize: 12,
background: language === lang ?
'#3182ce' : 'transparent',
color: language === lang ? '#fff' : '#718096',
border: '1px solid #2d3748',
borderRadius: 4,
cursor: 'pointer',
}}
>
{lang === 'javascript' ? 'JavaScript' : 'Python'}
</button>
))}
</div>


<div style={{ flex: 1, minHeight: 0 }}>
<Editor
key={language}
height="100%"
defaultLanguage="javascript"
defaultValue={challenge.starterCode}
defaultLanguage={language}
defaultValue={
language === 'javascript'
? challenge.starterCode
: challenge.variants.find(v => v.language === language)?.starterCode ?? ''
}
theme="vs-dark"
onChange={value => { codeRef.current = value ?? '' }}
options={{
Expand Down
7 changes: 7 additions & 0 deletions runner/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
EXPOSE 5000
CMD ["python", "app.py"]
45 changes: 45 additions & 0 deletions runner/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import json
import os
import subprocess
import tempfile
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/run', methods=['POST'])
def run_code():
data = request.get_json()
code = data.get('code', '')
input_data = data.get('input', {})
harness_template = data.get('harnessTemplate', '')

script = harness_template.replace('{USER_CODE}', code)

tmp_path = None
try:
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False, dir='/tmp') as f:
f.write(script)
tmp_path = f.name

result = subprocess.run(['python3', tmp_path],
input=json.dumps(input_data),
capture_output=True, text=True,
timeout=5, cwd='/tmp',)

if result.returncode != 0:
return jsonify({'ok': False, 'error': result.stderr.strip()})

return jsonify(json.loads(result.stdout))

except subprocess.TimeoutExpired:
return jsonify({'ok': False, 'error': 'Timeout (5s)'})
except json.JSONDecodeError:
return jsonify({'ok': False, 'error': 'Runner output was not valid JSON'})
except Exception as e:
return jsonify({'ok': False, 'error': str(e)})
finally:
if tmp_path and os.path.exists(tmp_path):
os.unlink(tmp_path)

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
1 change: 1 addition & 0 deletions runner/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
flask==3.1.0
79 changes: 72 additions & 7 deletions src/main/java/no/hvl/schemalab/DataSeeder.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,67 @@
import no.hvl.schemalab.model.*;
import no.hvl.schemalab.repository.AppUserRepository;
import no.hvl.schemalab.repository.ChallengeRepository;
import no.hvl.schemalab.repository.ChallengeVariantRepository;

import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import lombok.Data;

import java.util.List;

@Component
@Data
public class DataSeeder implements CommandLineRunner {

private final ChallengeRepository challengeRepository;
private final ChallengeVariantRepository challengeVariantRepository;
private final AppUserRepository appUserRepository;
private final PasswordEncoder passwordEncoder;

public DataSeeder(ChallengeRepository challengeRepository,
AppUserRepository appUserRepository,
PasswordEncoder passwordEncoder) {
this.challengeRepository = challengeRepository;
this.appUserRepository = appUserRepository;
this.passwordEncoder = passwordEncoder;
}
private final String MATCHING_HARNESS_PY = "import json, sys\n" + //
"input_data = json.loads(sys.stdin.read())\n" + //
"\n" + //
"{USER_CODE}\n" + //
"\n" + //
"try:\n" + //
" result = match_schemas(input_data['schemaA'], input_data['schemaB'])\n" + //
" print(json.dumps({\"ok\": True, \"result\": result}))\n" + //
"except Exception as e:\n" + //
" print(json.dumps({\"ok\": False, \"error\": str(e)}))";

private final String VERSIONING_HARNESS_PY = "import json, sys\n" + //
"input_data = json.loads(sys.stdin.read())\n" + //
"\n" + //
"{USER_CODE}\n" + //
"\n" + //
"try:\n" + //
" result = migrate(input_data['record'])\n" + //
" print(json.dumps({\"ok\": True, \"result\": result}))\n" + //
"except Exception as e:\n" + //
" print(json.dumps({\"ok\": False, \"error\": str(e)}))";

private final String MATCHING_TEMPLATE_PY = """
#
# Match fields from schemaA to schemaB.
# @param {Object} schemaA - JSON Schema object
# @param {Object} schemaB - JSON Schema object
# @returns [<{source: string, target: string}>]
#
def match_schemas(schema_a, schema_b):
return []
""";

private final String VERSIONING_TEMPLATE_PY = """
#
# Migrate a record from schema v1 to schema v2.
# @param record - A v1 record instance
# @returns {Object} - A v2 record instance
#
def migrate(record):
return {}
""";;

@Override
public void run(String... args) {
Expand All @@ -37,6 +78,18 @@ public void run(String... args) {
}
}

/// HELPER METHODS

private void addPythonVariant(Challenge challenge, String starterCode, String harnessTemplate) {
ChallengeVariant v = new ChallengeVariant();
v.setChallenge(challenge);
v.setLanguage("python");
v.setStarterCode(starterCode);
v.setHarnessTemplate(harnessTemplate);
challengeVariantRepository.save(v);
}

//
private void seedDevUser() {
if (appUserRepository.findByUsername("dev").isEmpty()) {
AppUser dev = new AppUser();
Expand Down Expand Up @@ -169,6 +222,8 @@ function matchSchemas(schemaA, schemaB) {
c.setTestCases(List.of(visible, hidden));

challengeRepository.save(c);

addPythonVariant(c, MATCHING_TEMPLATE_PY, MATCHING_HARNESS_PY);
}

private void seedChallenge2() {
Expand Down Expand Up @@ -264,6 +319,8 @@ record TestData(String fullName, String firstName, String lastName, String id, S
c.setTestCases(testCases);

challengeRepository.save(c);

addPythonVariant(c, VERSIONING_TEMPLATE_PY, VERSIONING_HARNESS_PY);
}

private void seedChallenge3() {
Expand Down Expand Up @@ -385,6 +442,8 @@ function matchSchemas(schemaA, schemaB) {
c.setTestCases(List.of(visible, hidden));

challengeRepository.save(c);

addPythonVariant(c, MATCHING_TEMPLATE_PY, MATCHING_HARNESS_PY);
}

private void seedChallenge4() {
Expand Down Expand Up @@ -485,6 +544,8 @@ record TestData(String id, String name, String street, String city, String posta
c.setTestCases(testCases);

challengeRepository.save(c);

addPythonVariant(c, VERSIONING_TEMPLATE_PY, VERSIONING_HARNESS_PY);
}

private void seedChallenge5() {
Expand Down Expand Up @@ -631,6 +692,8 @@ function matchSchemas(schemaA, schemaB) {
c.setTestCases(List.of(visible, hidden));

challengeRepository.save(c);

addPythonVariant(c, MATCHING_TEMPLATE_PY, MATCHING_HARNESS_PY);
}

private void seedChallenge6() {
Expand Down Expand Up @@ -730,5 +793,7 @@ record TestData(String empId, String fullName, String firstName, String lastName
c.setTestCases(testCases);

challengeRepository.save(c);

addPythonVariant(c, VERSIONING_TEMPLATE_PY, VERSIONING_HARNESS_PY);
}
}
Loading
Loading