Skip to content

Commit 6a2b9f5

Browse files
committed
Monkeypatch SocketWrapper, to survive but report if we do hit the WS bug
Hopefully this'll be fixed by the WS changes, but if not, this ensures we handle issues cleanly and can keep track of them. Hopefully later on we'll be able to remove this, if it never triggers.
1 parent abed417 commit 6a2b9f5

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

custom-typings/node-extensions.d.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Undocumented module that allows us to turn a stream into a usable net.Socket.
2+
// Deprecated in Node 12+, but useful in the meantime.
3+
declare module "_stream_wrap" {
4+
import * as net from 'net';
5+
import * as streams from 'stream';
6+
7+
class SocketWrapper extends net.Socket {
8+
constructor(stream: streams.Duplex);
9+
stream?: streams.Duplex & Partial<net.Socket>;
10+
}
11+
12+
export = SocketWrapper;
13+
}

src/index.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,3 +127,35 @@ export async function runHTK(options: {
127127
console.log('Server started in', Date.now() - certSetupTime, 'ms');
128128
console.log('Total startup took', Date.now() - startTime, 'ms');
129129
}
130+
131+
import SocketWrapper = require('_stream_wrap');
132+
133+
// Quick monkey-patches to guard against a bug in SocketWrapper that can break
134+
// some of the Mockttp internals in certain WS-based cases:
135+
const originalFinishShutdown = (<any>SocketWrapper.prototype).finishShutdown;
136+
(<any>SocketWrapper.prototype).finishShutdown = function (handle: any) {
137+
if (!handle) {
138+
// We still run the code anyway (since there are cases where it
139+
// might be fine, and we can't check them externally), but we
140+
// report issues, so we can work out how widespread this is.
141+
try {
142+
return originalFinishShutdown.apply(this, arguments);
143+
} catch (e) {
144+
reportError(e);
145+
return;
146+
}
147+
}
148+
else return originalFinishShutdown.apply(this, arguments);
149+
}
150+
const originalFinishWrite = (<any>SocketWrapper.prototype).finishWrite;
151+
(<any>SocketWrapper.prototype).finishWrite = function (handle: any) {
152+
if (!handle) {
153+
try {
154+
return originalFinishWrite.apply(this, arguments);
155+
} catch (e) {
156+
reportError(e);
157+
return;
158+
}
159+
}
160+
else return originalFinishWrite.apply(this, arguments);
161+
}

0 commit comments

Comments
 (0)