⚡ Bolt: Add GZIP compression to API responses#145
Conversation
Added GZIP compression to `writeJsonResponse` in `src/api/http-helpers.ts`. JSON payloads larger than 1KB will be compressed if the client supports GZIP. This reduces bandwidth usage and improves response times for data-heavy endpoints.
|
👋 Jules, reporting for duty! I'm here to lend a hand with this pull request. When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down. I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job! For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with New to Jules? Learn more at jules.google/docs. For security, I will only act on instructions from the user who triggered this task. |
|
Important Review skippedDraft detected. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Summary of ChangesHello @Dexploarer, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request introduces a significant performance enhancement by integrating GZIP compression into the API response handling. The change focuses on optimizing network usage and accelerating data transfer for larger JSON payloads by compressing them before delivery, provided the client explicitly supports GZIP encoding. This will lead to faster load times and reduced bandwidth consumption for users interacting with data-heavy API endpoints. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
| res.setHeader("Content-Type", "application/json"); | ||
| res.end(JSON.stringify(body)); | ||
|
|
||
| const jsonBody = JSON.stringify(body); |
There was a problem hiding this comment.
Unhandled Exception Risk: JSON.stringify
The call to JSON.stringify(body) can throw an exception if body contains circular references or non-serializable values. This will result in an unhandled promise rejection and may crash the server or leave the HTTP response incomplete.
Recommended Solution:
Wrap the serialization in a try-catch block and handle errors gracefully, for example:
let jsonBody: string;
try {
jsonBody = JSON.stringify(body);
} catch (err) {
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ error: "Failed to serialize response body" }));
return;
}| res.end(JSON.stringify(body)); | ||
|
|
||
| const jsonBody = JSON.stringify(body); | ||
| const req = (res as unknown as { req: http.IncomingMessage }).req; |
There was a problem hiding this comment.
Unsafe Access: res.req via Type Cast
The code accesses the request object using (res as unknown as { req: http.IncomingMessage }).req. This is not guaranteed to be safe, as the res object may not always have a req property, depending on the environment or future refactoring. If req is undefined, subsequent header checks will fail or behave unexpectedly.
Recommended Solution:
Add a runtime check to ensure req is defined before accessing headers, and handle the case where it is not:
const req = (res as any).req;
const acceptEncoding = req?.headers?.["accept-encoding"] || "";Or, better, require the caller to provide the request object explicitly if possible.
There was a problem hiding this comment.
Code Review
This pull request introduces GZIP compression for API responses, which is an excellent performance enhancement. The implementation correctly checks for client support via the Accept-Encoding header and payload size, and properly includes the Vary header in compressed responses. The accompanying tests are thorough and cover the key scenarios. My feedback focuses on simplifying the asynchronous code by using the modern promise-based API from Node.js's zlib module, which will improve the code's readability and maintainability.
| @@ -1,4 +1,5 @@ | |||
| import type http from "node:http"; | |||
| import zlib from "node:zlib"; | |||
There was a problem hiding this comment.
| const compressed = await new Promise<Buffer>((resolve, reject) => { | ||
| zlib.gzip(jsonBody, (err, result) => { | ||
| if (err) reject(err); | ||
| else resolve(result); | ||
| }); | ||
| }); |
| vi.mock("node:zlib", async () => { | ||
| return { | ||
| default: { | ||
| gzip: (_buf: unknown, cb: (err: null, res: Buffer) => void) => { | ||
| // Simple mock: just return the buffer reversed to simulate compression | ||
| // In reality, we just want to check it was called. | ||
| cb(null, Buffer.from("compressed")); | ||
| }, | ||
| }, | ||
| }; | ||
| }); |
There was a problem hiding this comment.
To align with the suggested change of using zlib.promises.gzip in the implementation, this mock should be updated to mock the promise-based API instead of the callback-based one.
vi.mock("node:zlib", () => ({
promises: {
gzip: async (_buf: unknown): Promise<Buffer> => {
// Simple mock: just return a fixed buffer to simulate compression.
return Buffer.from("compressed");
},
},
}));
writeJsonResponseinsrc/api/http-helpers.tsfor payloads > 1KB whenAccept-Encoding: gzipis present./api/conversations).http.ServerResponseandzlib.PR created automatically by Jules for task 17684048088717560080 started by @Dexploarer