File size: 8,439 Bytes
5fed0fc |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 |
import axios from 'axios';
import fs from 'fs/promises';
import path from 'path';
import FormData from 'form-data';
import {createReadStream} from 'fs';
export class GoJudgeClient {
constructor(baseURL = 'http://127.0.0.1:5050') {
this.baseURL = baseURL;
}
// Basic invocation
async runOne(cmd) {
const { data } = await axios.post(`${this.baseURL}/run`, { cmd: [cmd] }, { timeout: 300000 });
return data[0];
}
async run(cmds) {
const { data } = await axios.post(`${this.baseURL}/run`, cmds, { timeout: 300000 });
return data;
}
// Delete file
async deleteFile(fileId) {
try {
await axios.delete(`${this.baseURL}/file/${encodeURIComponent(fileId)}`);
} catch { }
}
// Get file content
async getFileContent(fileId) {
const { data } = await axios.get(`${this.baseURL}/file/${encodeURIComponent(fileId)}`, { responseType: 'arraybuffer' });
return data;
}
// Upload file
async copyInFile(filePath) {
try {
const form = new FormData();
// 'file' is the field name required by backend, fs.createReadStream for efficient file reading
form.append('file', createReadStream(filePath));
// Use await to wait for post request completion
const { data } = await axios.post(`${this.baseURL}/file`, form, {
headers: {
...form.getHeaders() // form-data library generates necessary multipart headers
}
});
return data;
} catch (error) {
console.error(`Failed to upload file ${filePath}:`, error.message);
throw error; // Throw exception up for caller to handle
}
}
// Cache single file
async cacheSingleFile(name, content) {
const res = await this.runOne({
args: ['/bin/true'],
env: ['PATH=/usr/bin:/bin'],
files: [{ content: '' }, { name: 'stdout', max: 1 }, { name: 'stderr', max: 1024 }],
copyIn: { [name]: { content } },
copyOutCached: [name],
cpuLimit: 1e9,
memoryLimit: 16 << 20,
procLimit: 5,
});
if (res.status !== 'Accepted' || !res.fileIds?.[name]) {
throw new Error(`cache file failed: ${res.status}`);
}
return res.fileIds[name];
}
// Prepare program (compile or cache)
async prepareProgram({ lang, code, mainName = null, testlibPath = '/lib/testlib' }) {
if (lang === 'cpp') {
return await this._prepareCpp(code, mainName);
}
if (lang === 'java') {
return await this._prepareJava(code, mainName);
}
if (lang === 'py' || lang === 'pypy' || lang === 'python' || lang === 'python3') {
return await this._preparePython(code, mainName, lang);
}
throw new Error('unsupported lang');
}
async _prepareCpp(code, mainName) {
const srcName = mainName || 'main.cpp';
const outName = 'a';
const res = await this.runOne({
args: ['/usr/bin/g++', srcName, '-O2', '-pipe', '-std=gnu++17', '-o', outName],
env: ['PATH=/usr/bin:/bin'],
files: [{ content: '' }, { name: 'stdout', max: 1024 * 1024 }, { name: 'stderr', max: 1024 * 1024 }],
copyIn: { [srcName]: { content: code } },
copyOut: ['stdout', 'stderr'],
copyOutCached: [outName],
cpuLimit: 10e9,
memoryLimit: 512 << 20,
procLimit: 50,
});
if (res.status !== 'Accepted') {
throw new Error(`compile failed: ${res.files?.stderr || res.status}`);
}
const exeId = res.fileIds[outName];
return {
runArgs: [outName],
preparedCopyIn: { [outName]: { fileId: exeId } },
cleanupIds: [exeId]
};
}
async _prepareJava(code, mainName) {
const srcName = mainName || 'Main.java';
const mainClass = (srcName.replace(/\.java$/, '') || 'Main');
const res = await this.runOne({
args: ['/usr/bin/javac', srcName],
env: ['PATH=/usr/bin:/bin'],
files: [{ content: '' }, { name: 'stdout', max: 1024 * 64 }, { name: 'stderr', max: 1024 * 64 }],
copyIn: { [srcName]: { content: code } },
copyOut: ['stdout', 'stderr'],
copyOutCached: [`${mainClass}.class`],
cpuLimit: 10e9,
memoryLimit: 1024 << 20,
procLimit: 50,
});
if (res.status !== 'Accepted') {
throw new Error(`javac failed: ${res.files?.stderr || res.status}`);
}
const clsId = res.fileIds[`${mainClass}.class`];
return {
runArgs: ['/usr/bin/java', mainClass],
preparedCopyIn: { [`${mainClass}.class`]: { fileId: clsId } },
cleanupIds: [clsId],
};
}
async _preparePython(code, mainName, lang) {
const srcName = mainName || 'main.py';
const fileId = await this.cacheSingleFile(srcName, code);
const interp = (lang === 'pypy') ? '/usr/bin/pypy3' : '/usr/bin/python3';
return {
runArgs: [interp, srcName],
preparedCopyIn: { [srcName]: { fileId } },
cleanupIds: [fileId]
};
}
// Prepare checker
async prepareChecker(checkerSourceText, testlibPath = '/lib/testlib', srcName = 'chk.cc') {
const outName = 'chk';
const res = await this.runOne({
args: ['/usr/bin/g++', srcName, '-O2', '-pipe', '-std=gnu++17', '-I', testlibPath, '-o', outName],
env: ['PATH=/usr/bin:/bin'],
files: [{ content: '' }, { name: 'stdout', max: 1024 * 64 }, { name: 'stderr', max: 1024 * 64 }],
copyIn: { [srcName]: { content: checkerSourceText } },
copyOutCached: [outName],
cpuLimit: 10e9,
memoryLimit: 512 << 20,
procLimit: 50,
});
if (res.status !== 'Accepted') {
throw new Error(`checker compile failed: ${res.files?.stderr || res.status}`);
}
const checkerId = res.fileIds[outName];
return {
checkerId,
cleanup: () => this.deleteFile(checkerId)
};
}
async prepareInteractor(interactorSourceText, testlibPath = '/lib/testlib', srcName = 'interactor.cc') {
const outName = 'interactor';
const res = await this.runOne({
args: ['/usr/bin/g++', srcName, '-O2', '-pipe', '-std=gnu++17', '-I', testlibPath, '-o', outName],
env: ['PATH=/usr/bin:/bin'],
files: [{ content: '' }, { name: 'stdout', max: 1024 * 1024 }, { name: 'stderr', max: 1024 * 1024 }],
copyIn: { [srcName]: { content: interactorSourceText } },
copyOutCached: [outName],
cpuLimit: 10e9,
memoryLimit: 512 << 20,
procLimit: 128,
});
if (res.status !== 'Accepted') {
throw new Error(`interactor compile failed: ${res.files?.stderr || res.status}`);
}
const interactorId = res.fileIds[outName];
return {
interactorId,
cleanup: () => this.deleteFile(interactorId)
};
}
async getCheckerBin(checkerSourceText, testlibPath = '/lib/testlib', srcName = 'chk.cc') {
const { checkerId, cleanup } = await this.prepareChecker(checkerSourceText, testlibPath, srcName);
const checkerBin = await this.getFileContent(checkerId);
cleanup();
return checkerBin;
}
async getInteractorBin(interactorSourceText, testlibPath = '/lib/testlib', srcName = 'interactor.cc') {
const { interactorId, cleanup } = await this.prepareInteractor(interactorSourceText, testlibPath, srcName);
const interactorBin = await this.getFileContent(interactorId);
cleanup();
return interactorBin;
}
async copyInBin(binPath, testlibPath = '/lib/testlib', srcName = 'chk.cc') {
if (!binPath) {
throw new Error('binPath is required');
}
const binId = await this.copyInFile(binPath);
if (!binId) {
throw new Error('Failed to copy in binary');
}
const cleanup = () => this.deleteFile(binId);
return { binId, cleanup };
}
} |