Skip to content

Commit

Permalink
Use name-value tuples for headers (#3848)
Browse files Browse the repository at this point in the history
This is a small cleanup extracted out of the WIP `basePath` PR.
  • Loading branch information
jridgewell authored Feb 17, 2023
1 parent c2dc79a commit 78b442e
Show file tree
Hide file tree
Showing 12 changed files with 43 additions and 20 deletions.
2 changes: 1 addition & 1 deletion crates/next-core/js/src/entry/app-renderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import "@vercel/turbopack-next/polyfill/async-local-storage";
import { RenderOpts, renderToHTMLOrFlight } from "next/dist/server/app-render";
import { PassThrough } from "stream";
import { ServerResponseShim } from "@vercel/turbopack-next/internal/http";
import { headersFromEntries } from "@vercel/turbopack-next/internal/utils";
import { headersFromEntries } from "@vercel/turbopack-next/internal/headers";
import { parse, ParsedUrlQuery } from "node:querystring";

globalThis.__next_require__ = (data) => {
Expand Down
12 changes: 6 additions & 6 deletions crates/next-core/js/src/entry/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { IncomingMessage, ServerResponse } from "node:http";
import { Buffer } from "node:buffer";
import { join } from "node:path";
import { createServer, makeRequest } from "@vercel/turbopack-next/ipc/server";
import { toPairs } from "@vercel/turbopack-next/internal/headers";
import { makeResolver } from "next/dist/server/router.js";
import loadConfig from "next/dist/server/config";
import { PHASE_DEVELOPMENT_SERVER } from "next/dist/shared/lib/constants";
Expand All @@ -14,8 +15,7 @@ import middlewareChunkGroup from "MIDDLEWARE_CHUNK_GROUP";
type RouterRequest = {
method: string;
pathname: string;
// TODO: not passed to request
rawHeaders: Array<[string, string]>;
rawHeaders: [string, string][];
rawQuery: string;
};

Expand Down Expand Up @@ -49,12 +49,12 @@ type MessageData =

type RewriteResponse = {
url: string;
headers: string[];
headers: [string, string][];
};

type MiddlewareHeadersResponse = {
statusCode: number;
headers: string[];
headers: [string, string][];
};

let resolveRouteMemo: Promise<
Expand Down Expand Up @@ -166,15 +166,15 @@ async function handleClientResponse(
type: "rewrite",
data: {
url: data.url,
headers: Object.entries(data.headers).flat(),
headers: Object.entries(data.headers),
},
};
}
}

const responseHeaders: MiddlewareHeadersResponse = {
statusCode: clientResponse.statusCode!,
headers: clientResponse.rawHeaders,
headers: toPairs(clientResponse.rawHeaders),
};

// TODO: support streaming middleware
Expand Down
5 changes: 3 additions & 2 deletions crates/next-core/js/src/internal/api-server-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { Ipc } from "@vercel/turbopack-next/ipc/index";
import type { ClientRequest, IncomingMessage, Server } from "node:http";
import type { ServerResponse } from "node:http";
import { createServer, makeRequest } from "@vercel/turbopack-next/ipc/server";
import { toPairs } from "@vercel/turbopack-next/internal/headers";
import { Buffer } from "node:buffer";

const ipc = IPC as Ipc<IpcIncomingMessage, IpcOutgoingMessage>;
Expand Down Expand Up @@ -34,7 +35,7 @@ type IpcOutgoingMessage =

type ResponseHeaders = {
status: number;
headers: string[];
headers: [string, string][];
};

