36 lines
1.3 KiB
JavaScript
36 lines
1.3 KiB
JavaScript
"use strict";
|
|
|
|
function destroyStreams(...streams) {
|
|
for (const stream of streams) {
|
|
if (!stream || stream.destroyed || typeof stream.destroy !== "function") continue;
|
|
try { stream.destroy(); } catch { }
|
|
}
|
|
}
|
|
|
|
function releaseFailedUpload(result, source, request) {
|
|
// adpanel:upload-failure-lifecycle - a completed failure has no consumer;
|
|
// stop its source and downstream socket instead of retaining a paused body.
|
|
if (Number(result?.status) !== 200 || !result?.json?.ok) destroyStreams(source, request);
|
|
}
|
|
|
|
function onPrematureClose(source, onFailure) {
|
|
// adpanel:upload-source-close - close without end is not completion and
|
|
// must release the downstream upload even when no error event accompanies it.
|
|
const check = () => {
|
|
if (!source.readableEnded) onFailure(source.errored || new Error("Upload source closed before end"));
|
|
};
|
|
source.once("close", check);
|
|
if (source.destroyed) check();
|
|
}
|
|
|
|
function cancelUpstreamOnClose(sink, response, request, onCancel) {
|
|
sink.once("close", () => {
|
|
if (sink.readableEnded) return;
|
|
// adpanel:download-consumer-cancel - downstream cancellation owns the
|
|
// upstream exchange too, even when backpressure has paused the response.
|
|
onCancel();
|
|
destroyStreams(response, request);
|
|
});
|
|
}
|
|
|
|
module.exports = { destroyStreams, releaseFailedUpload, onPrematureClose, cancelUpstreamOnClose }; |