I have a heavy I/O process that I initiate in using an endpoint. That endpoint should immidiately respond to the client that the process has been started.
The heavy I/O task could take up-to 30mins so what I'm wondering is that in what state does the connection between server and client leave after res.json(...)? Is the socket connection still open / half-open? Should I in this case destory the socket manually after res.json(...)? Is is Ok that the heavyIO task fails after 29mins and goes to the express error handler? And finally; is this pattern incorrect e.g., should I process I/O tasks totally differently?
Below is a minimal example:
import express from 'express'
const app = express()
const asyncHandler = (handler) =>
(req, res, next) => Promise.resolve(handler(req, res, next)).catch(next)
const heavyIO = () =>
new Promise((resolve, reject) => setTimeout(() => Math.random() > 0.5 ? resolve() : reject('FAILED'), 1000))
app.get('/start', asyncHandler(async (_req, res) => {
// I want to be able to initiate the process and send back
// confirmation that the process has been started. I want the
// client to be able forget about this request.
res.json('ok...started process')
// Then we start to run the heavy IO process. Without the "await" this could
// lead to unhandled promise rejection.
// If this fails, the rejected promise will flow to express default
// error handling which is I think "finalhandler" by default.
// Because the headers as sent (res.headersSent === true) the error
// handler will log the error and destroy the socket connection.
// If this succeeds, the server will probably close the socket connection as well
// internally.
// Up until this point the socket has been open (or half-open?) so is this a problem?
// Does it mean that the client has been "up-keeping" this socket connection
// somehow or has/can it have been timed out before this succeeds or fails.
await heavyIO()
console.log(`FINISHED I/O at ${new Date().toISOString()}! Exiting handler...`)
}))
app.listen(8080)