-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
66b1baa
commit c8a4f5b
Showing
21 changed files
with
501 additions
and
40 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import type { Context } from "hono"; | ||
|
||
// inversion of control container to store parked requests | ||
export type ParkingLot = Map< | ||
string, | ||
[Context, (value: Response) => void, (reason: unknown) => void] | ||
>; | ||
|
||
export const parkingLot: ParkingLot = new Map(); | ||
|
||
export { deflectorMiddleware } from "./middleware.js"; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,163 @@ | ||
import type { HonoRequest, MiddlewareHandler } from "hono"; | ||
|
||
import * as schema from "../../db/schema.js"; | ||
import logger from "../../logger.js"; | ||
import { | ||
handleFailedRequest, | ||
handleSuccessfulRequest, | ||
} from "../proxy-request/index.js"; | ||
import type { Bindings, Variables } from "../types.js"; | ||
import { parkingLot } from "./index.js"; | ||
|
||
let isDeflectorEnabled = false; | ||
export const setDeflectorStatus = (status: boolean) => { | ||
isDeflectorEnabled = status; | ||
} | ||
export const deflectorMiddleware: MiddlewareHandler<{ | ||
Bindings: Bindings; | ||
Variables: Variables; | ||
}> = async (c, next) => { | ||
const deflectTo = c.req.header("x-fpx-deflect-to"); | ||
if (!isDeflectorEnabled || !deflectTo) { | ||
return next(); | ||
} | ||
const db = c.get("db"); | ||
const traceId = crypto.randomUUID(); | ||
const [requestUrl, isInternal] = processTarget(deflectTo, c.req.url); | ||
logger.info(`Deflecting request to ${requestUrl}`); | ||
const newHeaders = new Headers(c.req.raw.headers); | ||
newHeaders.append("x-fpx-trace-id", traceId); | ||
const [{ id: requestId }] = await db | ||
.insert(schema.appRequests) | ||
.values({ | ||
requestMethod: c.req.method as any, | ||
requestUrl: requestUrl.toString(), | ||
requestHeaders: Object.fromEntries((newHeaders as any).entries()), | ||
requestPathParams: {}, | ||
requestQueryParams: Object.fromEntries(requestUrl.searchParams), | ||
requestBody: await resolveBody(c.req), | ||
requestRoute: requestUrl.pathname, | ||
}) | ||
.returning({ id: schema.appRequests.id }); | ||
const startTime = Date.now(); | ||
newHeaders.delete("x-fpx-deflect-to"); | ||
try { | ||
let response: Response; | ||
if (isInternal) { | ||
response = await new Promise((resolve, reject) => { | ||
parkingLot.set(traceId, [c, resolve, reject]); | ||
}); | ||
} else { | ||
response = await fetch(requestUrl, { | ||
method: c.req.method, | ||
headers: newHeaders, | ||
body: c.req.raw.body, | ||
}); | ||
} | ||
const duration = Date.now() - startTime; | ||
await handleSuccessfulRequest( | ||
db, | ||
requestId, | ||
duration, | ||
response.clone(), | ||
traceId, | ||
); | ||
|
||
return response; | ||
} catch (error) { | ||
logger.error("Error making request", error); | ||
const duration = Date.now() - startTime; | ||
await handleFailedRequest(db, requestId, traceId, duration, error); | ||
|
||
return c.json({ error: "Internal server error" }, 500); | ||
} | ||
}; | ||
|
||
function processTarget( | ||
targetString: string, | ||
requestString: string, | ||
): [URL, boolean] { | ||
try { | ||
const [targetUrl, requestUrl] = [targetString, requestString].map( | ||
(url) => new URL(url), | ||
); | ||
for (const prop of ["hostname", "port", "protocol"] as const) { | ||
requestUrl[prop] = targetUrl[prop]; | ||
} | ||
return [requestUrl, false]; | ||
} catch { | ||
const url = new URL(requestString); | ||
url.hostname = targetString; | ||
return [url, true]; | ||
} | ||
} | ||
|
||
async function resolveBody(request: HonoRequest) { | ||
const contentType = request.header("content-type")?.toLowerCase(); | ||
const method = request.method.toUpperCase(); | ||
|
||
// Handle methods without body | ||
if (method === "GET" || method === "HEAD" || method === "OPTIONS") { | ||
console.debug("Method is GET, HEAD, or OPTIONS, returning null"); | ||
return null; | ||
} | ||
|
||
// Handle empty body | ||
if (!contentType || request.header("content-length") === "0") { | ||
return null; | ||
} | ||
|
||
try { | ||
// JSON | ||
if (contentType.includes("application/json")) { | ||
console.debug("Content type is application/json, returning JSON"); | ||
return await request.json(); | ||
} | ||
|
||
// Form data (URL-encoded) | ||
if (contentType.includes("application/x-www-form-urlencoded")) { | ||
console.debug( | ||
"Content type is application/x-www-form-urlencoded, returning FormData", | ||
); | ||
return Object.fromEntries( | ||
(await request.formData()) as unknown as Iterable<[string, string]>, | ||
); | ||
} | ||
|
||
// TODO: Handle multipart/form-data (can contain both text and binary data) | ||
|
||
// Plain text | ||
if (contentType.includes("text/plain")) { | ||
console.debug("Content type is text/plain, returning text"); | ||
return await request.text(); | ||
} | ||
|
||
// Handle XML, HTML, JavaScript, CSS, and CSV files and other | ||
// formats that for some reason you'd send to your API | ||
if ( | ||
contentType.includes("application/xml") || | ||
contentType.includes("text/xml") || | ||
contentType.includes("text/html") || | ||
contentType === "application/javascript" || | ||
contentType === "text/javascript" || | ||
contentType === "text/css" || | ||
contentType === "text/csv" | ||
) { | ||
console.debug( | ||
"Content type is XML, HTML, JavaScript, CSS, or CSV, returning text", | ||
); | ||
return await request.text(); | ||
} | ||
|
||
// TODO: Handle binary data (application/octet-stream) | ||
// TODO: Handle image files | ||
// TODO: Handle PDF files | ||
|
||
console.debug("Content type is not recognized, returning text"); | ||
// Default case: try to parse as text | ||
return await request.text(); | ||
} catch (error) { | ||
console.error("Error parsing request body:", error); | ||
return null; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
import { Hono } from "hono"; | ||
import { z } from "zod"; | ||
import type { Bindings, Variables } from "../lib/types.js"; | ||
import { parkingLot } from "../lib/deflector/index.js"; | ||
import { zValidator } from "@hono/zod-validator"; | ||
|
||
const app = new Hono<{ Bindings: Bindings; Variables: Variables }>(); | ||
|
||
app.post( | ||
"/v0/deflector", | ||
zValidator( | ||
"json", | ||
z.object({ | ||
key: z.string(), | ||
value: z.string(), | ||
}), | ||
), | ||
async (ctx) => { | ||
const { key, value } = ctx.req.valid("json"); | ||
const fromCache = parkingLot.get(key); | ||
if (fromCache) { | ||
parkingLot.delete(key); | ||
const [parkedContext, resolve] = fromCache; | ||
resolve(parkedContext.json(JSON.parse(value))); | ||
return ctx.json({ result: "success" }); | ||
} | ||
return ctx.json({ error: `Unknown key: ${key}` }, 404); | ||
}, | ||
); | ||
|
||
export default app; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.