Skip to content

Conversation

cnlangzi
Copy link
Member

@cnlangzi cnlangzi commented Jan 25, 2025

Changed

Fixed

Added

Tests

Tasks to complete before merging PR:

  • Ensure unit tests are passing. If not run make unit-test to check for any regressions 📋
  • Ensure lint tests are passing. if not run make lint to check for any issues
  • Ensure codecov/patch is passing for changes.

Summary by Sourcery

Bug Fixes:

  • Fixed an issue where the Last-Modified and ETag headers were not being set correctly for embedded files.

Copy link

sourcery-ai bot commented Jan 25, 2025

Reviewer's Guide by Sourcery

This pull request addresses an issue where the Last-Modified and ETag headers were not being set correctly for embedded files. The changes ensure that these headers are properly set, which improves caching and reduces unnecessary data transfer.

Sequence diagram for FileViewer handling embedded files

sequenceDiagram
    participant Client
    participant FileViewer
    participant FileSystem

    Client->>FileViewer: GET request with If-None-Match
    alt is embedded file
        FileViewer->>FileViewer: Check ETag
        alt ETag matches
            FileViewer-->>Client: 304 Not Modified
        else ETag doesn't match
            FileViewer->>FileSystem: Open file
            FileSystem-->>FileViewer: File content
            FileViewer-->>Client: 200 OK with content and ETag
        end
    else not embedded file
        FileViewer->>FileSystem: Open file
        FileSystem-->>FileViewer: File content
        FileViewer-->>Client: Serve content with headers
    end
Loading

Class diagram showing FileViewer and StaticViewEngine changes

classDiagram
    class FileViewer {
        -fsys fs.FS
        -path string
        -isEmbed bool
        -etag string
        +MimeType() *MimeType
        +Render(w http.ResponseWriter, r *http.Request, data any) error
        -serveContent(w http.ResponseWriter, r *http.Request) error
    }

    class StaticViewEngine {
        -isEmbedFsys bool
        +Load(fsys fs.FS, app *App) error
        -handle(fsys fs.FS, app *App, path string)
    }

    note for FileViewer "Added ETag support for embedded files"
    note for StaticViewEngine "Added embed filesystem detection"
Loading

File-Level Changes

Change Details Files
Implemented ETag generation for embedded files.
  • Added a new NewFileViewer function to create FileViewer instances.
  • Modified the FileViewer struct to include isEmbed and etag fields.
  • Implemented ETag generation using SHA512 hash of the file content.
  • Set the ETag header in the Render method for embedded files.
  • Implemented handling of If-None-Match header to return 304 Not Modified when appropriate.
viewer_file.go
Modified Render method to handle both embedded and non-embedded files.
  • Added a conditional check to determine if the file is embedded.
  • If not embedded, the serveContent method is called.
  • If embedded, the ETag header is set and the If-None-Match header is checked before calling serveContent.
viewer_file.go
Added serveContent method to handle serving file content.
  • Implemented the serveContent method to open the file, get file info, and serve the content using http.ServeContent.
viewer_file.go
Modified StaticViewEngine to detect embed file systems.
  • Added a new field isEmbedFsys to the StaticViewEngine struct.
  • Set the isEmbedFsys field based on the type of the file system.
  • Pass the isEmbedFsys to the NewFileViewer function.
viewengine_static.go
Added unit tests for FileViewer.
  • Added tests for ETag generation and handling of If-None-Match header.
  • Added tests for Last-Modified header.
  • Added tests for file not found scenarios.
  • Added tests for error handling.
viewer_file_test.go

Assessment against linked issues

Issue Objective Addressed Explanation
#32 Fix Last-Modified header functionality for embedded resources

Possibly linked issues

  • #44854: The PR fixes the issue described in the issue. The PR fixes Last-Modified/ETag issue on embed file system.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

deepsource-io bot commented Jan 25, 2025

Here's the code health analysis summary for commits 4cd8e0c..a2f2ce6. View details on DeepSource ↗.

