bw-hspc-contest-env/shared/submission-runner/csharp.cts

91 lines
2.4 KiB
TypeScript
Raw Normal View History

import { spawn } from 'child_process';
import kill from 'tree-kill';
import type { IRunner, IRunnerReturn, RunResult } from './types.cjs';
import { timeoutSeconds } from './settings.cjs';
2024-03-11 20:23:57 -04:00
export const runCSharp: IRunner = async function (params: {
srcDir: string;
input: string;
outputCallback?: (data: string) => void;
2024-03-11 20:23:57 -04:00
}): Promise<IRunnerReturn> {
console.log(`- RUN: ${params.srcDir}`);
const child = spawn('dotnet run', { shell: true, cwd: params.srcDir });
2024-03-11 20:23:57 -04:00
try {
let outputBuffer = '';
child.stdout.setEncoding('utf8');
child.stdout.on('data', (data) => {
outputBuffer += data.toString();
params.outputCallback?.(data.toString());
});
child.stderr.setEncoding('utf8');
child.stderr.on('data', (data) => {
outputBuffer += data.toString();
params.outputCallback?.(data.toString());
});
2024-03-11 20:23:57 -04:00
const runStartTime = performance.now();
child.stdin.write(params.input);
child.stdin.end();
2024-03-11 20:23:57 -04:00
let timeLimitExceeded = false;
let completedNormally = false;
2024-03-11 20:23:57 -04:00
return {
success: true,
runResult: new Promise<RunResult>((resolve) => {
child.on('close', () => {
completedNormally = !timeLimitExceeded;
2024-03-11 20:23:57 -04:00
const runEndTime = performance.now();
const runtimeMilliseconds = Math.floor(runEndTime - runStartTime);
2024-03-11 20:23:57 -04:00
if (completedNormally) {
clearTimeout(timeoutHandle);
resolve({
kind: 'Completed',
output: outputBuffer,
exitCode: child.exitCode!,
runtimeMilliseconds
});
} else {
console.log(`Process terminated, total sandbox time: ${runtimeMilliseconds}ms`);
resolve({
kind: 'TimeLimitExceeded',
output: outputBuffer,
resultKindReason: `Timeout after ${timeoutSeconds} seconds`
});
}
});
2024-03-11 20:23:57 -04:00
const timeoutHandle = setTimeout(() => {
if (completedNormally) {
return;
}
2024-03-11 20:23:57 -04:00
console.log(`Run timed out after ${timeoutSeconds} seconds, killing process...`);
timeLimitExceeded = true;
2024-03-11 20:23:57 -04:00
child.stdin.end();
child.stdin.destroy();
child.stdout.destroy();
child.stderr.destroy();
if (child.pid !== undefined) {
kill(child.pid);
}
}, timeoutSeconds * 1000);
}),
killFunc() {
if (child.pid !== undefined) {
if (!completedNormally && !timeLimitExceeded) {
kill(child.pid);
params.outputCallback?.('\n[Manually stopped]');
}
}
}
};
} catch (error) {
return { success: false, runResult: { kind: 'RunError' } };
}
2024-03-11 20:23:57 -04:00
};