Skip to content

fix: avoid partial cache entries when file loading fails - #109

Open
vibhor-aggr wants to merge 2 commits into
koajs:masterfrom
vibhor-aggr:fix/avoid-partial-file-cache-entry
Open

vibhor-aggr wants to merge 2 commits into
koajs:masterfrom
vibhor-aggr:fix/avoid-partial-file-cache-entry

Conversation

@vibhor-aggr

@vibhor-aggr vibhor-aggr commented Jun 11, 2026

Copy link
Copy Markdown

Closes #99.

loadFile() previously inserted an empty cache entry before statSync() and readFileSync() completed. If the read failed, the cache could retain a partial object with path but no mtime, letting a later request crash at file.mtime.getTime().

This builds the metadata first and only publishes the cache entry after the file has been read and hashed successfully, while preserving existing per-file metadata such as maxAge.

Verification:

  • ./node_modules/.bin/mocha --grep 'partial file data'
  • npm test
  • git diff --check

Summary by Sourcery

Ensure static file cache entries are only created after files are successfully loaded to avoid partial metadata in the cache.

Bug Fixes:

  • Prevent caching of partial file metadata when dynamic file loading fails, avoiding crashes on subsequent requests.

Tests:

  • Add a regression test that simulates a read failure and verifies no partial cache entry is stored and that a subsequent successful read is served correctly.

@coderabbitai

coderabbitai Bot commented Jun 11, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@vibhor-aggr, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 10 minutes and 43 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more credits in the billing tab to continue.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 285b567b-20aa-44ac-bbb6-95830ad20b67

📥 Commits

Reviewing files that changed from the base of the PR and between 182f260 and 1a65596.

📒 Files selected for processing (2)
  • index.js
  • test/index.js

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@sourcery-ai

sourcery-ai Bot commented Jun 11, 2026

Copy link
Copy Markdown

Reviewer's Guide

Refactors file loading to build full metadata objects before inserting them into the cache and adds regression coverage to ensure failed dynamic loads do not leave partial cache entries.

Sequence diagram for updated loadFile cache insertion

sequenceDiagram
  participant Caller
  participant loadFile
  participant fs
  participant files

  Caller->>loadFile: loadFile(name, dir, options, files)
  loadFile->>fs: statSync(filename)
  fs-->>loadFile: stats
  loadFile->>fs: readFileSync(filename)
  fs-->>loadFile: buffer
  loadFile->>loadFile: [build obj metadata]
  loadFile->>files: set(pathname, obj)
  loadFile-->>Caller: obj
Loading

File-Level Changes

Change Details Files
Ensure file cache entries are only published after a successful stat and read, preserving existing per-file metadata.
  • Change loadFile to construct or reuse a metadata object locally without immediately storing it in the cache map.
  • Populate path, cacheControl, maxAge, type, mtime, length, md5, and optional buffer only after fs.statSync and fs.readFileSync succeed.
  • Store the fully populated metadata object back into the cache map once all fields are set.
index.js
Add a regression test that simulates a transient read failure to verify no partial cache entry is stored and subsequent requests succeed.
  • Introduce mz/fs and os test dependencies to support intercepting readFileSync and creating temporary directories.
  • Add a new test that overrides mzfs.readFileSync to fail once for a specific file while using dynamic, non-preloaded staticCache.
  • Verify that after a 500 response on failed read, no cache entry exists for the file and a subsequent request returns 200 with the correct body.
test/index.js

Assessment against linked issues

Issue Objective Addressed Explanation
#99 Fix the intermittent TypeError 'Cannot read property "getTime" of undefined' when using static-cache for static file hosting.
#99 Add a regression test ensuring that failed dynamic file loads do not leave partial cache entries that can cause runtime errors later.

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!

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

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've left some high level feedback:

  • In the new test, you're monkeypatching mzfs.readFileSync, but loadFile uses fs.readFileSync, so the failure path you're trying to exercise may never be hit; consider patching the actual fs.readFileSync (or whatever the production code uses) to ensure the test is meaningful.
  • To make the new test more robust, you could guard cleanup() with try/catch or use fs.rmSync(dir, { recursive: true, force: true }) so failures during unlink/rmdir don't mask assertions or leak resources when the test fails midway.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In the new test, you're monkeypatching `mzfs.readFileSync`, but `loadFile` uses `fs.readFileSync`, so the failure path you're trying to exercise may never be hit; consider patching the actual `fs.readFileSync` (or whatever the production code uses) to ensure the test is meaningful.
- To make the new test more robust, you could guard `cleanup()` with try/catch or use `fs.rmSync(dir, { recursive: true, force: true })` so failures during unlink/rmdir don't mask assertions or leak resources when the test fails midway.

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.

@vibhor-aggr

Copy link
Copy Markdown
Author

Thanks for the review. I rechecked the current head 1a65596f89913c57ef7b7d75e48f89467af91004. The partial-cache regression test patches mz/fs.readFileSync, which is the same module instance used by production loadFile() in index.js, so the dynamic load failure path is exercised. The cleanup path also restores the monkeypatch, closes the server, and guards file/directory removal so cleanup failures do not mask assertions.

Verified locally with Node v24.16.0:

  • ./node_modules/.bin/mocha --grep "partial file data": 1 passing
  • npm test: 38 passing
  • git diff --check master..HEAD: 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.

Cannot read property 'getTime' of undefined

1 participant