-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
268 lines (247 loc) · 6.57 KB
/
server.js
File metadata and controls
268 lines (247 loc) · 6.57 KB
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
258
259
260
261
262
263
264
265
266
267
268
// In case this process is being spawned from a parent, make sure to exit
// in case the parent is killed
process.on('disconnect', function() {
process.exit();
});
var throng = require('throng');
var utils = require('./utils');
var pass = utils.pass;
var execute = utils.execute;
var delay = utils.delay;
var http = require('http');
var database = require('./database');
/**
* Starts the webserver
*
* The webserver will act on 3 types of request. One that includes the program
* source code to be added to the compilation queue, one that checks for the
* result of the compilation process, and one for generic config retrival
*
* The source code should be provided direcly as the URL payload, eg:
* http://{host}:{port}/{url-encoded-source-code}
*
* The compilation result should be requested by providing the compilation id as
* the URL payload, prepended by the char 'i', eg:
* http://{host}:{port}/i{compilation-id}
*
* Generic configs should be requested by providing the config key
* the URL payload, prepended by the char 'c', eg:
* http://{host}:{port}/c{config-key}
*/
var start = function () {
var port = process.env.COMPILER_PORT || process.env.PORT || 8080;
var server = http.createServer(function (request, response) {
response.setHeader("Access-Control-Allow-Origin", "*");
if(request.url.length === 1){
indexRequest(request, response);
}
else if(request.url.charAt(1) === 'i'){
resultRequest(request, response);
}
else if(request.url.charAt(1) === 'c'){
configRequest(request, response);
}
else{
queueRequest(request, response);
}
});
server.listen(port);
console.log('Serving on port '+port);
}
throng({
workers: process.env.WEB_CONCURRENCY || require('os').cpus().length,
lifetime: Infinity,
start: start
});
/**
* Index
*
* Provides meta info about the compiler
*/
var indexRequest = function(request, response){
response.writeHead(200, {'Content-Type': 'application/json'});
response.end(JSON.stringify({
message: 'Quirkbot compiler',
endpoints:[
{
'/{source-code}': 'Queues code for compilation'
},
{
'/i{compilation-id}': 'Retrieves info of an ongoing compilation.'
},
{
'/c{config-key}': 'Retrieves value of a generic configuration by key.'
},
{
'/cfirmware-reset': 'A valid HEX that will reset the Quirkbot to the factory settings.'
},
{
'/clibrary-info': 'The content of the library.properties of the current Quirkbot library.'
},
{
'/chardware-info': 'The content of the version.txt of the current Quirkbot board definition.'
}
]
}));
}
/**
* Compilation queue handle
*
* Extracts the source code out of the request URL payload, and pipes it to the
* queue process.
*
* On success, a response with status code 200 will be provided, alongside with
* the compilation id for future reference.
*
* On error, a response with status code 403 will be provided, alongside with
* the compiled error message.
*/
var queueRequest = function(request, response){
var code;
try{
code = decodeURIComponent(request.url.substr(1))
}
catch(e){}
var sketch = {
code: code
}
pass(sketch)
.then(queue)
.then(function(sketch){
delete sketch.code;
response.writeHead(200, {'Content-Type': 'application/json'});
response.end(JSON.stringify(sketch));
})
.catch(function(sketch){
delete sketch.code;
response.writeHead(403, {'Content-Type': 'application/json'});
response.end(JSON.stringify(sketch));
})
}
var queue = function(sketch){
var promise = function(resolve, reject){
pass(sketch)
.then(validate)
.then(create)
.then(resolve)
.catch(reject)
}
return new Promise(promise)
}
var validate = function(sketch){
var promise = function(resolve, reject){
var doReject = function(){
sketch.error = 'Invalid Quirkbot program';
reject(sketch)
}
if(sketch.code.indexOf('"Quirkbot.h"') == -1){
return doReject();
}
resolve(sketch)
};
return new Promise(promise);
}
var create = function(sketch){
var promise = function(resolve, reject){
database.create(sketch.code)
.then(function(id){
sketch._id = id;
resolve(sketch)
})
};
return new Promise(promise);
}
/**
* Compilation result handle
*
* Extracts the id out of the request URL payload, and pipes it to the result
* request process
*
* On success, a response with status code 200 will be provided, alongside with
* the compiled hex code.
*
* On error, a response with status code 403 will be provided, alongside with
* the compiled error message.
*/
var resultRequest = function(request, response){
var sketch = {
_id: request.url.substr(2)
}
pass(sketch)
.then(getResult)
.then(function(sketch){
delete sketch.code;
delete sketch.createdAt;
delete sketch.__v;
response.writeHead(200, {'Content-Type': 'application/json'});
response.end(JSON.stringify(sketch));
})
.catch(function(sketch){
delete sketch.code;
delete sketch.createdAt;
delete sketch.__v;
response.writeHead(403, {'Content-Type': 'application/json'});
response.end(JSON.stringify(sketch));
})
}
var getResult = function(sketch){
var promise = function(resolve, reject){
if(!sketch._id){
return resolve(sketch);
}
database.extract(sketch._id)
.then(resolve)
.catch(function(error){
console.log(error, sketch)
reject(sketch);
})
}
return new Promise(promise)
}
/**
* Config handle
*
* Extracts the key out of the request URL payload, and pipes it to the result
* request process
*
* On success, a response with status code 200 will be provided, alongside with
* config object
*
* On error, a response with status code 403 will be provided, alongside with
* an compiled error message.
*/
var configRequest = function(request, response){
var key = request.url.substr(2);
database.getConfig(key)
.then(function(config){
response.writeHead(200, {'Content-Type': 'application/json'});
response.end(JSON.stringify(config));
})
.catch(function(error){
response.writeHead(403, {'Content-Type': 'application/json'});
response.end(JSON.stringify(error));
})
}
/**
* Recursive Database cleanup routine
*
* Every 40 seconds request the database to delete entries that are created more
* that 30 seconds ago. This means that if a program's hex is not requested
* within 30 seconds, it will be discarted.
**/
var cleanOldEntries = function(){
database.clearOld(30000)
.then(delay(40000))
.then(cleanOldEntries)
.catch(function(){
pass()
.then(delay(40000))
.then(cleanOldEntries)
})
}
var cluster = require('cluster');
if (cluster.isMaster){
setTimeout(cleanOldEntries,0);
}
process.on( 'SIGINT', process.exit ) // catch ctrl-c
process.on( 'SIGTERM', process.exit ) // catch kill