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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

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
  • Bug Fixes

    • Improved error handling for S3 client initialization and URL generation

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 introduces modifications to the S3 management functionality in the log viewer web UI. The changes focus on improving the S3 client initialization and integration with the Fastify server. The S3Manager class now supports more flexible configuration, with a new method to check if S3 is enabled. The implementation has been refactored to use Fastify's plugin system, allowing for more streamlined S3 client management across the application.

Changes

File Change Summary
components/log-viewer-webui/server/src/S3Manager.js - Updated constructor to accept an object with region
- Added isEnabled() method to check S3 client status
- Modified export to use Fastify plugin for decoration
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
- Modified path generation logic using isEnabled() method

Sequence Diagram

sequenceDiagram
    participant App as Fastify App
    participant S3Manager as S3Manager
    participant S3 as S3 Client

    App->>S3Manager: Create with region
    S3Manager-->>App: S3Manager instance
    App->>App: Decorate with S3Manager
    
    alt S3 Enabled
        App->>S3Manager: isEnabled()
        S3Manager-->>App: true
        App->>S3Manager: getPreSignedURL()
        S3Manager->>S3: Generate Pre-Signed URL
        S3-->>S3Manager: Return URL
        S3Manager-->>App: Pre-Signed URL
    else S3 Disabled
        App->>S3Manager: isEnabled()
        S3Manager-->>App: false
        App->>App: Use local path
    end
Loading

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.

@@ -55,4 +69,8 @@ class S3Manager {
}
}

export default S3Manager;
export default fastifyPlugin(async (app, region) => {
Copy link
Member

Choose a reason for hiding this comment

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

fastifyPlugin requires the second argument in the callback to be an options object: See https://fastify.dev/docs/latest/Reference/Plugins/#plugin-options

because Fastify specific options like logLevel, logSerializers, prefix are expected to show up in the options object if they exist.

Suggested change
export default fastifyPlugin(async (app, region) => {
export default fastifyPlugin(async (app, options) => {

export default fastifyPlugin(async (app, region) => {
console.log(`Region in Plugin init is ${region}`)
console.log(region)
await app.decorate("s3Manager", new S3Manager(region));
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 we can directly pass all options to the S3Manager constructor, assuming we will be adding more options in the future.

Suggested change
await app.decorate("s3Manager", new S3Manager(region));
await app.decorate("s3Manager", new S3Manager(options));

@@ -41,6 +42,8 @@ const app = async ({
port: settings.MongoDbPort,
},
});
console.log(settings.StreamFilesS3Region)
await server.register(S3Manager, settings.StreamFilesS3Region);
Copy link
Member

Choose a reason for hiding this comment

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

Then we will be calling this plugin registration with an option object:

Suggested change
await server.register(S3Manager, settings.StreamFilesS3Region);
await server.register(S3Manager, {region: settings.StreamFilesS3Region});

components/log-viewer-webui/server/src/S3Manager.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}`;

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