diff --git a/lib/utils/device/api.ts b/lib/utils/device/api.ts index 08ecec36..c103c72c 100644 --- a/lib/utils/device/api.ts +++ b/lib/utils/device/api.ts @@ -16,6 +16,8 @@ */ import * as Bluebird from 'bluebird'; import * as _ from 'lodash'; +import { NodeJSSocketWithFileDescriptor } from 'net-keepalive'; +import * as os from 'os'; import * as request from 'request'; import * as Stream from 'stream'; @@ -175,7 +177,7 @@ export class DeviceAPI { return new Bluebird((resolve, reject) => { const req = request.get(url); - req.on('error', reject).on('response', res => { + req.on('error', reject).on('response', async res => { if (res.statusCode !== 200) { reject( new ApiErrors.DeviceAPIError( @@ -183,6 +185,18 @@ export class DeviceAPI { ), ); } + res.socket.setKeepAlive(true, 1000); + if (os.platform() !== 'win32') { + const NetKeepalive = await import('net-keepalive'); + // Certain versions of typescript won't convert + // this automatically + const sock = (res.socket as any) as NodeJSSocketWithFileDescriptor; + // We send a tcp keepalive probe once every 5 seconds + NetKeepalive.setKeepAliveInterval(sock, 5000); + // After 5 failed probes, the connection is marked as + // closed + NetKeepalive.setKeepAliveProbes(sock, 5); + } resolve(res); }); }); diff --git a/lib/utils/device/logs.ts b/lib/utils/device/logs.ts index 6e3b4203..165cd915 100644 --- a/lib/utils/device/logs.ts +++ b/lib/utils/device/logs.ts @@ -45,7 +45,10 @@ export function displayDeviceLogs( }); logs.on('error', reject); - logs.on('end', resolve); + logs.on('end', () => { + logger.logError('Connection to device lost'); + resolve(); + }); }); } diff --git a/package.json b/package.json index c7ed1977..8da02cdc 100644 --- a/package.json +++ b/package.json @@ -74,6 +74,7 @@ "@types/lodash": "4.14.112", "@types/mixpanel": "2.14.0", "@types/mkdirp": "0.5.2", + "@types/net-keepalive": "^0.4.0", "@types/node": "6.14.2", "@types/prettyjson": "0.0.28", "@types/raven": "2.5.1", @@ -186,6 +187,7 @@ "window-size": "^1.1.0" }, "optionalDependencies": { + "net-keepalive": "^1.2.1", "removedrive": "^1.0.0", "windosu": "^0.2.0" }