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

feat(log-viewer-webui): Refactor S3Manager into a Fastify plugin. #689

Merged
merged 6 commits into from
Jan 31, 2025

Conversation

haiqi96
Copy link
Contributor

@haiqi96 haiqi96 commented Jan 23, 2025

Description

This PR refactors the S3Manager into a fastify plugin, which allows as to avoid initializing S3 Manager as a global variable.

Validation performed

Manually tested FS and S3 stream viewing.

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced S3 file management capabilities with improved configuration and pre-signed URL generation.
    • Added conditional S3 manager initialization for more flexible file streaming.
  • Improvements

    • Streamlined S3 integration in the application's server configuration.
    • Updated route handling to support more robust S3 file access, directly utilizing the Fastify context for S3 operations.

These updates provide more flexible and reliable file management when working with S3 storage.

Copy link
Contributor

coderabbitai bot commented Jan 23, 2025

Walkthrough

The pull request modifies the S3 management functionality in the log viewer web UI by updating the S3Manager class to utilize a Fastify plugin for initialization. The constructor now accepts an object containing the region, and the export has been adjusted to log the initialization process. Additionally, the app.js file conditionally registers the S3Manager based on the environment, while the query.js file refines the handling of the S3Manager, directly utilizing Fastify's context instead of a separate variable.

Changes

File Change Summary
components/log-viewer-webui/server/src/S3Manager.js - Updated constructor to accept an object with region
- Modified export to use Fastify plugin for decoration with initialization log
components/log-viewer-webui/server/src/app.js - Added import for S3Manager
- Conditionally registered S3Manager for non-test environments
components/log-viewer-webui/server/src/routes/query.js - Updated method signatures to include s3Manager
- Replaced separate S3 manager variable with Fastify context

Possibly Related PRs

Suggested Reviewers

  • kirkrodrigues
  • junhaoliao
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@junhaoliao junhaoliao self-requested a review January 23, 2025 20:11
Copy link
Member

@junhaoliao junhaoliao left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The overall structure is good. I made some comment about how to solve the issue of the region option being inaccessible.

components/log-viewer-webui/server/src/S3Manager.js Outdated Show resolved Hide resolved
components/log-viewer-webui/server/src/app.js Outdated Show resolved Hide resolved
components/log-viewer-webui/server/src/S3Manager.js Outdated Show resolved Hide resolved
@haiqi96 haiqi96 changed the title Draft Fastify feat(log-viewer-webui): Refactor S3Manager to be fastify plugin. Jan 23, 2025
@haiqi96 haiqi96 changed the title feat(log-viewer-webui): Refactor S3Manager to be fastify plugin. feat(log-viewer-webui): Refactor S3Manager into a fastify plugin. Jan 23, 2025
@haiqi96 haiqi96 requested a review from junhaoliao January 23, 2025 22:50
@haiqi96 haiqi96 marked this pull request as ready for review January 23, 2025 22:50
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
components/log-viewer-webui/server/src/S3Manager.js (1)

25-31: Handle potential undefined region parameter

In the constructor, consider handling the case where region might be undefined. Currently, if region is undefined, null !== region evaluates to true, which could lead to unintended behaviour when initializing S3Client with an undefined region.

Apply this diff to ensure region is not undefined:

 constructor ({region}) {
-    if (null !== region) {
+    if (null !== region && undefined !== region) {
         this.#s3Client = new S3Client({
             region: region,
         });
     }
 }

Alternatively, you can use a more concise check:

 constructor ({region}) {
-    if (null !== region) {
+    if (region) {
         this.#s3Client = new S3Client({
             region: region,
         });
     }
 }
components/log-viewer-webui/server/src/routes/query.js (2)

11-13: Improve JSDoc parameter type annotations

The use of the union type | in the JSDoc comments may not accurately represent the structure of the fastify object, which includes all listed properties. Consider using the intersection type & to indicate that fastify contains all specified properties.