type Handler = (data: {
Expand Down Expand Up @@ -139,7 +140,7 @@ export default function startHandler(handler: Handler): void {
const responseData: Buffer[] = [];
const responseHeaders: ResponseHeaders = {
status: clientResponse.statusCode!,
headers: clientResponse.rawHeaders,
headers: toPairs(clientResponse.rawHeaders),
};

ipc.send({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,25 @@ export function headersFromEntries(
}
return headers;
}

/**
* Transforms an array of elements into an array of pairs of elements.
*
* ## Example
*
* ```ts
* toPairs(["a", "b", "c", "d"]) // => [["a", "b"], ["c", "d"]]
* ```
*/
export function toPairs<T>(arr: T[]): Array<[T, T]> {
if (arr.length % 2 !== 0) {
throw new Error("toPairs: expected an even number of elements");
}

const pairs: Array<[T, T]> = [];
for (let i = 0; i < arr.length; i += 2) {
pairs.push([arr[i], arr[i + 1]]);
}

return pairs;
}
2 changes: 1 addition & 1 deletion crates/next-core/js/src/internal/page-server-handler.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import type { BuildManifest } from "next/dist/server/get-page-files";
import type { ReactLoadableManifest } from "next/dist/server/load-components";

import { ServerResponseShim } from "@vercel/turbopack-next/internal/http";
import { headersFromEntries } from "@vercel/turbopack-next/internal/utils";
import { headersFromEntries } from "@vercel/turbopack-next/internal/headers";
import type { Ipc } from "@vercel/turbopack-next/ipc/index";
import type { RenderData } from "types/turbopack";
import type { ChunkGroup } from "types/next";
Expand Down
4 changes: 2 additions & 2 deletions crates/next-core/js/src/ipc/server.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ClientRequest, IncomingMessage, Server } from "node:http";
import type { AddressInfo } from "node:net";
import http, { ServerResponse } from "node:http";
import { headersFromEntries } from "@vercel/turbopack-next/internal/utils";
import { headersFromEntries } from "@vercel/turbopack-next/internal/headers";

/**
* Creates a server that listens a random port.
Expand All @@ -24,7 +24,7 @@ export function makeRequest(
method: string,
path: string,
rawQuery?: string,
rawHeaders?: Array<[string, string]>
rawHeaders?: [string, string][]
): Promise<{
clientRequest: ClientRequest;
clientResponsePromise: Promise<IncomingMessage>;
Expand Down
2 changes: 1 addition & 1 deletion crates/next-core/src/next_image/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ impl ContentSource for NextImageContentSource {
ContentSourceContent::HttpProxy(
ProxyResult {
status: 302,
headers: vec!["Location".to_string(), url.clone()],
headers: vec![("Location".to_string(), url.clone())],
body: "".into(),
}
.cell(),
Expand Down
4 changes: 2 additions & 2 deletions crates/next-core/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,15 @@ pub struct RouterRequest {
#[serde(rename_all = "camelCase")]
pub struct RewriteResponse {
pub url: String,
pub headers: Vec<String>,
pub headers: Vec<(String, String)>,
}

#[turbo_tasks::value(shared)]
#[derive(Debug, Clone, Default)]
#[serde(rename_all = "camelCase")]
pub struct MiddlewareHeadersResponse {
pub status_code: u16,
pub headers: Vec<String>,
pub headers: Vec<(String, String)>,
}

#[turbo_tasks::value(shared)]
Expand Down
2 changes: 1 addition & 1 deletion crates/turbopack-dev-server/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ pub async fn process_request_with_content_source(
let mut response = Response::builder().status(proxy_result.status);
let headers = response.headers_mut().expect("headers must be defined");

for [name, value] in proxy_result.headers.array_chunks() {
for (name, value) in &proxy_result.headers {
headers.append(
HeaderName::from_bytes(name.as_bytes())?,
hyper::header::HeaderValue::from_str(value)?,
Expand Down
2 changes: 1 addition & 1 deletion crates/turbopack-dev-server/src/source/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub struct ProxyResult {
/// The HTTP status code to return.
pub status: u16,
/// Headers arranged as contiguous (name, value) pairs.
pub headers: Vec<String>,
pub headers: Vec<(String, String)>,
/// The body to return.
pub body: Rope,
}
Expand Down
2 changes: 1 addition & 1 deletion crates/turbopack-node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ pub async fn get_intermediate_asset(
#[turbo_tasks::value(shared)]
pub struct ResponseHeaders {
pub status: u16,
pub headers: Vec<String>,
pub headers: Vec<(String, String)>,
}

#[derive(Serialize)]
Expand Down
4 changes: 2 additions & 2 deletions crates/turbopack-node/src/render/render_proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,10 @@ async fn proxy_error(

Ok(ProxyResult {
status: 500,
headers: vec![
headers: vec![(
"content-type".to_string(),
"text/html; charset=utf-8".to_string(),
],
)],
body: body.into(),
}
.cell())
Expand Down

0 comments on commit 78b442e

Please sign in to comment.