Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Allow overriding the proxying for external rewrite #630

Merged
merged 12 commits into from
Nov 19, 2024
43 changes: 33 additions & 10 deletions packages/open-next/src/adapters/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import type { InternalEvent, Origin } from "types/open-next";
import { runWithOpenNextRequestContext } from "utils/promise";

import { debug } from "../adapters/logger";
import { debug, error } from "../adapters/logger";
import { createGenericHandler } from "../core/createGenericHandler";
import {
resolveIncrementalCache,
resolveOriginResolver,
resolveProxyRequest,
resolveQueue,
resolveTagCache,
} from "../core/resolve";
Expand All @@ -19,6 +20,10 @@ const defaultHandler = async (internalEvent: InternalEvent) => {
globalThis.openNextConfig.middleware?.originResolver,
);

const externalRequestProxy = await resolveProxyRequest(
globalThis.openNextConfig.middleware?.override?.proxyExternalRequest,
);

//#override includeCacheInMiddleware
globalThis.tagCache = await resolveTagCache(
globalThis.openNextConfig.middleware?.override?.tagCache,
Expand All @@ -40,17 +45,35 @@ const defaultHandler = async (internalEvent: InternalEvent) => {
const result = await routingHandler(internalEvent);
if ("internalEvent" in result) {
debug("Middleware intercepted event", internalEvent);
let origin: Origin | false = false;
if (!result.isExternalRewrite) {
origin = await originResolver.resolve(result.internalEvent.rawPath);
const origin = await originResolver.resolve(
result.internalEvent.rawPath,
);
return {
type: "middleware",
internalEvent: result.internalEvent,
isExternalRewrite: result.isExternalRewrite,
origin,
isISR: result.isISR,
};
}
try {
return externalRequestProxy.proxy(result.internalEvent);
} catch (e) {
error("External request failed.", e);
return {
type: "middleware",
internalEvent: {
...result.internalEvent,
rawPath: "/500",
url: "/500",
method: "GET",
},
isExternalRewrite: result.isExternalRewrite,
vicb marked this conversation as resolved.
Show resolved Hide resolved
origin: false,
isISR: result.isISR,
};
}
return {
type: "middleware",
internalEvent: result.internalEvent,
isExternalRewrite: result.isExternalRewrite,
origin,
isISR: result.isISR,
};
}

debug("Middleware response", result);
Expand Down
5 changes: 4 additions & 1 deletion packages/open-next/src/build/createMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,10 @@ export async function createMiddleware(
outfile: path.join(outputPath, "handler.mjs"),
middlewareInfo,
options,
overrides: config.middleware?.override,
overrides: {
...config.middleware.override,
originResolver: config.middleware.originResolver,
},
defaultConverter: "aws-cloudfront",
includeCache: config.dangerous?.enableCacheInterception,
additionalExternals: config.edgeExternals,
Expand Down
13 changes: 12 additions & 1 deletion packages/open-next/src/build/edge/createEdgeBundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@ import { build } from "esbuild";
import type { MiddlewareInfo, MiddlewareManifest } from "types/next-types";
import type {
IncludedConverter,
IncludedOriginResolver,
LazyLoadedOverride,
OverrideOptions,
RouteTemplate,
SplittedFunctionOptions,
} from "types/open-next";

import type { OriginResolver } from "types/overrides.js";
import logger from "../../logger.js";
import { openNextEdgePlugins } from "../../plugins/edge.js";
import { openNextReplacementPlugin } from "../../plugins/replacement.js";
Expand All @@ -23,7 +26,11 @@ interface BuildEdgeBundleOptions {
entrypoint: string;
outfile: string;
options: BuildOptions;
overrides?: OverrideOptions;
overrides?: OverrideOptions & {
originResolver?:
vicb marked this conversation as resolved.
Show resolved Hide resolved
| LazyLoadedOverride<OriginResolver>
| IncludedOriginResolver;
};
defaultConverter?: IncludedConverter;
additionalInject?: string;
includeCache?: boolean;
Expand Down Expand Up @@ -84,6 +91,10 @@ export async function buildEdgeBundle({
: "sqs-lite",
}
: {}),
originResolver:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add proxyExternalRequest

typeof overrides?.originResolver === "string"
? overrides.originResolver
: "pattern-env",
},
fnName: name,
}),
Expand Down
1 change: 1 addition & 0 deletions packages/open-next/src/build/validateConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const compatibilityMatrix: Record<IncludedWrapper, IncludedConverter[]> = {
"aws-lambda-streaming": ["aws-apigw-v2"],
cloudflare: ["edge"],
node: ["node"],
dummy: [],
};

function validateFunctionOptions(fnOptions: FunctionOptions) {
Expand Down
5 changes: 5 additions & 0 deletions packages/open-next/src/core/createMainHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { openNextHandler } from "./requestHandler";
import {
resolveConverter,
resolveIncrementalCache,
resolveProxyRequest,
resolveQueue,
resolveTagCache,
resolveWrapper,
Expand Down Expand Up @@ -33,6 +34,10 @@ export async function createMainHandler() {

globalThis.tagCache = await resolveTagCache(thisFunction.override?.tagCache);

globalThis.proxyExternalRequest = await resolveProxyRequest(
thisFunction.override?.proxyExternalRequest,
);

globalThis.lastModified = {};

// From the config, we create the converter
Expand Down
47 changes: 31 additions & 16 deletions packages/open-next/src/core/requestHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import { runWithOpenNextRequestContext } from "utils/promise";

import { debug, error, warn } from "../adapters/logger";
import { patchAsyncStorage } from "./patchAsyncStorage";
import { convertRes, createServerResponse, proxyRequest } from "./routing/util";
import { resolveProxyRequest } from "./resolve";
import { convertRes, createServerResponse } from "./routing/util";
import type { MiddlewareOutputEvent } from "./routingHandler";
import routingHandler, {
MIDDLEWARE_HEADER_PREFIX,
Expand Down Expand Up @@ -65,6 +66,34 @@ export async function openNextHandler(
delete headers[rawKey];
}

if (
"isExternalRewrite" in preprocessResult &&
preprocessResult.isExternalRewrite
conico974 marked this conversation as resolved.
Show resolved Hide resolved
) {
try {
preprocessResult = await globalThis.proxyExternalRequest.proxy(
preprocessResult.internalEvent,
);
} catch (e) {
error("External request failed.", e);
preprocessResult = {
internalEvent: {
type: "core",
rawPath: "/500",
method: "GET",
headers: {},
url: "/500",
query: {},
cookies: {},
remoteAddress: "",
},
isExternalRewrite: false,
vicb marked this conversation as resolved.
Show resolved Hide resolved
isISR: false,
origin: false,
};
}
}

if ("type" in preprocessResult) {
// response is used only in the streaming case
if (responseStreaming) {
Expand Down Expand Up @@ -110,20 +139,14 @@ export async function openNextHandler(
store.mergeHeadersPriority = mergeHeadersPriority;
}

const preprocessedResult = preprocessResult as MiddlewareOutputEvent;
const req = new IncomingMessage(reqProps);
const res = createServerResponse(
preprocessedEvent,
overwrittenResponseHeaders,
responseStreaming,
);

await processRequest(
req,
res,
preprocessedEvent,
preprocessedResult.isExternalRewrite,
);
await processRequest(req, res, preprocessedEvent);

const {
statusCode,
Expand Down Expand Up @@ -155,21 +178,13 @@ async function processRequest(
req: IncomingMessage,
res: OpenNextNodeResponse,
internalEvent: InternalEvent,
isExternalRewrite?: boolean,
) {
// @ts-ignore
// Next.js doesn't parse body if the property exists
// https://github.com/dougmoscrop/serverless-http/issues/227
delete req.body;

try {
// `serverHandler` is replaced at build time depending on user's
// nextjs version to patch Nextjs 13.4.x and future breaking changes.

if (isExternalRewrite) {
return proxyRequest(internalEvent, res);
}

//#override applyNextjsPrebundledReact
setNextjsPrebundledReact(internalEvent.rawPath);
//#endOverride
Expand Down
35 changes: 23 additions & 12 deletions packages/open-next/src/core/resolve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,13 @@ import type {
DefaultOverrideOptions,
InternalEvent,
InternalResult,
LazyLoadedOverride,
OpenNextConfig,
OverrideOptions,
} from "types/open-next";
import type {
Converter,
ImageLoader,
OriginResolver,
TagCache,
Warmer,
Wrapper,
} from "types/overrides";
import type { Converter, TagCache, Wrapper } from "types/overrides";

// Just a little utility type to remove undefined from a type
type RemoveUndefined<T> = T extends undefined ? never : T;

export async function resolveConverter<
E extends BaseEventOrResult = InternalEvent,
Expand Down Expand Up @@ -95,7 +91,7 @@ export async function resolveIncrementalCache(
* @__PURE__
*/
export async function resolveImageLoader(
imageLoader: LazyLoadedOverride<ImageLoader> | string,
imageLoader: RemoveUndefined<OpenNextConfig["imageOptimization"]>["loader"],
) {
if (typeof imageLoader === "function") {
return imageLoader();
Expand All @@ -109,7 +105,9 @@ export async function resolveImageLoader(
* @__PURE__
*/
export async function resolveOriginResolver(
originResolver?: LazyLoadedOverride<OriginResolver> | string,
originResolver: RemoveUndefined<
OpenNextConfig["middleware"]
>["originResolver"],
) {
if (typeof originResolver === "function") {
return originResolver();
Expand All @@ -122,11 +120,24 @@ export async function resolveOriginResolver(
* @__PURE__
*/
export async function resolveWarmerInvoke(
warmer?: LazyLoadedOverride<Warmer> | "aws-lambda",
warmer: RemoveUndefined<OpenNextConfig["warmer"]>["invokeFunction"],
) {
if (typeof warmer === "function") {
return warmer();
}
const m_1 = await import("../overrides/warmer/aws-lambda.js");
return m_1.default;
}

/**
* @__PURE__
*/
export async function resolveProxyRequest(
proxyRequest: OverrideOptions["proxyExternalRequest"],
) {
if (typeof proxyRequest === "function") {
return proxyRequest();
}
const m_1 = await import("../overrides/proxyExternalRequest/node.js");
return m_1.default;
}
Loading
Loading