fix(nextjs): Prevent false `API resolved without sending a response` warning (#4139)
fix(nextjs): Prevent false `API resolved without sending a response` warning (#4139)

This prevents a false positive warning from nextjs which arises from the interaction of our API route wrapper `withSentry()` with nextjs's native API route handling.

In dev, nextjs checks that API route handlers return a response to the client before they resolve, and it throws a warning[1] if this hasn't happened. Meanwhile, in `withSentry()`, we wrap the `res.end()` method to ensure that events are flushed before the request/response lifecycle finishes.

As a result, there are cases where the handler resolves before the response is finished, while flushing is still in progress. This triggers the warning mentioned above, but it's a false alarm - the response may not have ended _yet_, but it will end. This suppresses the warning by temporarily marking the response finished, and then restoring it to unfinished before the original `res.end()` is called.

The fix here is simple, but the async-i-ness of it all leads to some complex interactions in sequencing between the SDK, nextjs, and Node itself. I've tried to lay it out as clearly as I can in comments.

Fixes https://github.com/getsentry/sentry-javascript/issues/4007
Fixes https://github.com/getsentry/sentry-javascript/issues/3852

[1] https://github.com/vercel/next.js/blob/e1464ae5a5061ae83ad015018d4afe41f91978b6/packages/next/server/api-utils.ts#L106-L118
getsentry/raven-js,getsentry/raven-js,getsentry/raven-js,getsentry/raven-js