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

Ft/otel proxy #271

Merged
merged 11 commits into from
Jan 4, 2024
4 changes: 2 additions & 2 deletions nuvemshop/handlers/sitemap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export default function Sitemap(
const url = ctx.publicUrl;
return async (
req: Request,
ctx: ConnInfo,
connInfoctx: ConnInfo,
) => {
if (!url) {
throw new Error("Missing publicUrl");
Expand All @@ -52,7 +52,7 @@ export default function Sitemap(

const response = await Proxy({
url: publicUrl,
})(req, ctx);
})(req, connInfoctx);

if (!response.ok) {
return response;
Expand Down
47 changes: 41 additions & 6 deletions website/handlers/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { DecoSiteState } from "deco/mod.ts";
import { Handler } from "std/http/mod.ts";
import { proxySetCookie } from "../../utils/cookie.ts";
import { Script } from "../types.ts";
import { Monitoring } from "deco/engine/core/resolver.ts";

const HOP_BY_HOP = [
"Keep-Alive",
Expand All @@ -26,6 +27,22 @@ const removeCFHeaders = (headers: Headers) => {
});
};

async function logClonedResponseBody(
response: Response,
monitoring: Monitoring | undefined,
): Promise<void> {
if (!response.body) {
return;
}

const clonedResponse = response.clone();
const text = await clonedResponse.text();

monitoring?.logger?.error?.(
`Proxy error = ${response.statusText}, body = ${text}`,
);
}

/**
* @title {{{key}}} - {{{value}}}
*/
Expand Down Expand Up @@ -117,12 +134,30 @@ export default function Proxy({
headers.set(key, value);
}

const response = await fetch(to, {
headers,
redirect,
method: req.method,
body: req.body,
});
const monitoring = isFreshCtx<DecoSiteState>(_ctx)
? _ctx?.state?.monitoring
: undefined;

const fecthFunction = async () => {
try {
return await fetch(to, {
headers,
redirect,
method: req.method,
body: req.body,
});
} catch (err) {
monitoring?.logger?.error?.(err);

throw err;
}
};

const response = await fecthFunction();

if (response.status >= 299 || response.status < 200) {
await logClonedResponseBody(response, monitoring);
}

const contentType = response.headers.get("Content-Type");

Expand Down
Loading