Skip to content

Commit 36dc966

Browse files
committed
fix: race condition and buffer issue in puter.http
The call to sock.write() wasn't waiting for the 'open' event, which worked fine over non-TLS sockets by chance. Also, responses with only a single WISP packet were resulting in buffered response data not being sent to the caller.
1 parent 3f5b34c commit 36dc966

File tree

1 file changed

+24
-14
lines changed

1 file changed

+24
-14
lines changed

src/puter-js/src/lib/http.js

+24-14
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,11 @@ export const make_http_api = ({ Socket, DEFAULT_PORT }) => {
1919
const api = {};
2020

2121
api.request = (options, callback) => {
22-
const sock = new Socket(options.hostname, options.port ?? DEFAULT_PORT);
2322
const encoder = new TextEncoder();
2423
const decoder = new TextDecoder();
2524

25+
let sock;
26+
2627
// Request object
2728
const req = new HTTPRequest([
2829
'data',
@@ -128,18 +129,6 @@ export const make_http_api = ({ Socket, DEFAULT_PORT }) => {
128129
}
129130
};
130131
let state = STATE_HEADERS;
131-
132-
sock.on('data', (data) => {
133-
state.data(data);
134-
});
135-
136-
sock.on('error', (err) => {
137-
req.emit('error', err);
138-
});
139-
140-
sock.on('close', () => {
141-
res.emit('end');
142-
});
143132

144133
// Construct and send HTTP request
145134
const method = options.method || 'GET';
@@ -164,7 +153,28 @@ export const make_http_api = ({ Socket, DEFAULT_PORT }) => {
164153
requestString += options.data;
165154
}
166155

167-
sock.write(encoder.encode(requestString));
156+
sock = new Socket(options.hostname, options.port ?? DEFAULT_PORT);
157+
158+
sock.on('data', (data) => {
159+
console.log('data event', data);
160+
state.data(data);
161+
});
162+
sock.on('open', () => {
163+
sock.write(encoder.encode(requestString));
164+
});
165+
sock.on('error', (err) => {
166+
req.emit('error', err);
167+
});
168+
sock.on('close', () => {
169+
if ( buffer ) {
170+
console.log('close with buffer', buffer);
171+
const bin = encoder.encode(buffer);
172+
buffer = '';
173+
state.data(bin);
174+
}
175+
res.emit('end');
176+
});
177+
168178

169179
return req;
170180
};

0 commit comments

Comments
 (0)