Skip to content

Commit

Permalink
clean up init result
Browse files Browse the repository at this point in the history
  • Loading branch information
lubieowoce committed Nov 22, 2024
1 parent cf8320c commit ed871e1
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 48 deletions.
46 changes: 24 additions & 22 deletions packages/next/src/server/lib/render-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@ import type { PropagateToWorkersField } from './router-utils/types'
import next from '../next'
import type { Span } from '../../trace'

type InitializationResult = {
export type ServerInitResult = {
requestHandler: RequestHandler
upgradeHandler: UpgradeHandler
app: NextServer
server: NextServer
}

let initializations: Record<string, Promise<InitializationResult> | undefined> =
{}
let initializations: Record<string, Promise<ServerInitResult> | undefined> = {}

let sandboxContext: undefined | typeof import('../web/sandbox/context')

Expand All @@ -36,9 +35,9 @@ export async function getServerField(
if (!initialization) {
throw new Error('Invariant cant propagate server field, no app initialized')
}
const { app } = initialization
let appField = (app as any).server
return appField[field]
const { server } = initialization
let wrappedServer = server['server']! // NextServer.server is private
return wrappedServer[field as keyof typeof wrappedServer]
}

export async function propagateServerField(
Expand All @@ -50,17 +49,20 @@ export async function propagateServerField(
if (!initialization) {
throw new Error('Invariant cant propagate server field, no app initialized')
}
const { app } = initialization
let appField = (app as any).server

if (appField) {
if (typeof appField[field] === 'function') {
await appField[field].apply(
(app as any).server,
const { server } = initialization
let wrappedServer = server['server']
const _field = field as keyof NonNullable<typeof wrappedServer>

if (wrappedServer) {
if (typeof wrappedServer[_field] === 'function') {
// @ts-expect-error
await wrappedServer[_field].apply(
wrappedServer,
Array.isArray(value) ? value : []
)
} else {
appField[field] = value
// @ts-expect-error
wrappedServer[_field] = value
}
}
}
Expand All @@ -81,7 +83,7 @@ async function initializeImpl(opts: {
bundlerService: DevBundlerService | undefined
startServerSpan: Span | undefined
quiet?: boolean
}) {
}): Promise<ServerInitResult> {
const type = process.env.__NEXT_PRIVATE_RENDER_WORKER
if (type) {
process.title = 'next-render-worker-' + type
Expand All @@ -90,28 +92,28 @@ async function initializeImpl(opts: {
let requestHandler: RequestHandler
let upgradeHandler: UpgradeHandler

const app = next({
const server = next({
...opts,
hostname: opts.hostname || 'localhost',
customServer: false,
httpServer: opts.server,
port: opts.port,
}) as NextServer // should return a NextServer when `customServer: false`
requestHandler = app.getRequestHandler()
upgradeHandler = app.getUpgradeHandler()
requestHandler = server.getRequestHandler()
upgradeHandler = server.getUpgradeHandler()

await app.prepare(opts.serverFields)
await server.prepare(opts.serverFields)

return {
requestHandler,
upgradeHandler,
app,
server,
}
}

export async function initialize(
opts: Parameters<typeof initializeImpl>[0]
): Promise<InitializationResult> {
): Promise<ServerInitResult> {
// if we already setup the server return as we only need to do
// this on first worker boot
if (initializations[opts.dir]) {
Expand Down
6 changes: 3 additions & 3 deletions packages/next/src/server/lib/router-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import type { WorkerRequestHandler, WorkerUpgradeHandler } from './types'
import type { DevBundler, ServerFields } from './router-utils/setup-dev-bundler'
import type { NextUrlWithParsedQuery, RequestMeta } from '../request-meta'
import type { NextServer } from '../next'

// This is required before other imports to ensure the require hook is setup.
import '../node-environment'
Expand Down Expand Up @@ -47,6 +46,7 @@ import {
} from '../dev/hot-reloader-types'
import { normalizedAssetPrefix } from '../../shared/lib/normalized-asset-prefix'
import { NEXT_PATCH_SYMBOL } from './patch-fetch'
import type { ServerInitResult } from './render-server'

const debug = setupDebug('next:router-server:main')
const isNextFont = (pathname: string | null) =>
Expand Down Expand Up @@ -79,7 +79,7 @@ export async function initialize(opts: {
experimentalHttpsServer?: boolean
startServerSpan?: Span
quiet?: boolean
}): Promise<[WorkerRequestHandler, WorkerUpgradeHandler, NextServer]> {
}): Promise<ServerInitResult> {
if (!process.env.NODE_ENV) {
// @ts-ignore not readonly
process.env.NODE_ENV = opts.dev ? 'development' : 'production'
Expand Down Expand Up @@ -739,5 +739,5 @@ export async function initialize(opts: {
}
}

return [requestHandler, upgradeHandler, handlers.app]
return { requestHandler, upgradeHandler, server: handlers.server }
}
4 changes: 2 additions & 2 deletions packages/next/src/server/lib/start-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -334,8 +334,8 @@ export async function startServer(
keepAliveTimeout,
experimentalHttpsServer: !!selfSignedCertificate,
})
requestHandler = initResult[0]
upgradeHandler = initResult[1]
requestHandler = initResult.requestHandler
upgradeHandler = initResult.upgradeHandler

const startServerProcessDuration =
performance.mark('next-start-end') &&
Expand Down
34 changes: 13 additions & 21 deletions packages/next/src/server/next.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import type { UrlWithParsedQuery } from 'url'
import type { IncomingMessage, ServerResponse } from 'http'
import type { Duplex } from 'stream'
import type { NextUrlWithParsedQuery } from './request-meta'
import type { WorkerRequestHandler, WorkerUpgradeHandler } from './lib/types'

import './require-hook'
import './node-polyfill-crypto'
Expand All @@ -26,6 +25,7 @@ import { getTracer } from './lib/trace/tracer'
import { NextServerSpan } from './lib/trace/constants'
import { formatUrl } from '../shared/lib/router/utils/format-url'
import type { ServerFields } from './lib/router-utils/setup-dev-bundler'
import type { ServerInitResult } from './lib/render-server'

let ServerImpl: typeof NextNodeServer

Expand Down Expand Up @@ -303,11 +303,7 @@ class NextCustomServer implements NextWrapperServer {
private didWebSocketSetup: boolean = false
protected cleanupListeners: (() => Promise<void>)[] = []

protected init?: {
requestHandler: WorkerRequestHandler
upgradeHandler: WorkerUpgradeHandler
renderServer: NextServer
}
protected init?: ServerInitResult

public options: NextServerOptions

Expand All @@ -330,8 +326,8 @@ class NextCustomServer implements NextWrapperServer {
protected get upgradeHandler() {
return this.getInit().upgradeHandler
}
protected get renderServer() {
return this.getInit().renderServer
protected get server() {
return this.getInit().server
}

get hostname() {
Expand All @@ -355,11 +351,7 @@ class NextCustomServer implements NextWrapperServer {
minimalMode: this.options.minimalMode,
quiet: this.options.quiet,
})
this.init = {
requestHandler: initResult[0],
upgradeHandler: initResult[1],
renderServer: initResult[2],
}
this.init = initResult
}

private setupWebSocketHandler(
Expand Down Expand Up @@ -415,38 +407,38 @@ class NextCustomServer implements NextWrapperServer {
}

setAssetPrefix(assetPrefix: string): void {
this.renderServer.setAssetPrefix(assetPrefix)
this.server.setAssetPrefix(assetPrefix)
}

getUpgradeHandler(): UpgradeHandler {
return this.renderServer.getUpgradeHandler()
return this.server.getUpgradeHandler()
}

logError(...args: Parameters<NextWrapperServer['logError']>) {
this.renderServer.logError(...args)
this.server.logError(...args)
}

async renderToHTML(...args: Parameters<NextWrapperServer['renderToHTML']>) {
return this.renderServer.renderToHTML(...args)
return this.server.renderToHTML(...args)
}

async renderError(...args: Parameters<NextWrapperServer['renderError']>) {
return this.renderServer.renderError(...args)
return this.server.renderError(...args)
}

async renderErrorToHTML(
...args: Parameters<NextWrapperServer['renderErrorToHTML']>
) {
return this.renderServer.renderErrorToHTML(...args)
return this.server.renderErrorToHTML(...args)
}

async render404(...args: Parameters<NextWrapperServer['render404']>) {
return this.renderServer.render404(...args)
return this.server.render404(...args)
}

async close() {
await Promise.all([
this.init?.renderServer.close(),
this.init?.server.close(),
...this.cleanupListeners.map((f) => f()),
])
}
Expand Down

0 comments on commit ed871e1

Please sign in to comment.