Skip to content

Commit f747eca

Browse files
Yoriki Yamaguchibrettstack
authored andcommitted
fix: randomize socket suffix (#120)
* randomize socket suffix * fix: test for getSocketPath
1 parent 55ea8fc commit f747eca

File tree

2 files changed

+10
-6
lines changed

2 files changed

+10
-6
lines changed

__tests__/index.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,8 +91,8 @@ test('mapApiGatewayEventToHttpRequest: without headers', () => {
9191
})
9292

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

9898
const PassThrough = require('stream').PassThrough

index.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -139,17 +139,21 @@ function startServer(server) {
139139
function getSocketPath(socketPathSuffix) {
140140
if (/^win/.test(process.platform)) {
141141
const path = require('path')
142-
return path.join('\\\\?\\pipe', process.cwd(), `server${socketPathSuffix}`)
142+
return path.join('\\\\?\\pipe', process.cwd(), `server-${socketPathSuffix}`)
143143
}
144144
else {
145-
return `/tmp/server${socketPathSuffix}.sock`
145+
return `/tmp/server-${socketPathSuffix}.sock`
146146
}
147147
}
148148

149+
function getRandomString() {
150+
return Math.random().toString(36).substring(2, 15)
151+
}
152+
149153
function createServer (requestListener, serverListenCallback, binaryTypes) {
150154
const server = http.createServer(requestListener)
151155

152-
server._socketPathSuffix = 0
156+
server._socketPathSuffix = getRandomString()
153157
server._binaryTypes = binaryTypes ? binaryTypes.slice() : []
154158
server.on('listening', () => {
155159
server._isListening = true
@@ -162,7 +166,7 @@ function createServer (requestListener, serverListenCallback, binaryTypes) {
162166
.on('error', (error) => {
163167
if (error.code === 'EADDRINUSE') {
164168
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.`)
165-
++server._socketPathSuffix
169+
server._socketPathSuffix = getRandomString()
166170
return server.close(() => startServer(server))
167171
}
168172

0 commit comments

Comments
 (0)