sharp
sharp copied to clipboard
Permanent Promise Hang & Memory Leak on Stream Errors / Destruction
- Severity: 🟠 High (Production Resource Exhaustion / Unresolved Promises)
- Target Files:
lib/input.mjslib/output.mjslib/constructor.mjs
Description & Root Cause
When image data is piped into sharp, asynchronous operations await stream completion using _whenStreamInFinished:
function _whenStreamInFinished (fn) {
if (this.writableFinished) {
fn();
} else {
this.once('finish', fn);
}
}
In Node.js Streams:
- If a readable source aborts, network connection drops during client upload, or
stream.destroy(err)is invoked, an errored/destroyed stream never emits'finish'. this.writableFinishedremainsfalse.this.once('finish', fn)will never fire.- Any caller awaiting
await sharpStream.toBuffer(),.toFile(),.metadata(), or.stats()will hang indefinitely.
Reproduction Proof-of-Concept
import sharp from 'sharp';
const transformer = sharp();
transformer.on('error', () => {}); // listener attached
const promise = transformer.toBuffer();
transformer.destroy(new Error('Simulated network disconnect'));
// The promise hangs forever; neither .then() nor .catch() is ever called.
Recommended Fix
Update _whenStreamInFinished to accept an error handler and monitor 'error' and 'close':
function _whenStreamInFinished (fn, errFn) {
if (this.writableFinished) {
fn();
} else if (this.destroyed || this.errored) {
if (errFn) errFn(this.errored || new Error('Stream was destroyed before finishing'));
} else {
const onFinish = () => {
this.removeListener('error', onError);
this.removeListener('close', onClose);
fn();
};
const onError = (err) => {
this.removeListener('finish', onFinish);
this.removeListener('close', onClose);
if (errFn) errFn(err);
};
const onClose = () => {
if (!this.writableFinished) {
onError(this.errored || new Error('Stream closed prematurely'));
}
};
this.once('finish', onFinish);
this.once('error', onError);
this.once('close', onClose);
}
}
The "Reproduction Proof-of-Concept" provided doesn't hang, it triggers the error handler as you'd expect. Anything else is API misuse of a Stream's destroy() function. Please verify the output of LLM-based tooling.