-
Notifications
You must be signed in to change notification settings - Fork 5
/
serverAnalyzer.js
executable file
·258 lines (253 loc) · 8.64 KB
/
serverAnalyzer.js
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import { createRequire } from 'module'
import { writeFile, appendFile } from "fs/promises";
import { existsSync, unlinkSync } from "fs";
import { spawn, execSync } from "child_process";
import { usrID, usrDirMgr, makeDir, removeDir, dateTime, writePing, FLAGS } from "./serverUtil.js";
import express from "express";
const require = createRequire(import.meta.url);
const multer = require("multer");
const serverTimeout = 60000;
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Set of Middleware
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
export function reqTypeRouter() {
return (req, res, next) => {
if (req.is("application/json") === "application/json") {
return express.json()(req, res, next);
} else if (req.get('Content-Type').includes("multipart/form-data")) {
return multer().none()(req, res, next);
} else if (req.get('Content-Type').includes("application/x-www")) {
return express.urlencoded({extended: true})(req, res, next);
}
}
}
// ------------------------------------------------
export function usrConnect(serverDir) {
return (req, res, next) => {
if (req.body.reqType === "usrConnect") {
let id = usrID(req.ip);
if (id !== "-1") {
var reqDest = usrDirMgr(req, serverDir, id);
makeDir(reqDest.usrAbsDirPath);
} else {
reqDest = usrDirMgr(req, serverDir, "");
}
const asyVersion = execSync('asy -c VERSION', {
timeout: 500,
encoding: "ascii"
})
const dateAndTime = dateTime();
const rawData = {
usrIP: req.ip,
usrDir: reqDest.usrDirName,
date: dateAndTime.date,
time: dateAndTime.time,
};
const logFilePath = serverDir + "/logs/log";
appendFile(logFilePath, JSON.stringify(rawData, null, `\n`))
.then(() => console.log(`log file created successfully.`))
.catch((err) => console.log(`An error occurred while writing log file!\n ${err.toString()}`));
const data = {
usrID: id,
usrConnectStatus: "UDIC",
asyVersion: asyVersion
}
res.send(data);
} else {
next();
}
}
}
// ------------------------------------------------
export function reqAnalyzer(serverDir) {
return (req, res, next) => {
const reqDest = usrDirMgr(req, serverDir, req.body.id);
const codeFilename = req.body.workspaceName + "_" + req.body.workspaceId;
const codeFile = codeFilename + ".asy";
req.body = {
...req.body,
...reqDest,
codeFilename: codeFilename,
codeFile: codeFile,
codeFilePath: reqDest.usrAbsDirPath + "/" + codeFile,
htmlFile: reqDest.usrAbsDirPath + "/" + codeFilename + ".html",
}
if (typeof req.body.isUpdated === "string") {
req.body.isUpdated = req.body.isUpdated.includes("true");
}
if (req.body.codeOption !== undefined && typeof req.body.codeOption === "string") {
req.body.codeOption = req.body.codeOption.includes("true");
}
if (req.body.outputOption !== undefined && typeof req.body.outputOption === "string") {
req.body.outputOption = req.body.outputOption.includes("true");
}
// console.log("modified req.body:\n", req.body);
next();
}
}
// ------------------------------------------------
export function delAnalyzer(serverDir) {
return (req, res, next) => {
let requestAndId = /(\w+)&(\w+)/gi.exec(req.body);
if (requestAndId[1] === "deleteReq") {
const reqDest = usrDirMgr(req, serverDir, requestAndId[2]);
if (existsSync(reqDest.usrAbsDirPath)) {
removeDir(reqDest.usrAbsDirPath);
} else {
res.send(null);
}
} else {
res.send(null);
}
}
}
// ------------------------------------------------
export function writeAsyFile(serverDir) {
return (req, res, next) => {
const filePath = req.body.codeFilePath;
const fileContent = req.body.codeText;
writeFile(filePath, fileContent).then(() => {
next();
}).catch((err) => {
res.send(errResCreator(FLAGS.FAILURE.ASY_WRITE_FILE_ERR, err));
})
}
}
// ------------------------------------------------
export function requestResolver() {
return (req, res, next) => {
const option = {
cwd: req.body.usrAbsDirPath,
codeFile: req.body.codeFile,
codeOption: req.body.codeOption,
outputOption: req.body.outputOption,
}
switch (req.body.reqType) {
case "ping":
writePing(req.body.usrAbsDirPath);
next();
break;
case "run":
option.outformat = "html"
asyRunManager(req, res, next, option);
break;
case "download":
if (option.codeOption && !option.outputOption) {
res.send({
responseType: FLAGS.SUCCESS.ASY_FILE_CREATED,
isUpdated: !req.body.isUpdated
})
break;
} else if (option.outputOption) {
option.outformat = req.body.requestedOutformat;
asyRunManager(req, res, next, option);
break;
}
break;
default:
break;
}
}
}
// ------------------------------------------------
export function downloadReq(dirname) {
return function (req, res, next) {
if (req.body.codeOption) {
if (existsSync(req.body.codeFilePath)) {
res.download(req.body.codeFilePath);
}
}
if (req.body.outputOption) {
const outputFilePath = req.body.usrAbsDirPath + "/" + req.body.codeFilename + "." + req.body.requestedOutformat;
if (existsSync(outputFilePath)) {
res.download(outputFilePath);
}
}
}
}
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Resolver core function
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function asyRunManager(req, res, next, option) {
const asyArgs = ['-noV', '-outpipe', '2', '-noglobalread', '-f', option.outformat, option.codeFile];
const chProcOption = {
cwd: option.cwd,
}
const htmlFileExists = existsSync(req.body.htmlFile);
// if (req.body.reqType === "download" && option.outformat === "html" && htmlFileExists) {
// res.send({
// responseType: FLAGS.SUCCESS.ASY_OUTPUT_CREATED,
// isUpdated: !req.body.isUpdated
// });
// return;
// }
if (htmlFileExists) {
unlinkSync(req.body.htmlFile);
}
let stderrData = "", stdoutData = "";
const chProcHandler = spawn('asy', asyArgs, chProcOption);
setTimeout(() => {
chProcHandler.kill("SIGTERM");
}, serverTimeout)
// ------------------------------- onError
chProcHandler.on('error', (err) => {
const errResObject = errResCreator(FLAGS.FAILURE.PROCESS_SPAWN_ERR, err);
chProcHandler.kill();
res.send(errResObject);
});
// ------------------------------- onData
chProcHandler.stderr.on('data', (chunk) => {stderrData += chunk.toString()});
chProcHandler.stdout.on('data', (chunk) => {stdoutData += chunk.toString()});
// ------------------------------- onClose
chProcHandler.on('close', () => {});
// ------------------------------- onExit
chProcHandler.on('exit', (code, signal) => {
if (code === null) {
(signal === "SIGTERM") ? res.send(errResCreator(FLAGS.FAILURE.PROCESS_TIMEDOUT_ERR)) :
res.send(errResCreator(FLAGS.FAILURE.PROCESS_TERMINATED_ERR));
} else if (code !== 0) {
res.send({
...errResCreator(FLAGS.FAILURE.ASY_CODE_COMPILE_ERR),
stderr: stderrData,
stdout: stdoutData,
isUpdated: false
});
} else {
process.nextTick(() => {
const outputFilePath = req.body.usrAbsDirPath + "/" + req.body.codeFilename + "." + option.outformat;
if (existsSync(outputFilePath)) {
res.send({
responseType: FLAGS.SUCCESS.ASY_OUTPUT_CREATED,
stderr: stderrData,
stdout: stdoutData,
isUpdated: !req.body.isUpdated,
path: (option.outformat === "html")? req.body.usrRelDirPath
+ "/" + req.body.codeFilename + "." + option.outformat: ""
});
} else {
res.send({
responseType: FLAGS.SUCCESS.ASY_RUN_NO_OUTPUT,
stderr: stderrData,
stdout: stdoutData,
isUpdated: false
});
}
});
}
// console.log(`Code: ${code}\nSignal: ${signal}`);
});
}
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Core internal functions
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
export function errResCreator(flag, errObject = null, errorCode = null) {
const errResponse = {
responseType: "ERROR",
errorType: flag[0],
errorText: flag[1]
}
if (errObject === Object(errObject)) {
errResponse.errorCode = errObject.code;
errResponse.errorContent = errObject.toString();
} else {
errResponse.errorCode = errorCode;
}
return errResponse;
}