Skip to content

Commit

Permalink
fix: fix leaking promise
Browse files Browse the repository at this point in the history
  • Loading branch information
nitedani committed Aug 7, 2024
1 parent d0a1187 commit 052d16a
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 42 deletions.
27 changes: 11 additions & 16 deletions packages/vike-node/src/runtime/adapters/connectToWeb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,22 +31,17 @@ function connectToWeb(handler: ConnectMiddleware): WebHandler {
const { res, onReadable } = createServerResponse(req)

return new Promise<Response | undefined>((resolve, reject) => {
;(async () => {
try {
const { readable, headers, statusCode } = await onReadable
const responseBody = statusCodesWithoutBody.includes(statusCode)
? null
: (Readable.toWeb(readable) as ReadableStream)
resolve(
new Response(responseBody, {
status: statusCode,
headers: flattenHeaders(headers)
})
)
} catch (error) {
reject(error instanceof Error ? error : new Error('Error creating response'))
}
})()
onReadable(({ readable, headers, statusCode }) => {
const responseBody = statusCodesWithoutBody.includes(statusCode)
? null
: (Readable.toWeb(readable) as ReadableStream)
resolve(
new Response(responseBody, {
status: statusCode,
headers: flattenHeaders(headers)
})
)
})

const next = (error?: unknown) => {
if (error) {
Expand Down
32 changes: 16 additions & 16 deletions packages/vike-node/src/runtime/adapters/createServerResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,35 +7,35 @@ import { PassThrough, Readable } from 'stream'
* Creates a custom ServerResponse object that allows for intercepting and streaming the response.
*
* @param {IncomingMessage} incomingMessage - The incoming HTTP request message.
* @returns {{ res: ServerResponse; onReadable: Promise<{ readable: Readable; headers: OutgoingHttpHeaders; statusCode: number }> }}
* @returns {{
* res: ServerResponse;
* onReadable: (cb: (result: { readable: Readable; headers: OutgoingHttpHeaders; statusCode: number }) => void) => void
* }}
* An object containing:
* - res: The custom ServerResponse object.
* - onReadable: A promise that resolves when the response is readable, providing the readable stream, headers, and status code.
* - onReadable: A function that takes a callback. The callback is invoked when the response is readable,
* providing an object with the readable stream, headers, and status code.
*/
function createServerResponse(incomingMessage: IncomingMessage) {
const res = new ServerResponse(incomingMessage)
const passThrough = new PassThrough()
const onReadable = new Promise<{ readable: Readable; headers: OutgoingHttpHeaders; statusCode: number }>(
(resolve, reject) => {
const handleReadable = () => {
resolve({ readable: Readable.from(passThrough), headers: res.getHeaders(), statusCode: res.statusCode })
}

const handleError = (err: Error) => {
reject(err)
}

passThrough.once('readable', handleReadable)
passThrough.once('end', handleReadable)
passThrough.once('error', handleError)
res.once('error', handleError)
const onReadable = (
cb: (result: { readable: Readable; headers: OutgoingHttpHeaders; statusCode: number }) => void
) => {
const handleReadable = () => {
cb({ readable: Readable.from(passThrough), headers: res.getHeaders(), statusCode: res.statusCode })
}
)

passThrough.once('readable', handleReadable)
passThrough.once('end', handleReadable)
}

passThrough.once('finish', () => {
res.emit('finish')
})
passThrough.once('close', () => {
res.destroy()
res.emit('close')
})
passThrough.on('drain', () => {
Expand Down
7 changes: 3 additions & 4 deletions packages/vike-node/src/runtime/frameworks/fastify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ export { vike }

import type { FastifyPluginCallback, FastifyRequest } from 'fastify'
import { createServerResponse } from '../adapters/createServerResponse.js'
import { globalStore } from '../globalStore.js'
import { createHandler } from '../handler.js'
import type { VikeOptions } from '../types.js'
import { globalStore } from '../globalStore.js'

/**
* Creates a Fastify plugin to handle Vike requests and Hot Module Replacement (HMR).
Expand Down Expand Up @@ -36,12 +36,11 @@ function vike(options?: VikeOptions<FastifyRequest>): FastifyPluginCallback {
instance.get('*', async (req, reply) => {
globalStore.setupHMRProxy(req.raw)
const { res, onReadable } = createServerResponse(req.raw)
;(async () => {
const { readable, headers, statusCode } = await onReadable
onReadable(({ readable, headers, statusCode }) => {
reply.code(statusCode)
reply.headers(headers)
reply.send(readable)
})()
})
await handler({
req: req.raw,
res,
Expand Down
13 changes: 7 additions & 6 deletions packages/vike-node/src/runtime/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,6 @@ import { globalStore } from './globalStore.js'
import type { ConnectMiddleware, VikeOptions } from './types.js'
import { writeHttpResponse } from './utils/writeHttpResponse.js'

const argv1 = process.argv[1]
const entrypointDirAbs = argv1
? dirname(isAbsolute(argv1) ? argv1 : join(process.cwd(), argv1))
: dirname(fileURLToPath(import.meta.url))
const defaultStaticDir = join(entrypointDirAbs, '..', 'client')

export function createHandler<PlatformRequest>(options: VikeOptions<PlatformRequest> = {}) {
const staticConfig = resolveStaticConfig(options.static)
const shouldCache = staticConfig && staticConfig.cache
Expand Down Expand Up @@ -124,6 +118,13 @@ function resolveStaticConfig(static_: VikeOptions['static']): false | { root: st
// See vercel.json > outputDirectory
if (process.env.VERCEL) return false
if (static_ === false) return false

const argv1 = process.argv[1]
const entrypointDirAbs = argv1
? dirname(isAbsolute(argv1) ? argv1 : join(process.cwd(), argv1))
: dirname(fileURLToPath(import.meta.url))
const defaultStaticDir = join(entrypointDirAbs, '..', 'client')

if (static_ === true || static_ === undefined) {
return { root: defaultStaticDir, cache: true }
}
Expand Down

0 comments on commit 052d16a

Please sign in to comment.