-
Notifications
You must be signed in to change notification settings - Fork 2
/
client-lib.js
255 lines (223 loc) · 7.05 KB
/
client-lib.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
const WebSocket = require('ws');
const childProcess = require('child_process');
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const os = require('os');
function findLocalParleyDir(base, localParley) {
if(fs.existsSync(path.resolve(path.join(base, localParley)))) {
return path.resolve(path.join(base, localParley));
}
return false;
}
/*
The tmpdir is used to store the pid file and the socket
TODO: windows
*/
function tmpdir() {
const name = "parley-" + os.userInfo().username;
const fulldir = "/tmp/" + name;
if(!fs.existsSync(fulldir)) {
try {
mkdirp.sync(fulldir);
}
catch(e) {
error("Could not find or create temporary directory " + fulldir);
process.exit(1);
}
}
return fulldir;
}
function getSocket() {
const dir = tmpdir();
const portFile = path.join(dir, "comm.sock");
return portFile;
}
function start(options) {
const LOG = 4; // For debugging
const INFO = 3; // Here and below are for the user
const WARN = 2;
const ERROR = 1;
const SILENT = 0;
var LOG_LEVEL = INFO;
if(options.meta.quiet) { LOG_LEVEL = ERROR; }
function makeLogger(level) {
return function(...args) {
if(LOG_LEVEL >= level) {
console.log.apply(console, ["[client] ", new Date()].concat(args));
}
}
}
const info = makeLogger(INFO);
const log = makeLogger(LOG);
const warn = makeLogger(WARN);
const error = makeLogger(ERROR);
const localParley = options["_all"]["local-parley"];
var localParleyDir = findLocalParleyDir(process.cwd(), localParley);
if(localParleyDir === false) {
try {
mkdirp.sync(localParley);
localParleyDir = path.resolve(path.join(process.cwd(), localParley));
}
catch(e) {
error(String(e));
error("No " + localParley + " directory found and couldn't create it, exiting");
process.exit(1);
}
}
const serverModule = options.client.compiler;
var portFile = getSocket();
if(options.client.port) {
portFile = path.resolve(options.client.port); // Allow user to override location of port file
}
if(!options["pyret-options"]["compiled-dir"]) {
const compileTarget = path.join(localParleyDir, "compiled");
options["pyret-options"]["compiled-dir"] = compileTarget;
}
if(!options["pyret-options"]["base-dir"]) {
const baseDir = path.resolve(path.join(localParleyDir, ".."));
options["pyret-options"]["base-dir"] = baseDir;
}
function shutdown() {
try {
const client = new WebSocket("ws+unix://" + portFile);
client.on('error', function(err) {
error('Connection error: ' + err.toString() + ".");
error('You can try again, and the Pyret server may restart. If you see this error repeatedly, report it as a bug.');
});
client.on('open', function(connection) {
client.send(JSON.stringify({ command: 'shutdown' }));
});
tryToRemoveFiles();
}
catch(e) {
warn("Error during shutdown: " + e);
tryToRemoveFiles();
}
}
function tryToRemoveFiles() {
if(fs.existsSync(portFile)) { fs.unlinkSync(portFile); }
}
if(options.client.shutdown) {
shutdown();
return;
//process.exit(0);
}
function runProgram(path) {
log("Executing program: ", path);
const proc = childProcess.spawn("node", [path], {stdio: 'inherit'});
proc.on('close', function(code) {
process.exit(code);
});
}
function makeSocketAndConnect() {
const client = new WebSocket("ws+unix://" + portFile);
client.on('error', function(err) {
error('Connection error: ' + err.toString() + ".");
error('You can try again, and the Pyret server may restart. If you see this error repeatedly, report it as a bug.');
shutdown();
});
function sigint() {
log("Caught interrupt signal during compile job, stopping compile job");
client.send(JSON.stringify({ command: 'stop' }));
process.exit(0);
}
client.on('close', function() {
log('parley connection closed');
process.removeListener('SIGINT', sigint);
});
client.on('open', function(connection) {
log('parley protocol connected');
process.on('SIGINT', sigint);
client.on('message', function(message) {
const parsed = JSON.parse(message);
if(parsed.type === 'echo-log') {
if(options.meta.quiet) { return; }
if(parsed["clear-first"]) {
process.stdout.write("\r");
process.stdout.write(new Array(parsed["clear-first"] + 1).join(" "));
process.stdout.write("\r");
process.stdout.write(parsed.contents);
}
else {
process.stdout.write(parsed.contents);
}
}
else if(parsed.type === 'echo-err') {
process.stderr.write(parsed.contents);
}
else if(parsed.type === "compile-failure") {
// Intentional no-op
}
else if(parsed.type === "compile-success") {
log("Successful compile response");
if(!options.meta.norun) {
process.nextTick(() => runProgram(options["pyret-options"]["outfile"]));
}
}
});
var forMessage = { command: "compile", compileOptions: JSON.stringify(options['pyret-options']) };
client.send(JSON.stringify(forMessage));
});
return client;
}
function startupServer(port, wait) {
const child = childProcess.fork(
serverModule,
["-serve", "--port", port],
{
stdio: [0, 1, 2, 'ipc'],
execArgv: ["-max-old-space-size=8192"]
} // To send messages on completion of startup
);
if(wait) {
return new Promise((resolve, reject) => {
child.on('message', function(msg) {
if(msg.type === 'success') {
child.unref();
child.disconnect();
resolve(msg);
}
else {
reject(msg);
}
});
});
}
else {
child.unref();
child.disconnect();
}
}
const connectURL = portFile;
if (fs.existsSync(portFile)) {
// If the compiler is newer than the server process, restart
var compilerStats = fs.lstatSync(serverModule);
var portStats = fs.lstatSync(portFile);
if(portStats.mtime.getTime() < compilerStats.mtime.getTime()) {
info("A running server was found, but the chosen compiler (" + serverModule + ") is newer than the server. Restarting...");
shutdown();
startupServer(portFile, true)
.then(() => makeSocketAndConnect())
.catch((err) => error('Starting up the server failed: ', err));
}
else {
log("Connecting to: ", connectURL);
makeSocketAndConnect();
}
// Otherwise, try starting up a server and waiting for it, then doing the work
} else {
if (fs.existsSync(portFile)) {
makeSocketAndConnect();
}
else {
info("Starting up server...");
startupServer(portFile, true)
.then(() => makeSocketAndConnect())
.catch((err) => console.error('Starting up the server failed: ', err));
}
}
}
module.exports = {
start: start
}