Skip to content

Commit

Permalink
Merge pull request #271 from deco-cx/ft/otel-proxy
Browse files Browse the repository at this point in the history
Ft/otel proxy
  • Loading branch information
hugo-ccabral authored Jan 4, 2024
2 parents 8e65199 + fbbb8ec commit 94c36e9
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 8 deletions.
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

0 comments on commit 94c36e9

Please sign in to comment.