-
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
e1b8a4b
commit d637ba8
Showing
30 changed files
with
565 additions
and
105 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
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,100 @@ | ||
import { headersToObject, resolveBody } from "@fiberplane/fpx-utils"; | ||
import type { 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 schema.NewAppRequest["requestMethod"], | ||
requestUrl: requestUrl.toString(), | ||
requestHeaders: headersToObject(newHeaders), | ||
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]; | ||
} | ||
} |
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 { zValidator } from "@hono/zod-validator"; | ||
import { Hono } from "hono"; | ||
import { z } from "zod"; | ||
import { parkingLot } from "../lib/deflector/index.js"; | ||
import type { Bindings, Variables } from "../lib/types.js"; | ||
|
||
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
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,56 @@ | ||
import { Button } from "@/components/ui/button"; | ||
import { useToast } from "@/components/ui/use-toast"; | ||
import { cn } from "@/utils"; | ||
import { useQueryClient } from "@tanstack/react-query"; | ||
import { useState } from "react"; | ||
import { CodeMirrorJsonEditor } from "./Editors"; | ||
import { REQUESTOR_REQUESTS_KEY } from "./queries"; | ||
|
||
export function DeflectorResponse({ | ||
deflectorTarget, | ||
}: { | ||
deflectorTarget: string; | ||
}) { | ||
const [text, setText] = useState(""); | ||
const { toast } = useToast(); | ||
const client = useQueryClient(); | ||
return ( | ||
<div className={cn("h-full grid grid-rows-[auto_1fr]")}> | ||
<div> | ||
<Button | ||
onClick={async () => { | ||
try { | ||
// this is just to check if the JSON is valid and fail otherwise | ||
JSON.parse(text); | ||
setText(""); | ||
await fetch("/v0/deflector", { | ||
method: "POST", | ||
headers: { | ||
"Content-Type": "application/json", | ||
}, | ||
body: JSON.stringify({ | ||
key: deflectorTarget, | ||
value: text, | ||
}), | ||
}); | ||
client.invalidateQueries({ queryKey: [REQUESTOR_REQUESTS_KEY] }); | ||
} catch (e) { | ||
toast({ | ||
title: "Error", | ||
description: `Invalid JSON: ${e}`, | ||
}); | ||
} | ||
}} | ||
> | ||
Send response | ||
</Button> | ||
</div> | ||
<div className={cn("overflow-hidden overflow-y-auto w-full")}> | ||
<CodeMirrorJsonEditor | ||
value={text} | ||
onChange={(value) => setText(value ?? "")} | ||
/> | ||
</div> | ||
</div> | ||
); | ||
} |
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.