Apply this diff to adjust the JSDoc annotations:

 /**
  * @param {object} props
- * @param {import("fastify").FastifyInstance |
- * {dbManager: DbManager} |
- * {s3Manager: S3Manager}} props.fastify
+ * @param {import("fastify").FastifyInstance &
+ * {dbManager: DbManager} &
+ * {s3Manager: S3Manager}} props.fastify
  * @param {EXTRACT_JOB_TYPES} props.jobType
  * @param {number} props.logEventIdx
  * @param {string} props.streamId

59-61: Adjust JSDoc annotations for accurate typing

Similar to the earlier comment, update the parameter type annotations to reflect that fastify includes all the specified properties.

Apply this diff:

 /**
  * @param {import("fastify").FastifyInstance &
  * {dbManager: DbManager} &
  * {s3Manager: S3Manager}} fastify
  * @param {import("fastify").FastifyPluginOptions} options
  * @return {Promise<void>}
  */
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 66067d6 and 77826ce.

📒 Files selected for processing (3)
  • components/log-viewer-webui/server/src/S3Manager.js (4 hunks)
  • components/log-viewer-webui/server/src/app.js (2 hunks)
  • components/log-viewer-webui/server/src/routes/query.js (3 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
components/log-viewer-webui/server/src/app.js (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

components/log-viewer-webui/server/src/routes/query.js (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

components/log-viewer-webui/server/src/S3Manager.js (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: lint-check (macos-latest)
🔇 Additional comments (7)
components/log-viewer-webui/server/src/S3Manager.js (5)

19-19: Initialization of private field #s3Client

Properly initializing #s3Client to null enhances code safety by ensuring the variable has a known state before use.


22-23: Clarify constructor parameter documentation

The JSDoc comments accurately reflect the updated constructor parameters, improving code readability and maintainability.


33-34: isEnabled method implementation looks good

The isEnabled method correctly checks the initialization state of #s3Client, enhancing the class's usability.


45-47: Usage of false === <expression> complies with coding guidelines

The condition if (false === this.isEnabled()) aligns with the project's coding standards.


68-70: Proper use of Fastify plugin to register S3Manager

Exporting S3Manager as a Fastify plugin and decorating it onto the app instance improves modularity and follows best practices.

components/log-viewer-webui/server/src/app.js (2)

9-9: Importing S3Manager

The import statement correctly brings in the S3Manager plugin for registration.


45-45: Registering S3Manager with appropriate options

Registering S3Manager with the region option ensures proper configuration. This aligns with previous review suggestions and enhances code clarity.

Comment on lines 94 to 99
if (fastify.s3Manager.isEnabled()) {
streamMetadata.path = await fastify.s3Manager.getPreSignedUrl(
`s3://${settings.StreamFilesS3PathPrefix}${streamMetadata.path}`
);
} else {
streamMetadata.path = `/streams/${streamMetadata.path}`;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Ensure s3Manager is defined before use

Accessing fastify.s3Manager without checking if it is defined could lead to runtime errors, especially in environments where s3Manager is not registered (e.g., when NODE_ENV === "test"). Modify the condition to check for the existence of s3Manager before calling isEnabled().

Apply this diff to prevent potential null reference errors:

-if (fastify.s3Manager.isEnabled()) {
+if (fastify.s3Manager && fastify.s3Manager.isEnabled()) {
     streamMetadata.path = await fastify.s3Manager.getPreSignedUrl(
         `s3://${settings.StreamFilesS3PathPrefix}${streamMetadata.path}`
     );
 } else {
     streamMetadata.path = `/streams/${streamMetadata.path}`;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (fastify.s3Manager.isEnabled()) {
streamMetadata.path = await fastify.s3Manager.getPreSignedUrl(
`s3://${settings.StreamFilesS3PathPrefix}${streamMetadata.path}`
);
} else {
streamMetadata.path = `/streams/${streamMetadata.path}`;
if (fastify.s3Manager && fastify.s3Manager.isEnabled()) {
streamMetadata.path = await fastify.s3Manager.getPreSignedUrl(
`s3://${settings.StreamFilesS3PathPrefix}${streamMetadata.path}`
);
} else {
streamMetadata.path = `/streams/${streamMetadata.path}`;

@@ -55,4 +65,6 @@ class S3Manager {
}
}

export default S3Manager;
export default fastifyPlugin(async (app, options) => {
await app.decorate("s3Manager", new S3Manager(options));
Copy link
Member

@junhaoliao junhaoliao Jan 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for overlooking this enablement check mechanism when we discussed this offline. Some changes can be made to make the code even cleaner, if you also agree:

  1. Let's treat this callback provided to fastifyPlugin() as a factory function of class S3Manager and perform all argument checks inside.
  2. If any such checks fail, we don't decorate the Fastify app. Consider adding an error log / throwing an error so developers become aware of this.
  3. That way we can (hopefully) ensure all arguments passed to S3Manager are valid and do not cause the constructor to crash, and we can also guarantee the s3Client is always valid within the scope of the class (no need to do isEnabled checks).
  4. Most importantly, we can make the query route code unaware of any S3Manager's exact implementation, by checking fastify.hasDecorator('s3Manager') instead of fastify.s3Manager.isEnabled()

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For 1, can you give a more concrete example?

Do you mean instead of writing new S3Manager() as the second argument, pass in a function that

  1. Takes in options as argument
  2. If argument verification passes, return calls S3Manager constructor and return a new S3Manager() instance
  3. If fails, throw an error, and does it need to return anythinig?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

right, let's do something like

export default fastifyPlugin(async (app, options) => {
    const {xxx} = options;
    if (xxx is invalid) {
        // if throwing halts the server (please help confirm), we shall require users (developers who register this plugin) to validate the args.
        // or simply, instead, `console.error("error message")` then `return`
        throw new Error("error message");
    }

    await app.decorate("s3Manager", new S3Manager(options));
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have tried throwing an error, and the entire container is down, with the following log

2025-01-29 15:00:07 Error: I will throw an error message
2025-01-29 15:00:07     at file:///opt/clp/var/www/log_viewer_webui/server/src/S3Manager.js:63:15
2025-01-29 15:00:07     at Plugin.exec (/opt/clp/var/www/log_viewer_webui/server/node_modules/avvio/lib/plugin.js:125:28)
2025-01-29 15:00:07     at Boot._loadPlugin (/opt/clp/var/www/log_viewer_webui/server/node_modules/avvio/boot.js:432:10)
2025-01-29 15:00:07     at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

now I think about it, actually we cannot throw an error, because there will be valid case where region is null, simply meaning that s3Manager is not enabled.

So I guess what we should do is:
If region is null, return without doing anything
else, initialize s3 plugin

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
components/log-viewer-webui/server/src/S3Manager.js (1)

63-63: Use structured logging for initialization

Consider using a more structured logging approach for better consistency and machine readability.

-    console.log(`s3Manager initialized with region ${region}`)
+    app.log.info({region}, 's3Manager initialized')
components/log-viewer-webui/server/src/routes/query.js (1)

94-94: Follow coding guidelines for boolean expressions

Per coding guidelines, prefer false == over ! for boolean expressions.

-        if (fastify.hasDecorator('s3Manager')) {
+        if (false === fastify.hasDecorator('s3Manager')) {
+            streamMetadata.path = `/streams/${streamMetadata.path}`;
+        } else {
+            streamMetadata.path = await fastify.s3Manager.getPreSignedUrl(
+                `s3://${settings.StreamFilesS3PathPrefix}${streamMetadata.path}`
+            );
         }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 77826ce and c8a5898.

📒 Files selected for processing (2)
  • components/log-viewer-webui/server/src/S3Manager.js (3 hunks)
  • components/log-viewer-webui/server/src/routes/query.js (3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
components/log-viewer-webui/server/src/S3Manager.js (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

components/log-viewer-webui/server/src/routes/query.js (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: lint-check (ubuntu-latest)
  • GitHub Check: build (macos-latest)
  • GitHub Check: lint-check (macos-latest)
🔇 Additional comments (3)
components/log-viewer-webui/server/src/S3Manager.js (2)

64-64: Pass complete options object to constructor

As discussed previously, pass the complete options object to allow for future extensibility.

-    await app.decorate("s3Manager", new S3Manager(region));
+    await app.decorate("s3Manager", new S3Manager(options));

24-24: 🛠️ Refactor suggestion

Update constructor signature to match previous agreement

Based on the previous discussion, the constructor should accept an options object instead of a direct region parameter.

Apply this diff to align with the agreed approach:

-    constructor (region) {
+    constructor ({region}) {

Also update the JSDoc to reflect this change:

-     * @param {string} region
+     * @param {object} props
+     * @param {string | null} props.region

Likely invalid or redundant comment.

components/log-viewer-webui/server/src/routes/query.js (1)

11-13: LGTM! Type definition updated correctly

The JSDoc has been properly updated to include the s3Manager type in the FastifyInstance union type.

Comment on lines 94 to 99
if (fastify.hasDecorator('s3Manager')) {
streamMetadata.path = await fastify.s3Manager.getPreSignedUrl(
`s3://${settings.StreamFilesS3PathPrefix}${streamMetadata.path}`
);
} else {
streamMetadata.path = `/streams/${streamMetadata.path}`;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling for getPreSignedUrl

The getPreSignedUrl operation can fail and throw errors. These should be handled gracefully.

         if (fastify.hasDecorator('s3Manager')) {
-            streamMetadata.path = await fastify.s3Manager.getPreSignedUrl(
-                `s3://${settings.StreamFilesS3PathPrefix}${streamMetadata.path}`
-            );
+            try {
+                streamMetadata.path = await fastify.s3Manager.getPreSignedUrl(
+                    `s3://${settings.StreamFilesS3PathPrefix}${streamMetadata.path}`
+                );
+            } catch (error) {
+                resp.code(StatusCodes.INTERNAL_SERVER_ERROR);
+                throw new Error(`Failed to generate pre-signed URL: ${error.message}`);
+            }
         } else {
             streamMetadata.path = `/streams/${streamMetadata.path}`;
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (fastify.hasDecorator('s3Manager')) {
streamMetadata.path = await fastify.s3Manager.getPreSignedUrl(
`s3://${settings.StreamFilesS3PathPrefix}${streamMetadata.path}`
);
} else {
streamMetadata.path = `/streams/${streamMetadata.path}`;
if (fastify.hasDecorator('s3Manager')) {
try {
streamMetadata.path = await fastify.s3Manager.getPreSignedUrl(
`s3://${settings.StreamFilesS3PathPrefix}${streamMetadata.path}`
);
} catch (error) {
resp.code(StatusCodes.INTERNAL_SERVER_ERROR);
throw new Error(`Failed to generate pre-signed URL: ${error.message}`);
}
} else {
streamMetadata.path = `/streams/${streamMetadata.path}`;

junhaoliao
junhaoliao previously approved these changes Jan 30, 2025
components/log-viewer-webui/server/src/S3Manager.js Outdated Show resolved Hide resolved
@junhaoliao junhaoliao changed the title feat(log-viewer-webui): Refactor S3Manager into a fastify plugin. feat(log-viewer-webui): Refactor S3Manager into a Fastify plugin. Jan 30, 2025
@junhaoliao
Copy link
Member

I modified the PR title directly.

}

console.log(`Initializing S3Manager with region="${region}"...`);
await app.decorate("s3Manager", new S3Manager(region));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we add another log after the decorate is done? Just for debugging purpose.
@junhaoliao

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think for now it's fine not to log after init completion, since we don't expect constructor to hang. In cases where the constructor throws, we shall be notified for any exception messages.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
components/log-viewer-webui/server/src/S3Manager.js (1)

63-66: Consider adding error logging for invalid options.

While the null check is correct, adding error logs would help developers understand why the S3Manager wasn't initialized.

Apply this diff to improve error handling:

     const {region} = options;
     if (null === region) {
+        console.log("S3Manager initialization skipped: region is null");
         return;
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2a521cf and 60bf555.

📒 Files selected for processing (1)
  • components/log-viewer-webui/server/src/S3Manager.js (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
components/log-viewer-webui/server/src/S3Manager.js (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: lint-check (ubuntu-latest)
🔇 Additional comments (3)
components/log-viewer-webui/server/src/S3Manager.js (3)

1-1: LGTM! The import statement is correctly added.

The import of fastifyPlugin is necessary for implementing the Fastify plugin architecture.


24-24: Use object destructuring for constructor parameters.

Previous discussions in the PR indicate that object destructuring is preferred for better extensibility.

Apply this diff to implement the agreed-upon pattern:

-    constructor (region) {
+    constructor ({region}) {

58-70: LGTM! The plugin implementation follows best practices.

The implementation includes proper JSDoc comments, null checks, logging, and app decoration. The use of null === region follows the coding guidelines.

@haiqi96 haiqi96 requested a review from junhaoliao January 30, 2025 20:44
@haiqi96 haiqi96 merged commit 037cf10 into y-scope:main Jan 31, 2025
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants