1
1
import type { OutgoingHttpHeaders } from 'http'
2
2
3
3
import { ComputeJsOutgoingMessage , toComputeResponse , toReqRes } from '@fastly/http-compute-js'
4
- import { Context } from '@netlify/functions'
5
4
import type { NextConfigComplete } from 'next/dist/server/config-shared.js'
6
5
import type { WorkerRequestHandler } from 'next/dist/server/lib/types.js'
7
6
@@ -16,10 +15,12 @@ import { nextResponseProxy } from '../revalidate.js'
16
15
17
16
import { createRequestContext , getLogger , getRequestContext } from './request-context.cjs'
18
17
import { getTracer } from './tracer.cjs'
19
- import { setWaitUntil } from './wait-until.cjs'
18
+ import { setupWaitUntil } from './wait-until.cjs'
20
19
21
20
const nextImportPromise = import ( '../next.cjs' )
22
21
22
+ setupWaitUntil ( )
23
+
23
24
let nextHandler : WorkerRequestHandler , nextConfig : NextConfigComplete
24
25
25
26
/**
@@ -45,15 +46,9 @@ const disableFaultyTransferEncodingHandling = (res: ComputeJsOutgoingMessage) =>
45
46
}
46
47
}
47
48
48
- // TODO: remove once https://github.com/netlify/serverless-functions-api/pull/219
49
- // is released and public types are updated
50
- interface FutureContext extends Context {
51
- waitUntil ?: ( promise : Promise < unknown > ) => void
52
- }
53
-
54
- export default async ( request : Request , context : FutureContext ) => {
49
+ export default async ( request : Request ) => {
55
50
const tracer = getTracer ( )
56
- setWaitUntil ( context )
51
+
57
52
if ( ! nextHandler ) {
58
53
await tracer . withActiveSpan ( 'initialize next server' , async ( ) => {
59
54
// set the server config
@@ -129,19 +124,19 @@ export default async (request: Request, context: FutureContext) => {
129
124
return new Response ( body || null , response )
130
125
}
131
126
132
- if ( context . waitUntil ) {
133
- context . waitUntil ( requestContext . backgroundWorkPromise )
134
- }
135
-
136
127
const keepOpenUntilNextFullyRendered = new TransformStream ( {
137
128
async flush ( ) {
138
129
// it's important to keep the stream open until the next handler has finished
139
130
await nextHandlerPromise
140
- if ( ! context . waitUntil ) {
141
- // if waitUntil is not available, we have to keep response stream open until background promises are resolved
142
- // to ensure that all background work executes
143
- await requestContext . backgroundWorkPromise
144
- }
131
+
132
+ // Next.js relies on `close` event emitted by response to trigger running callback variant of `next/after`
133
+ // however @fastly /http-compute-js never actually emits that event - so we have to emit it ourselves,
134
+ // otherwise Next would never run the callback variant of `next/after`
135
+ res . emit ( 'close' )
136
+
137
+ // if waitUntil is not available, we have to keep response stream open until background promises are resolved
138
+ // to ensure that all background work executes
139
+ await requestContext . backgroundWorkPromise
145
140
} ,
146
141
} )
147
142
0 commit comments