Skip to content

Commit

Permalink
fix: randomize socket suffix (#120)
Browse files Browse the repository at this point in the history
* randomize socket suffix

* fix: test for getSocketPath
  • Loading branch information
Yoriki Yamaguchi authored and brettstack committed Feb 9, 2018
1 parent 55ea8fc commit f747eca
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
4 changes: 2 additions & 2 deletions __tests__/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ test('mapApiGatewayEventToHttpRequest: without headers', () => {
})

test('getSocketPath', () => {
const socketPath = awsServerlessExpress.getSocketPath(0)
expect(socketPath).toEqual('/tmp/server0.sock')
const socketPath = awsServerlessExpress.getSocketPath('12345abcdef')
expect(socketPath).toEqual('/tmp/server-12345abcdef.sock')
})

const PassThrough = require('stream').PassThrough
Expand Down
12 changes: 8 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,17 +139,21 @@ function startServer(server) {
function getSocketPath(socketPathSuffix) {
if (/^win/.test(process.platform)) {
const path = require('path')
return path.join('\\\\?\\pipe', process.cwd(), `server${socketPathSuffix}`)
return path.join('\\\\?\\pipe', process.cwd(), `server-${socketPathSuffix}`)
}
else {
return `/tmp/server${socketPathSuffix}.sock`
return `/tmp/server-${socketPathSuffix}.sock`
}
}

function getRandomString() {
return Math.random().toString(36).substring(2, 15)
}

function createServer (requestListener, serverListenCallback, binaryTypes) {
const server = http.createServer(requestListener)

server._socketPathSuffix = 0
server._socketPathSuffix = getRandomString()
server._binaryTypes = binaryTypes ? binaryTypes.slice() : []
server.on('listening', () => {
server._isListening = true
Expand All @@ -162,7 +166,7 @@ function createServer (requestListener, serverListenCallback, binaryTypes) {
.on('error', (error) => {
if (error.code === 'EADDRINUSE') {
console.warn(`WARNING: Attempting to listen on socket ${getSocketPath(server._socketPathSuffix)}, but it is already in use. This is likely as a result of a previous invocation error or timeout. Check the logs for the invocation(s) immediately prior to this for root cause, and consider increasing the timeout and/or cpu/memory allocation if this is purely as a result of a timeout. aws-serverless-express will restart the Node.js server listening on a new port and continue with this request.`)
++server._socketPathSuffix
server._socketPathSuffix = getRandomString()
return server.close(() => startServer(server))
}

Expand Down

0 comments on commit f747eca

Please sign in to comment.