fix: occasional ERR_STREAM_PREMATURE_CLOSE uploading
Massimo Melina committed
Nov 4, 2024 at 11:02 UTC
fd5572ec61600621d5372b81d82e88b47ea911be
2 files changed
+9
-2
src/serveGuiAndSharedFiles.ts
+4
-2
@@ -6,7 +6,6 @@ import events from './events'
6
import { ADMIN_URI, FRONTEND_URI, HTTP_BAD_REQUEST, HTTP_FORBIDDEN, HTTP_METHOD_NOT_ALLOWED, HTTP_NOT_FOUND,
7
HTTP_UNAUTHORIZED, HTTP_SERVER_ERROR, HTTP_OK } from './cross-const'
8
import { uploadWriter } from './upload'
9
-import { pipeline } from 'stream/promises'
9
import formidable from 'formidable'
10
import { Writable } from 'stream'
11
import { serveFile, serveFileNode } from './serveFile'
@@ -48,7 +47,10 @@ export const serveGuiAndSharedFiles: Koa.Middleware = async (ctx, next) => {
47
ctx.state.uploadPath = decPath
48
const dest = uploadWriter(folder, rest, ctx)
49
if (dest) {
51
- void pipeline(ctx.req, dest)
50
+ ctx.req.pipe(dest).on('error', err => {
51
+ ctx.status = HTTP_SERVER_ERROR
52
+ ctx.body = err.message || String(err)
53
+ })
54
await dest.lockMiddleware // we need to wait more than just the stream
55
ctx.body = {}
56
}
src/upload.ts
+5
@@ -135,6 +135,10 @@ export function uploadWriter(base: VfsNode, path: string, ctx: Koa.Context) {
135
136
const fileStream = resuming ? fs.createWriteStream(resumable, { flags: 'r+', start: resume })
137
: fs.createWriteStream(tempName)
138
+ writeStream.on('error', e => {
139
+ releaseFile()
140
+ console.debug(e)
141
+ })
142
writeStream.pipe(fileStream)
143
Object.assign(obj, { fileStream })
144
trackProgress()
@@ -239,6 +243,7 @@ export function uploadWriter(base: VfsNode, path: string, ctx: Koa.Context) {
243
}
244
245
function fail(status?: number, msg?: string) {
246
+ console.debug('upload failed', status, msg)
247
releaseFile()
248
if (status)
249
ctx.status = status