@koeroesi86/node-worker-express 22.3.12-fd2e588 → 23.3.4361494358-main
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/constants/index.d.ts +11 -0
- package/dist/index-aad82b3f.js +15 -0
- package/dist/index-aad82b3f.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +446 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware/bodyParser.d.ts +5 -0
- package/dist/middleware/index.d.ts +19 -0
- package/dist/staticWorker.d.ts +3 -0
- package/dist/staticWorker.js +194 -0
- package/dist/staticWorker.js.map +1 -0
- package/dist/types/index.d.ts +41 -0
- package/dist/utils/constructWsMessage.d.ts +3 -0
- package/dist/utils/getClientIp.d.ts +3 -0
- package/dist/utils/isWebSocket.d.ts +3 -0
- package/dist/utils/parseWsMessage.d.ts +3 -0
- package/dist/utils/workerPool.d.ts +19 -0
- package/dist/workerInvoke.d.ts +1 -0
- package/dist/workerInvoke.js +54 -0
- package/dist/workerInvoke.js.map +1 -0
- package/package.json +8 -3
- package/rollup.config.js +12 -0
- package/.travis.yml +0 -17
- package/constants/index.js +0 -12
- package/examples/public/favicon.ico +0 -0
- package/examples/public/websocket/worker.js +0 -60
- package/examples/public/worker.js +0 -42
- package/examples/server.js +0 -29
- package/examples/staticWorker.js +0 -237
- package/index.d.ts +0 -64
- package/index.js +0 -3
- package/middleware/bodyParser.js +0 -36
- package/middleware/index.js +0 -288
- package/middleware/workerInvoke.js +0 -54
- package/nodemon.json +0 -6
- package/scripts/version.js +0 -9
- package/utils/constructWsMessage.js +0 -27
- package/utils/getClientIp.js +0 -71
- package/utils/isWebSocket.js +0 -16
- package/utils/parseWsMessage.js +0 -25
- package/utils/workerPool.js +0 -101
package/examples/staticWorker.js
DELETED
|
@@ -1,237 +0,0 @@
|
|
|
1
|
-
const path = require('path');
|
|
2
|
-
const fs = require('fs');
|
|
3
|
-
const crypto = require('crypto');
|
|
4
|
-
const { execSync } = require('child_process');
|
|
5
|
-
const { Writable } = require('stream');
|
|
6
|
-
|
|
7
|
-
let timer;
|
|
8
|
-
|
|
9
|
-
const features = {
|
|
10
|
-
enableEmit: false,
|
|
11
|
-
};
|
|
12
|
-
|
|
13
|
-
function debounce(fn = () => {}, timeout = 0) {
|
|
14
|
-
if (timer) clearTimeout(timer);
|
|
15
|
-
timer = setTimeout(() => {
|
|
16
|
-
timer = undefined;
|
|
17
|
-
fn();
|
|
18
|
-
}, timeout);
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
function getContentType(extension = '') {
|
|
22
|
-
const contentTypes = {
|
|
23
|
-
'.aac': 'audio/aac',
|
|
24
|
-
'.abw': 'application/x-abiword',
|
|
25
|
-
'.arc': 'application/x-freearc',
|
|
26
|
-
'.avi': 'video/x-msvideo',
|
|
27
|
-
'.azw': 'application/vnd.amazon.ebook',
|
|
28
|
-
'.bin': 'application/octet-stream',
|
|
29
|
-
'.bmp': 'image/bmp',
|
|
30
|
-
'.bz': 'application/x-bzip',
|
|
31
|
-
'.bz2': 'application/x-bzip2',
|
|
32
|
-
'.csh': 'application/x-csh',
|
|
33
|
-
'.css': 'text/css',
|
|
34
|
-
'.csv': 'text/csv',
|
|
35
|
-
'.doc': 'application/msword',
|
|
36
|
-
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
37
|
-
'.eot': 'application/vnd.ms-fontobject',
|
|
38
|
-
'.epub': 'application/epub+zip',
|
|
39
|
-
'.gz': 'application/gzip',
|
|
40
|
-
'.gif': 'image/gif',
|
|
41
|
-
'.htm': 'text/html',
|
|
42
|
-
'.html': 'text/html',
|
|
43
|
-
'.ico': 'image/vnd.microsoft.icon',
|
|
44
|
-
'.ics': 'text/calendar',
|
|
45
|
-
'.jar': 'application/java-archive',
|
|
46
|
-
'.jpeg': 'image/jpeg',
|
|
47
|
-
'.jpg': 'image/jpeg',
|
|
48
|
-
'.js': 'text/javascript',
|
|
49
|
-
'.json': 'application/json',
|
|
50
|
-
'.jsonld': 'application/ld+json',
|
|
51
|
-
'.mid': 'audio/midi',
|
|
52
|
-
'.midi': 'audio/x-midi',
|
|
53
|
-
'.mjs': 'text/javascript',
|
|
54
|
-
'.mp3': 'audio/mpeg',
|
|
55
|
-
'.mpeg': 'video/mpeg',
|
|
56
|
-
'.mpkg': 'application/vnd.apple.installer+xml',
|
|
57
|
-
'.odp': 'application/vnd.oasis.opendocument.presentation',
|
|
58
|
-
'.ods': 'application/vnd.oasis.opendocument.spreadsheet',
|
|
59
|
-
'.odt': 'application/vnd.oasis.opendocument.text',
|
|
60
|
-
'.oga': 'audio/ogg',
|
|
61
|
-
'.ogv': 'video/ogg',
|
|
62
|
-
'.ogx': 'application/ogg',
|
|
63
|
-
'.opus': 'audio/opus',
|
|
64
|
-
'.otf': 'font/otf',
|
|
65
|
-
'.png': 'image/png',
|
|
66
|
-
'.pdf': 'application/pdf',
|
|
67
|
-
'.php': 'application/php',
|
|
68
|
-
'.ppt': 'application/vnd.ms-powerpoint',
|
|
69
|
-
'.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
70
|
-
'.rar': 'application/vnd.rar',
|
|
71
|
-
'.rtf': 'application/rtf',
|
|
72
|
-
'.sh': 'application/x-sh',
|
|
73
|
-
'.svg': 'image/svg+xml',
|
|
74
|
-
'.swf': 'application/x-shockwave-flash',
|
|
75
|
-
'.tar': 'application/x-tar',
|
|
76
|
-
'.tif': 'image/tiff',
|
|
77
|
-
'.tiff': 'image/tiff',
|
|
78
|
-
'.ts': 'video/mp2t',
|
|
79
|
-
'.ttf': 'font/ttf',
|
|
80
|
-
'.txt': 'text/plain',
|
|
81
|
-
'.vsd': 'application/vnd.visio',
|
|
82
|
-
'.wav': 'audio/wav',
|
|
83
|
-
'.weba': 'audio/webm',
|
|
84
|
-
'.webm': 'video/webm',
|
|
85
|
-
'.webp': 'image/webp',
|
|
86
|
-
'.woff': 'font/woff',
|
|
87
|
-
'.woff2': 'font/woff2',
|
|
88
|
-
'.xhtml': 'application/xhtml+xml',
|
|
89
|
-
'.xls': 'application/vnd.ms-excel',
|
|
90
|
-
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
91
|
-
'.xml': 'application/xml',
|
|
92
|
-
'.xul': 'application/vnd.mozilla.xul+xml',
|
|
93
|
-
'.zip': 'application/zip',
|
|
94
|
-
'.3gp': 'video/3gpp',
|
|
95
|
-
'.3g2': 'video/3gpp2',
|
|
96
|
-
'.7z': 'application/x-7z-compressed',
|
|
97
|
-
};
|
|
98
|
-
|
|
99
|
-
return contentTypes[extension] || contentTypes['.txt'];
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
function etag(body) {
|
|
103
|
-
if (body.length === 0) {
|
|
104
|
-
// fast-path empty
|
|
105
|
-
return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"';
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
// compute hash of entity
|
|
109
|
-
const hash = crypto
|
|
110
|
-
.createHash('sha1')
|
|
111
|
-
.update(body, 'utf8')
|
|
112
|
-
.digest('base64')
|
|
113
|
-
.substring(0, 27);
|
|
114
|
-
|
|
115
|
-
// compute length of entity
|
|
116
|
-
const len = typeof body === 'string'
|
|
117
|
-
? Buffer.byteLength(body, 'utf8')
|
|
118
|
-
: body.length;
|
|
119
|
-
|
|
120
|
-
return `"${len.toString(16)}-${hash}"`
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
/**
|
|
124
|
-
* TODO: implement
|
|
125
|
-
* @param {Buffer} body
|
|
126
|
-
* @param {string} fileName
|
|
127
|
-
* @returns {boolean|string}
|
|
128
|
-
*/
|
|
129
|
-
function getCharset(body, fileName) {
|
|
130
|
-
// Byte order mark
|
|
131
|
-
if (body[0] === 0xEF && body[1] === 0xBB && body[2] === 0xBF)
|
|
132
|
-
return 'utf8';
|
|
133
|
-
if (body[0] === 0xFE && body[1] === 0xFF)
|
|
134
|
-
return 'utf16be';
|
|
135
|
-
if (body[0] === 0xFF && body[1] === 0xFE)
|
|
136
|
-
return 'utf16le';
|
|
137
|
-
if (body.indexOf('') === 0)
|
|
138
|
-
return 'iso-8859-1';
|
|
139
|
-
|
|
140
|
-
try {
|
|
141
|
-
return execSync(`file -b --mime-encoding ${fileName}`).toString('utf8').trim();
|
|
142
|
-
} catch (e) {
|
|
143
|
-
//
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
return false;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
const staticWorker = (event, callback = () => {}) => {
|
|
150
|
-
debounce(() => {
|
|
151
|
-
console.log('Exiting static worker.');
|
|
152
|
-
process.exit(0);
|
|
153
|
-
}, 1000 * 60 * 30);
|
|
154
|
-
const currentPath = `${event.path.replace(/\.{2,}/, '')}${/\/$/.test(event.path) ? 'index.html' : ''}`;
|
|
155
|
-
const fileName = path.resolve(event.rootPath, `.${currentPath}`);
|
|
156
|
-
if (['GET', 'HEAD'].includes(event.httpMethod) && fs.existsSync(fileName)) {
|
|
157
|
-
// TODO: range request
|
|
158
|
-
const bodyBuffer = fs.readFileSync(fileName);
|
|
159
|
-
const stats = fs.statSync(fileName);
|
|
160
|
-
const extension = path.extname(fileName);
|
|
161
|
-
const contentType = getContentType(extension);
|
|
162
|
-
const currentEtag = etag(bodyBuffer);
|
|
163
|
-
const charset = getCharset(bodyBuffer, fileName);
|
|
164
|
-
|
|
165
|
-
const lastModified = new Date(stats.mtime);
|
|
166
|
-
let isModified = true;
|
|
167
|
-
|
|
168
|
-
if (event.headers['if-none-match'] === currentEtag) {
|
|
169
|
-
isModified = false;
|
|
170
|
-
} else if (event.headers['if-modified-since']) {
|
|
171
|
-
const ifModifiedSince = new Date(event.headers['if-modified-since']);
|
|
172
|
-
if (ifModifiedSince.toUTCString() === lastModified.toUTCString()) {
|
|
173
|
-
isModified = false;
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
const response = {
|
|
177
|
-
statusCode: isModified ? 200 : 304,
|
|
178
|
-
headers: {
|
|
179
|
-
'Content-Type': `${contentType}${charset ? `; charset=${charset}` : ''}`,
|
|
180
|
-
'Cache-Control': 'public, max-age=0',
|
|
181
|
-
'Content-Length': bodyBuffer.byteLength,
|
|
182
|
-
'ETag': currentEtag,
|
|
183
|
-
...(stats.mtime && { 'Last-Modified': lastModified.toUTCString() }),
|
|
184
|
-
},
|
|
185
|
-
body: isModified ? bodyBuffer.toString('base64') : '',
|
|
186
|
-
isBase64Encoded: true,
|
|
187
|
-
};
|
|
188
|
-
|
|
189
|
-
if (features.enableEmit && isModified) {
|
|
190
|
-
const writer = new Writable({
|
|
191
|
-
/**
|
|
192
|
-
* @param {Buffer} chunk
|
|
193
|
-
* @param {string} encoding
|
|
194
|
-
* @param {Function} next
|
|
195
|
-
*/
|
|
196
|
-
write(chunk, encoding, next) {
|
|
197
|
-
response.emit = true;
|
|
198
|
-
response.isBase64Encoded = true;
|
|
199
|
-
response.body = chunk.toString('base64');
|
|
200
|
-
// console.log('sending', chunk.length, 'bytes')
|
|
201
|
-
callback(response);
|
|
202
|
-
next();
|
|
203
|
-
},
|
|
204
|
-
destroy() {
|
|
205
|
-
response.isBase64Encoded = false;
|
|
206
|
-
response.emit = true;
|
|
207
|
-
response.body = null;
|
|
208
|
-
callback(response);
|
|
209
|
-
},
|
|
210
|
-
});
|
|
211
|
-
|
|
212
|
-
fs.createReadStream(fileName, {
|
|
213
|
-
// encoding: 'binary',
|
|
214
|
-
// encoding: 'utf-8',
|
|
215
|
-
emitClose: false,
|
|
216
|
-
autoClose: false,
|
|
217
|
-
// highWaterMark: 16,
|
|
218
|
-
start: 0,
|
|
219
|
-
end: Infinity,
|
|
220
|
-
}).pipe(writer);
|
|
221
|
-
} else {
|
|
222
|
-
callback(response);
|
|
223
|
-
}
|
|
224
|
-
} else {
|
|
225
|
-
callback({
|
|
226
|
-
statusCode: 404,
|
|
227
|
-
headers: {
|
|
228
|
-
'Content-Type': 'text/plain',
|
|
229
|
-
'Cache-Control': 'public, max-age=0',
|
|
230
|
-
},
|
|
231
|
-
body:`${fileName} does not exist`,
|
|
232
|
-
isBase64Encoded: false,
|
|
233
|
-
});
|
|
234
|
-
}
|
|
235
|
-
};
|
|
236
|
-
|
|
237
|
-
module.exports = staticWorker;
|
package/index.d.ts
DELETED
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
type MiddlewareOptions = {
|
|
2
|
-
root: string,
|
|
3
|
-
limit?: number,
|
|
4
|
-
limitPerPath?: number|((path: string) => number),
|
|
5
|
-
limitRequestBody?: number,
|
|
6
|
-
limitRequestTimeout?: number,
|
|
7
|
-
idleCheckTimeout?: number,
|
|
8
|
-
onStdout?: (data: Buffer) => void,
|
|
9
|
-
onStderr?: (data: Buffer) => void,
|
|
10
|
-
onExit?: void,
|
|
11
|
-
index?: string[],
|
|
12
|
-
env?: object,
|
|
13
|
-
staticWorker?: string,
|
|
14
|
-
cwd?: string,
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
declare namespace Middleware {
|
|
18
|
-
type RequestEvent = {
|
|
19
|
-
httpMethod: string;
|
|
20
|
-
protocol: string;
|
|
21
|
-
path: string;
|
|
22
|
-
pathFragments: string[];
|
|
23
|
-
queryStringParameters: { [key: string]: string };
|
|
24
|
-
headers: { [key: string]: string };
|
|
25
|
-
remoteAddress: string;
|
|
26
|
-
body: string;
|
|
27
|
-
rootPath: string;
|
|
28
|
-
closed?: boolean;
|
|
29
|
-
frame?: string;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
type WorkerInputEvent = {
|
|
33
|
-
type: string;
|
|
34
|
-
requestId: string;
|
|
35
|
-
event?: RequestEvent;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
type WorkerOutputEvent = {
|
|
39
|
-
type: string;
|
|
40
|
-
requestId: string;
|
|
41
|
-
event?: ResponseEvent|WSFrameEvent;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
type ResponseEvent = {
|
|
45
|
-
statusCode: number;
|
|
46
|
-
headers?: { [key: string]: string };
|
|
47
|
-
isBase64Encoded?: boolean;
|
|
48
|
-
emit?: boolean;
|
|
49
|
-
body?: string;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
type WSFrameEvent = {
|
|
53
|
-
sendWsMessage: boolean;
|
|
54
|
-
frame: string;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
type InvokableWorker = (event: RequestEvent, callback: (e: ResponseEvent) => void) => void;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
declare module '@koeroesi86/node-worker-express' {
|
|
61
|
-
import { RequestHandler } from "express";
|
|
62
|
-
|
|
63
|
-
export function middleware(options: MiddlewareOptions): RequestHandler;
|
|
64
|
-
}
|
package/index.js
DELETED
package/middleware/bodyParser.js
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
const ignoredMethods = ['get', 'delete', 'options', 'head'];
|
|
2
|
-
|
|
3
|
-
const bodyParser = (config = { limitRequestBody: 1000000, shouldError: true }) => (request, response, next) => {
|
|
4
|
-
let body = '';
|
|
5
|
-
|
|
6
|
-
if (ignoredMethods.includes(request.method.toLowerCase())) {
|
|
7
|
-
request.body = body;
|
|
8
|
-
next();
|
|
9
|
-
return;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
request.on('data', data => {
|
|
13
|
-
body += data;
|
|
14
|
-
|
|
15
|
-
// Too much POST data, kill the connection!
|
|
16
|
-
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
|
|
17
|
-
if (body.length > (config.limitRequestBody || 1000000)) {
|
|
18
|
-
body = "";
|
|
19
|
-
|
|
20
|
-
if (config.shouldError) {
|
|
21
|
-
response.writeHead(413, { 'Content-Type': 'text/plain' });
|
|
22
|
-
response.end();
|
|
23
|
-
request.connection.destroy();
|
|
24
|
-
} else {
|
|
25
|
-
next();
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
});
|
|
29
|
-
|
|
30
|
-
request.on('end', () => {
|
|
31
|
-
request.body = body;
|
|
32
|
-
next();
|
|
33
|
-
});
|
|
34
|
-
};
|
|
35
|
-
|
|
36
|
-
module.exports = bodyParser;
|
package/middleware/index.js
DELETED
|
@@ -1,288 +0,0 @@
|
|
|
1
|
-
const { v4: uuid } = require('uuid');
|
|
2
|
-
const path = require('path');
|
|
3
|
-
const fs = require('fs');
|
|
4
|
-
const url = require('url');
|
|
5
|
-
const { WORKER_EVENT } = require('../constants');
|
|
6
|
-
const WorkerPool = require('../utils/workerPool');
|
|
7
|
-
const isWebSocket = require('../utils/isWebSocket');
|
|
8
|
-
const parseWsMessage = require('../utils/parseWsMessage');
|
|
9
|
-
const constructWsMessage = require('../utils/constructWsMessage');
|
|
10
|
-
const getClientIp = require('../utils/getClientIp');
|
|
11
|
-
const createBodyParser = require('./bodyParser');
|
|
12
|
-
|
|
13
|
-
const ForbiddenPaths = [
|
|
14
|
-
'..'
|
|
15
|
-
];
|
|
16
|
-
|
|
17
|
-
const Protocols = {
|
|
18
|
-
http: 'HTTP',
|
|
19
|
-
websocket: 'WS',
|
|
20
|
-
};
|
|
21
|
-
|
|
22
|
-
const DefaultOptions = {
|
|
23
|
-
root: null,
|
|
24
|
-
limit: 0,
|
|
25
|
-
limitPerPath: 0,
|
|
26
|
-
limitRequestBody: 1000000,
|
|
27
|
-
limitRequestTimeout: 5000,
|
|
28
|
-
idleCheckTimeout: 5,
|
|
29
|
-
onStdout: () => {
|
|
30
|
-
},
|
|
31
|
-
onStderr: () => {
|
|
32
|
-
},
|
|
33
|
-
onExit: () => {
|
|
34
|
-
},
|
|
35
|
-
onForbiddenPath: (request, response) => {
|
|
36
|
-
response.writeHead(500, { 'Content-Type': 'text/plain' });
|
|
37
|
-
response.end();
|
|
38
|
-
request.connection.destroy();
|
|
39
|
-
},
|
|
40
|
-
index: [],
|
|
41
|
-
env: {},
|
|
42
|
-
staticWorker: path.resolve(__dirname, '../examples/staticWorker.js'),
|
|
43
|
-
cwd: process.cwd(),
|
|
44
|
-
};
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* @namespace Middleware
|
|
48
|
-
* @param {MiddlewareOptions} [options]
|
|
49
|
-
* @returns {RequestHandler}
|
|
50
|
-
*/
|
|
51
|
-
const workerMiddleware = (options) => {
|
|
52
|
-
const config = {
|
|
53
|
-
...DefaultOptions,
|
|
54
|
-
...(options && options),
|
|
55
|
-
};
|
|
56
|
-
if (!config.root) {
|
|
57
|
-
throw new Error('No root path defined in configuration!');
|
|
58
|
-
}
|
|
59
|
-
const rootPath = path.resolve(config.root);
|
|
60
|
-
const workerPool = new WorkerPool({
|
|
61
|
-
overallLimit: config.limit,
|
|
62
|
-
onExit: config.onExit,
|
|
63
|
-
idleCheckTimeout: config.idleCheckTimeout,
|
|
64
|
-
});
|
|
65
|
-
const bodyParser = createBodyParser({ limitRequestBody: config.limitRequestBody });
|
|
66
|
-
const aliasCache = {};
|
|
67
|
-
const workerCache = {};
|
|
68
|
-
|
|
69
|
-
return async (request, response, next) => {
|
|
70
|
-
const {
|
|
71
|
-
query: queryStringParameters,
|
|
72
|
-
pathname
|
|
73
|
-
} = url.parse(request.url, true);
|
|
74
|
-
request.pathFragments = pathname.split(/\//gi).filter(Boolean);
|
|
75
|
-
|
|
76
|
-
try {
|
|
77
|
-
let isWorker = false;
|
|
78
|
-
const pathFragments = pathname.split(/\//gi).filter(Boolean);
|
|
79
|
-
let currentPathFragments = pathFragments.slice(0);
|
|
80
|
-
let pathExists = false;
|
|
81
|
-
|
|
82
|
-
await new Promise((resolve, reject) => {
|
|
83
|
-
if (request.pathFragments.find(p => ForbiddenPaths.includes(p))) {
|
|
84
|
-
config.onForbiddenPath(request, response);
|
|
85
|
-
reject();
|
|
86
|
-
}
|
|
87
|
-
resolve();
|
|
88
|
-
});
|
|
89
|
-
|
|
90
|
-
await Promise.race([
|
|
91
|
-
new Promise((res, rej) => setTimeout(rej, config.limitRequestTimeout)),
|
|
92
|
-
new Promise(res => bodyParser(request, response, res)),
|
|
93
|
-
]);
|
|
94
|
-
let indexPath;
|
|
95
|
-
|
|
96
|
-
if (aliasCache[pathname] && fs.existsSync(aliasCache[pathname])) {
|
|
97
|
-
isWorker = true;
|
|
98
|
-
indexPath = aliasCache[pathname];
|
|
99
|
-
} else if (workerCache[pathname] && fs.existsSync(workerCache[pathname])) {
|
|
100
|
-
isWorker = true;
|
|
101
|
-
indexPath = workerCache[pathname];
|
|
102
|
-
} else {
|
|
103
|
-
indexPath = path.join(rootPath, ...currentPathFragments)
|
|
104
|
-
|
|
105
|
-
for (let i = currentPathFragments.length; i >= 0 && !pathExists; i--) {
|
|
106
|
-
if (pathExists) continue;
|
|
107
|
-
currentPathFragments.splice(i);
|
|
108
|
-
const currentPath = path.join(rootPath, ...currentPathFragments);
|
|
109
|
-
pathExists = fs.existsSync(currentPath);
|
|
110
|
-
if (!pathExists) continue;
|
|
111
|
-
const currentStats = fs.statSync(currentPath);
|
|
112
|
-
|
|
113
|
-
if (pathExists && currentStats.isDirectory()) {
|
|
114
|
-
// index fallback
|
|
115
|
-
pathExists = !!config.index.find(indexFile => {
|
|
116
|
-
const checkIndexFilePath = path.join(currentPath, indexFile);
|
|
117
|
-
if (fs.existsSync(checkIndexFilePath)) {
|
|
118
|
-
isWorker = true;
|
|
119
|
-
indexPath = checkIndexFilePath;
|
|
120
|
-
aliasCache[pathname] = checkIndexFilePath;
|
|
121
|
-
setTimeout(() => {
|
|
122
|
-
aliasCache[pathname] = null;
|
|
123
|
-
delete aliasCache[pathname];
|
|
124
|
-
}, 5000);
|
|
125
|
-
return true;
|
|
126
|
-
}
|
|
127
|
-
});
|
|
128
|
-
if (pathExists) break;
|
|
129
|
-
} else if (pathExists && currentStats.isFile()) {
|
|
130
|
-
if (config.index.includes(currentPathFragments[currentPathFragments.length - 1])) {
|
|
131
|
-
isWorker = true;
|
|
132
|
-
workerCache[pathname] = currentPath;
|
|
133
|
-
setTimeout(() => {
|
|
134
|
-
workerCache[pathname] = null;
|
|
135
|
-
delete workerCache[pathname];
|
|
136
|
-
}, 5000);
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/** @type {RequestEvent} */
|
|
143
|
-
const event = {
|
|
144
|
-
httpMethod: request.method.toUpperCase(),
|
|
145
|
-
protocol: isWebSocket(request) ? Protocols.websocket : Protocols.http,
|
|
146
|
-
path: pathname,
|
|
147
|
-
pathFragments: pathFragments,
|
|
148
|
-
queryStringParameters: JSON.parse(JSON.stringify(queryStringParameters)),
|
|
149
|
-
headers: request.headers,
|
|
150
|
-
remoteAddress: getClientIp(request),
|
|
151
|
-
body: `${request.body}`,
|
|
152
|
-
rootPath: rootPath,
|
|
153
|
-
};
|
|
154
|
-
|
|
155
|
-
const worker = isWorker ? await workerPool.getWorker(
|
|
156
|
-
indexPath,
|
|
157
|
-
{
|
|
158
|
-
stdio: [ 'pipe', 'pipe', 'pipe', 'ipc' ],
|
|
159
|
-
env: { ...process.env, ...config.env },
|
|
160
|
-
cwd: config.cwd,
|
|
161
|
-
},
|
|
162
|
-
typeof config.limitPerPath === "function" ? config.limitPerPath(indexPath) : config.limitPerPath
|
|
163
|
-
) : await workerPool.getWorker(
|
|
164
|
-
config.staticWorker,
|
|
165
|
-
{
|
|
166
|
-
cwd: process.cwd(),
|
|
167
|
-
stdio: [ 'pipe', 'pipe', 'pipe', 'ipc' ],
|
|
168
|
-
},
|
|
169
|
-
1
|
|
170
|
-
);
|
|
171
|
-
|
|
172
|
-
const requestId = uuid();
|
|
173
|
-
|
|
174
|
-
let firstReceived = false;
|
|
175
|
-
const requestSocketListener = data => {
|
|
176
|
-
const frame = parseWsMessage(data);
|
|
177
|
-
|
|
178
|
-
// TODO: filter open frame better
|
|
179
|
-
if (data.length === 8 && !firstReceived) {
|
|
180
|
-
firstReceived = true;
|
|
181
|
-
return;
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
firstReceived = true;
|
|
185
|
-
|
|
186
|
-
worker.postMessage({
|
|
187
|
-
type: WORKER_EVENT.WS_MESSAGE_RECEIVE,
|
|
188
|
-
requestId,
|
|
189
|
-
event: { ...event, frame }
|
|
190
|
-
});
|
|
191
|
-
};
|
|
192
|
-
if (event.protocol === Protocols.websocket) {
|
|
193
|
-
request.socket.on('data', requestSocketListener);
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
worker.instance.stdout.off('data', config.onStdout);
|
|
197
|
-
worker.instance.stdout.on('data', config.onStdout);
|
|
198
|
-
|
|
199
|
-
worker.instance.stderr.off('data', config.onStderr);
|
|
200
|
-
worker.instance.stderr.on('data', config.onStderr);
|
|
201
|
-
|
|
202
|
-
const messageListener = responseEvent => {
|
|
203
|
-
if (responseEvent.requestId === requestId) {
|
|
204
|
-
if (responseEvent.type === WORKER_EVENT.RESPONSE) {
|
|
205
|
-
worker.postMessage({
|
|
206
|
-
type: WORKER_EVENT.RESPONSE_ACKNOWLEDGE,
|
|
207
|
-
requestId,
|
|
208
|
-
});
|
|
209
|
-
/** @type {ResponseEvent|WSFrameEvent} event */
|
|
210
|
-
const { event } = responseEvent;
|
|
211
|
-
const bufferEncoding = event.isBase64Encoded ? 'base64' : 'utf8';
|
|
212
|
-
|
|
213
|
-
response.writeHead(event.statusCode, event.headers);
|
|
214
|
-
response.write(Buffer.from(event.body, bufferEncoding));
|
|
215
|
-
response.end();
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
if (responseEvent.type === WORKER_EVENT.RESPONSE_EMIT) {
|
|
219
|
-
worker.postMessage({
|
|
220
|
-
type: WORKER_EVENT.RESPONSE_ACKNOWLEDGE,
|
|
221
|
-
requestId,
|
|
222
|
-
});
|
|
223
|
-
/** @type {ResponseEvent|WSFrameEvent} event */
|
|
224
|
-
const { event } = responseEvent;
|
|
225
|
-
const bufferEncoding = event.isBase64Encoded ? 'base64' : 'utf8';
|
|
226
|
-
|
|
227
|
-
if (!response.headersSent) {
|
|
228
|
-
response.writeHead(event.statusCode, event.headers);
|
|
229
|
-
}
|
|
230
|
-
if (event.body !== null) {
|
|
231
|
-
response.write(Buffer.from(event.body, bufferEncoding).toString());
|
|
232
|
-
} else {
|
|
233
|
-
response.end();
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
if (responseEvent.type === WORKER_EVENT.WS_MESSAGE_SEND) {
|
|
238
|
-
request.socket.write(constructWsMessage(responseEvent.event.frame));
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
if (responseEvent.type === WORKER_EVENT.REQUEST_ACKNOWLEDGE) {
|
|
242
|
-
worker.busy = false;
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
};
|
|
246
|
-
|
|
247
|
-
const requestCloseListener = () => {
|
|
248
|
-
worker.postMessage({
|
|
249
|
-
type: WORKER_EVENT.WS_CONNECTION_CLOSE,
|
|
250
|
-
requestId,
|
|
251
|
-
event
|
|
252
|
-
});
|
|
253
|
-
if (request.socket && request.socket.off) request.socket.off('close', requestCloseListener);
|
|
254
|
-
worker.removeEventListener('message', messageListener);
|
|
255
|
-
};
|
|
256
|
-
request.socket.on('close', requestCloseListener);
|
|
257
|
-
|
|
258
|
-
worker.addEventListener('message', messageListener);
|
|
259
|
-
worker.postMessage({
|
|
260
|
-
type: WORKER_EVENT.REQUEST,
|
|
261
|
-
requestId,
|
|
262
|
-
event,
|
|
263
|
-
});
|
|
264
|
-
|
|
265
|
-
const cleanupConnection = () => {
|
|
266
|
-
worker.removeEventListener('message', messageListener);
|
|
267
|
-
if (request && request.off) {
|
|
268
|
-
request.off('close', cleanupConnection);
|
|
269
|
-
request.off('aborted', cleanupConnection);
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
if (request.socket && request.socket.off) {
|
|
273
|
-
request.socket.off('data', requestSocketListener);
|
|
274
|
-
request.socket.off('close', requestCloseListener);
|
|
275
|
-
}
|
|
276
|
-
};
|
|
277
|
-
request.on('aborted', cleanupConnection);
|
|
278
|
-
if (event.protocol === Protocols.http) {
|
|
279
|
-
request.on('close', cleanupConnection);
|
|
280
|
-
response.on('finish', cleanupConnection)
|
|
281
|
-
}
|
|
282
|
-
} catch (e) {
|
|
283
|
-
next(e);
|
|
284
|
-
}
|
|
285
|
-
};
|
|
286
|
-
};
|
|
287
|
-
|
|
288
|
-
module.exports = workerMiddleware;
|
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
const { WORKER_EVENT } = require('../constants');
|
|
2
|
-
|
|
3
|
-
/** @namespace Middleware */
|
|
4
|
-
|
|
5
|
-
/** @type {InvokableWorker} worker */
|
|
6
|
-
const worker = require(process.argv[2]);
|
|
7
|
-
|
|
8
|
-
/** @type {WorkerInputEvent} message */
|
|
9
|
-
function messageListener(message) {
|
|
10
|
-
if (message.type === WORKER_EVENT.REQUEST) {
|
|
11
|
-
process.send({
|
|
12
|
-
type: WORKER_EVENT.REQUEST_ACKNOWLEDGE,
|
|
13
|
-
requestId: message.requestId,
|
|
14
|
-
});
|
|
15
|
-
const callback = responseEvent => {
|
|
16
|
-
/** @type {WorkerOutputEvent} e */
|
|
17
|
-
const e = {
|
|
18
|
-
type: WORKER_EVENT.RESPONSE,
|
|
19
|
-
requestId: message.requestId,
|
|
20
|
-
event: responseEvent,
|
|
21
|
-
};
|
|
22
|
-
if (responseEvent.sendWsMessage) e.type = WORKER_EVENT.WS_MESSAGE_SEND;
|
|
23
|
-
if (responseEvent.emit) e.type = WORKER_EVENT.RESPONSE_EMIT;
|
|
24
|
-
process.send(e);
|
|
25
|
-
};
|
|
26
|
-
worker(message.event, callback);
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
if (message.type === WORKER_EVENT.WS_MESSAGE_RECEIVE) {
|
|
30
|
-
const callback = responseEvent => {
|
|
31
|
-
/** @type {WorkerOutputEvent} e */
|
|
32
|
-
const e = {
|
|
33
|
-
type: WORKER_EVENT.WS_MESSAGE_SEND,
|
|
34
|
-
requestId: message.requestId,
|
|
35
|
-
event: responseEvent,
|
|
36
|
-
}
|
|
37
|
-
process.send(e);
|
|
38
|
-
};
|
|
39
|
-
worker(message.event, callback);
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
if (message.type === WORKER_EVENT.WS_CONNECTION_CLOSE) {
|
|
43
|
-
/** @type {ResponseEvent} responseEvent */
|
|
44
|
-
worker({ ...message.event, closed: true }, responseEvent => {
|
|
45
|
-
process.send({
|
|
46
|
-
type: WORKER_EVENT.WS_CONNECTION_CLOSE_ACKNOWLEDGE,
|
|
47
|
-
requestId: message.requestId,
|
|
48
|
-
event: responseEvent,
|
|
49
|
-
});
|
|
50
|
-
});
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
process.on('message', messageListener);
|
package/nodemon.json
DELETED
package/scripts/version.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
const { execSync } = require('child_process');
|
|
2
|
-
|
|
3
|
-
const { TRAVIS_TAG, TRAVIS_BUILD_NUMBER } = process.env;
|
|
4
|
-
|
|
5
|
-
const now = new Date();
|
|
6
|
-
const version = `${(now.getFullYear() + '').substring(2)}.${((now.getMonth() + 1) + '').padStart(2, '0')}.${TRAVIS_BUILD_NUMBER}-${TRAVIS_TAG || 'release'}`;
|
|
7
|
-
|
|
8
|
-
execSync(`yarn version --no-git-tag-version --new-version "v${version}"`, { shell: true });
|
|
9
|
-
console.log('version set', version);
|