-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
191 lines (168 loc) · 4.73 KB
/
main.ts
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
import { mergeReadableStreams, router, zipReadableStreams } from "./deps.ts";
Deno.serve(
{ port: 8000 },
router({
"/": () => {
return responseJSON({ status: "pass" });
},
"/health{z}?{/}?": () => {
return responseJSON({ status: "pass" });
},
"/runner/:version{/}?": async () => {
return await responseHealthCheck();
},
"/runner/:version/health{z}?{/}?": async () => {
return await responseHealthCheck();
},
"/runner/:version/run{/}?": async (req) => {
if (req.method !== "POST") {
return resposeError("Bad request", 400);
}
if (!req.body) {
return resposeError("Bad request", 400);
}
const parameters: RequestParameters = await req.json();
if (!parameters.code) {
return resposeError("Bad request", 400);
}
if (!parameters._streaming) {
return runOutput(parameters);
}
return runStream(parameters);
},
})
);
async function swiftVersion(): Promise<string> {
const command = makeVersionCommand();
const { stdout } = await command.output();
return new TextDecoder().decode(stdout);
}
async function runOutput(parameters: RequestParameters): Promise<Response> {
const version = await swiftVersion();
const { stdout, stderr } = await makeSwiftCommand(parameters).output();
const output = new TextDecoder().decode(stdout);
const errors = new TextDecoder().decode(stderr);
return responseJSON(new OutputResponse(output, errors, version));
}
function runStream(parameters: RequestParameters): Response {
return new Response(
zipReadableStreams(
spawn(makeVersionCommand(), undefined, "version", "version"),
spawn(makeSwiftCommand(parameters), parameters.code, "stdout", "stderr")
),
{
headers: {
"content-type": "text/plain; charset=utf-8",
},
}
);
}
function spawn(
command: Deno.Command,
input: string | undefined,
stdoutKey: string,
stderrKey: string
): ReadableStream<Uint8Array> {
const process = command.spawn();
if (input) {
const stdin = process.stdin;
const writer = stdin.getWriter();
writer.write(new TextEncoder().encode(input));
writer.releaseLock();
stdin.close();
}
return mergeReadableStreams(
makeStreamResponse(process.stderr, stderrKey),
makeStreamResponse(process.stdout, stdoutKey)
);
}
function makeVersionCommand(): Deno.Command {
return new Deno.Command("swift", {
args: ["-version"],
stdout: "piped",
stderr: "piped",
});
}
function makeSwiftCommand(parameters: RequestParameters): Deno.Command {
const command = parameters.command || "swift";
const options =
parameters.options ||
"-I ./swiftfiddle.com/_Packages/.build/release/ -I ./swiftfiddle.com/_Packages/.build/checkouts/swift-numerics/Sources/_NumericsShims/include/ -L ./swiftfiddle.com/_Packages/.build/release/ -l_Packages";
const timeout = parameters.timeout || 60;
const color = parameters._color || false;
const env = color
? {
TERM: "xterm-256color",
LD_PRELOAD: "./faketty.so",
}
: undefined;
const args = ["-i0", "-oL", "-eL", "timeout", `${timeout}`, command];
if (options) {
args.push(...options.split(" "));
}
args.push("-");
return new Deno.Command("stdbuf", {
args: args,
env: env,
stdin: "piped",
stdout: "piped",
stderr: "piped",
});
}
function makeStreamResponse(
stream: ReadableStream<Uint8Array>,
key: string
): ReadableStream<Uint8Array> {
return stream.pipeThrough(
new TransformStream<Uint8Array, Uint8Array>({
transform(chunk, controller) {
const text = new TextDecoder().decode(chunk);
controller.enqueue(
new TextEncoder().encode(
`${JSON.stringify(new StreamResponse(key, text))}\n`
)
);
},
})
);
}
async function responseHealthCheck(): Promise<Response> {
const version = await swiftVersion();
return responseJSON({ version });
}
function responseJSON(json: unknown): Response {
return new Response(JSON.stringify(json), {
headers: {
"content-type": "application/json; charset=utf-8",
},
});
}
function resposeError(message: string, status: number): Response {
return new Response(message, { status });
}
interface RequestParameters {
command?: string;
options?: string;
code?: string;
timeout?: number;
_color?: boolean;
_streaming?: boolean;
}
class OutputResponse {
output: string;
errors: string;
version: string;
constructor(output: string, errors: string, version: string) {
this.output = output;
this.errors = errors;
this.version = version;
}
}
class StreamResponse {
kind: string;
text: string;
constructor(kind: string, text: string) {
this.kind = kind;
this.text = text;
}
}