Analysis Summary

AnalyzerStatusSummaryLink
DeepSource Go LogoGo✅ Success
🎯 1 occurence resolved
View Check ↗

💡 If you’re a repository administrator, you can configure the quality gates from the settings.

Copy link

codecov bot commented Jan 25, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 90.97%. Comparing base (4cd8e0c) to head (a2f2ce6).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #33      +/-   ##
==========================================
+ Coverage   90.66%   90.97%   +0.30%     
==========================================
  Files          37       37              
  Lines        1286     1330      +44     
==========================================
+ Hits         1166     1210      +44     
  Misses         83       83              
  Partials       37       37              
Flag Coverage Δ
Unit-Tests 90.97% <100.00%> (+0.30%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @cnlangzi - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟡 General issues: 3 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

return err
}

http.ServeContent(w, r, v.path, fi.ModTime(), f.(io.ReadSeeker))
Copy link

Choose a reason for hiding this comment

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

issue (bug_risk): Unsafe type assertion to io.ReadSeeker could panic

The type assertion f.(io.ReadSeeker) will panic if the file system doesn't support seeking. Consider checking the type assertion with ok value and handle non-seeker case gracefully.

viewer_file.go Outdated

w.Header().Set("ETag", v.etag)
if match := r.Header.Get("If-None-Match"); match != "" {
if match == v.etag {
Copy link

Choose a reason for hiding this comment

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

issue: ETag comparison doesn't handle all HTTP spec cases

The If-None-Match header can contain multiple ETags and weak validators (W/ prefix). Consider using a more robust ETag comparison that handles these cases.

Copy link
Member Author

Choose a reason for hiding this comment

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

@sourcery-ai review

Copy link

Choose a reason for hiding this comment

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

Sure! I'm generating a new review now.

Copy link

Choose a reason for hiding this comment

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

Hey @cnlangzi, I've posted a new review for you!

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @cnlangzi - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider adding error logging in NewFileViewer when file open or ETag calculation fails, rather than silently continuing. This would help with debugging if issues occur.
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

return err
}

http.ServeContent(w, r, v.path, fi.ModTime(), f.(io.ReadSeeker))
Copy link

Choose a reason for hiding this comment

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

issue (bug_risk): Add type assertion check for io.ReadSeeker

This type assertion could panic if the file doesn't implement io.ReadSeeker. Consider checking the type assertion with the comma-ok pattern.

@@ -39,6 +71,40 @@
// Render serves a file from the file system using the FileViewer.
// It writes the file to the http.ResponseWriter.
func (v *FileViewer) Render(w http.ResponseWriter, r *http.Request, data any) error {
Copy link

Choose a reason for hiding this comment

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

issue (complexity): Consider simplifying the file serving logic by using http.ServeContent and setting the ETag conditionally for embedded files.

The current implementation adds unnecessary complexity by custom ETag handling and branching logic. We can simplify while preserving the embedded file optimization:

func (v *FileViewer) Render(w http.ResponseWriter, r *http.Request, data any) error {
    f, err := v.fsys.Open(v.path)
    if err != nil {
        w.WriteHeader(http.StatusNotFound)
        return nil
    }
    defer f.Close()

    fi, err := f.Stat()
    if err != nil {
        return err
    }

    if v.isEmbed {
        w.Header().Set("ETag", v.etag)
    }

    http.ServeContent(w, r, v.path, fi.ModTime(), f.(io.ReadSeeker))
    return nil
}

This simplification:

  1. Removes duplicate code paths and nested conditionals
  2. Uses http.ServeContent's built-in ETag handling for non-embedded files
  3. Preserves the pre-computed ETag optimization for embedded files
  4. Eliminates manual ETag matching since http.ServeContent handles it

@cnlangzi cnlangzi merged commit bc1170e into main Jan 25, 2025
7 checks passed
@cnlangzi cnlangzi deleted the fix/embed_cache branch January 25, 2025 08:02
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.

FileViewer: Last-Modified doesn't work
1 participant