-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
178 lines (145 loc) · 4.5 KB
/
index.js
File metadata and controls
178 lines (145 loc) · 4.5 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
const https = require('https');
//const https = require('http');
const stream = require('stream');
const EventEmitter = require('events');
const requestPrefix = 'pb-h-';
const responsePrefix = 'pb-h-';
class Server extends EventEmitter {
constructor() {
super();
if (arguments.length === 1) {
this._handler = arguments[0];
}
else if (arguments.length === 2) {
this._handler = arguments[1];
}
this.patchbayServer = 'patchbay.pub';
this.patchbayChannel = '/';
this.numWorkers = 1;
}
listen() {
for (let i = 0; i < this.numWorkers; i++) {
this.listenWorker(i);
}
}
async listenWorker(index) {
const rootUrl = this.patchbayServer + '/res' + this.patchbayChannel + '?switch=true';
const runLoop = async () => {
while (true) {
const randomChannelId = genRandomChannelId();
const switchResponse = await new Promise((resolve, reject) => {
const switchRequestOptions = {
method: 'POST',
};
if (this._authToken) {
switchRequestOptions.headers = {
'Pb-Token': this._authToken,
};
}
const switchRequest = https.request(rootUrl, switchRequestOptions, (res) => {
resolve(res);
});
switchRequest.on('error', (e) => {
console.error("Switch request error");
console.error(e);
// TODO: Will this leak memory from recursion?
setTimeout(runLoop, 3000);
});
switchRequest.write(randomChannelId);
switchRequest.end();
});
//const res = new stream.PassThrough();
const res = await new Promise((resolve, reject) => {
const url = this.patchbayServer + '/' + randomChannelId;
const serveRequest = https.request(url, {
method: 'POST'
}, (res) => {
// must consume according to node docs
res.resume();
//resolve(res);
});
resolve(serveRequest);
//res.pipe(serveRequest);
});
res.on('error', (e) => {
console.error("Generic res error");
console.error(e);
});
if (this._authToken) {
res.setHeader('Pb-Token', this._authToken);
}
const oldSetHeader = res.setHeader;
res.setHeader = function(name, value) {
oldSetHeader.call(res, responsePrefix + name, value);
};
// When statusCode is set, set the appropriate patchbay header to pass
// it through to the requester.
Object.defineProperty(res, 'statusCode', {
set: function(val) {
//this.setHeader('Pb-Status', String(val));
oldSetHeader.call(res, 'Pb-Status', String(val));
}
});
const resHeaders = {};
for (const headerName of Object.keys(switchResponse.headers)) {
if (headerName.startsWith(requestPrefix)) {
resHeaders[headerName.slice(requestPrefix.length)] = switchResponse.headers[headerName];
}
}
// TODO: might need to inherit from http.IncomingMessage
const req = {
headers: resHeaders,
method: switchResponse.headers['pb-method'],
url: switchResponse.headers['pb-uri'],
on: switchResponse.on.bind(switchResponse),
pipe: switchResponse.pipe.bind(switchResponse),
resume: switchResponse.resume.bind(switchResponse),
};
if (this._handler) {
this._handler(req, res);
}
this.emit('request', req, res);
}
};
await runLoop();
}
setPatchbayServer(server) {
this.patchbayServer = server;
}
setPatchbayChannel(channelId) {
if (!channelId.startsWith('/')) {
throw new Error("Invalid channelId");
}
this.patchbayChannel = channelId;
}
setNumWorkers(numWorkers) {
this.numWorkers = numWorkers;
}
setAuthToken(token) {
this._authToken = token;
}
}
function createServer() {
return new Server(...arguments);
}
function genRandomChannelId() {
const possible = "0123456789abcdefghijkmnpqrstuvwxyz";
function genCluster() {
let cluster = "";
for (let i = 0; i < 32; i++) {
const randIndex = Math.floor(Math.random() * possible.length);
cluster += possible[randIndex];
}
return cluster;
}
let id = "";
id += genCluster();
//id += '-';
//id += genCluster();
//id += '-';
//id += genCluster();
return id;
}
module.exports = {
createServer
};