Skip to content

Commit

Permalink
Merge pull request #577 from oceanprotocol/issue-576-connection-close
Browse files Browse the repository at this point in the history
fix possible response with connection closed
  • Loading branch information
paulo-ocean authored Aug 1, 2024
2 parents d335681 + ac8583b commit b45d819
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
1 change: 1 addition & 0 deletions src/components/P2P/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,7 @@ export class OceanP2P extends EventEmitter {
} catch (e) {
response.status.httpStatus = 404
response.status.error = 'Cannot connect to peer'
P2P_LOGGER.log(LOG_LEVELS_STR.LEVEL_ERROR, `Unable to connect to peer: ${peerId}`)
return response
}

Expand Down
32 changes: 25 additions & 7 deletions src/components/httpRoutes/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,15 @@ directCommandRoute.post(
return
}

let closedResponse = false

// detect connection closed
res.on('close', () => {
if (!closedResponse) {
HTTP_LOGGER.error('TCP connection was closed before we could send a response!')
}
closedResponse = true
})
let isBinaryContent = false
const sink = async function (source: any) {
let first = true
Expand All @@ -63,18 +72,25 @@ directCommandRoute.post(
} catch (e) {
res.status(500)
res.write(uint8ArrayToString(chunk.subarray()))
closedResponse = true
res.end()
HTTP_LOGGER.error(e.message)
}
} else {
if (isBinaryContent) {
// Binary content, could be encrypted
res.write(chunk.subarray())
} else {
const str = uint8ArrayToString(chunk.subarray())
res.write(str)
try {
if (isBinaryContent) {
// Binary content, could be encrypted
res.write(chunk.subarray())
} else {
const str = uint8ArrayToString(chunk.subarray())
res.write(str)
}
} catch (e) {
HTTP_LOGGER.error(e.message)
}
}
}
closedResponse = true
res.end()
}

Expand Down Expand Up @@ -117,9 +133,11 @@ directCommandRoute.post(
}
}

if (response.stream == null) {
// only if response was not already sent
if (response.stream == null && !closedResponse) {
res.status(response.status.httpStatus)
res.write(response.status.error)
closedResponse = true
res.end()
}
}
Expand Down

0 comments on commit b45d819

Please sign in to comment.