Skip to content

feat!: Custom CacheControl header per file - #167

Merged
nielsenko merged 9 commits into
serverpod:mainfrom
nielsenko:custom-cache-control-per-file
Sep 19, 2025
Merged

nielsenko merged 9 commits into
serverpod:mainfrom
nielsenko:custom-cache-control-per-file

Conversation

@nielsenko

@nielsenko nielsenko commented Sep 15, 2025 •

Copy link
Copy Markdown
Collaborator

Description

Allow Cache-Control header to be set per file.

Related Issues

Pre-Launch Checklist

Please ensure that your PR meets the following requirements before submitting:

  • This update focuses on a single feature or bug fix. (For multiple fixes, please submit separate PRs.)
  • I have read and followed the Dart Style Guide and formatted the code using dart format.
  • I have referenced at least one issue this PR fixes or is related to.
  • I have updated/added relevant documentation (doc comments with ///), ensuring consistency with existing project documentation.
  • I have added new tests to verify the changes.
  • All existing and new tests pass successfully.
  • I have documented any breaking changes below.

Breaking Changes

  • Includes breaking changes.
  • No breaking changes.

Changes the interface of createStaticHandler and createFileHandler.

Summary by CodeRabbit

  • New Features
    • Static and file handlers now support a per-file Cache-Control callback, enabling tailored caching headers.
    • Handlers receive richer file metadata to inform caching and response behavior.
  • Bug Fixes
    • More robust content-type detection, including safer handling of empty files.
    • Improved consistency for range and conditional requests (If-Range, ETag/Last-Modified).
  • Refactor
    • Unified file metadata flow across file-serving paths for clearer, more reliable behavior.
  • Documentation
    • Minor wording improvements in comments to clarify GET/HEAD behavior and caching notes.

@coderabbitai

coderabbitai Bot commented Sep 15, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

Public API updated to introduce FileInfo and per-file cache-control callbacks. Static file serving internals were refactored to operate on FileInfo, adjust MIME detection, and propagate FileInfo through range and header-building logic. Tests were updated to pass function-typed cacheControl arguments and a new per-file caching test was added.

Changes

Cohort / File(s) Summary of Changes
Static handler core refactor
lib/src/io/static/static_handler.dart
Introduced public FileInfo (replacing private _FileInfo), added file reference and isStale; refactored LRU cache types; shifted all serving paths to use FileInfo; added Stream.firstOrNull; modified MIME detection and range handling to use FileInfo; updated header-building; changed createStaticHandler/createFileHandler to accept per-file cacheControl callback.
Tests — API parameter migration
test/static/alternative_root_test.dart, test/static/basic_file_test.dart, test/static/content_type_test.dart, test/static/default_handler_test.dart, test/static/get_handler_test.dart, test/static/if_modified_since_test.dart, test/static/if_none_match_test.dart, test/static/if_range_test.dart, test/static/not_found_test.dart, test/static/range_edge_cases_test.dart, test/static/range_test.dart, test/static/symbolic_link_test.dart, test/static/unsupported_methods_test.dart
Replaced cacheControl: null with a function-typed argument: cacheControl: (final _) => null across all call sites; no behavioral changes asserted.
Tests — cache-control feature coverage
test/static/cache_control_test.dart
Expanded fixtures; updated to function-typed cacheControl; added a per-file caching test that applies Cache-Control only to jpg files; retained existing global header test via callback.
Tests — file handler API migration
test/static/create_file_handler_test.dart
Updated invocations of createFileHandler to include cacheControl: (final _) => null, aligning with new signature; no changes to expectations.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant C as Client
    participant H as StaticHandler
    participant L as LruCache
    participant FS as FileSystem
    participant CC as CacheControlCallback
    participant M as MimeResolver

    C->>H: HTTP GET/HEAD /path
    H->>L: Lookup FileInfo by key
    alt Cache miss or stale
        H->>FS: stat(path), openRead(...)
        FS-->>H: File, FileStat, header bytes
        H->>M: resolve mimeType(header bytes, extension)
        M-->>H: mimeType
        H->>L: Put(FileInfo)
    end
    H->>CC: cacheControl(fileInfo)
    CC-->>H: CacheControlHeader? (per-file)
    alt Conditional headers (If-None-Match/If-Modified-Since)
        H-->>C: 304 Not Modified + headers
    else Range request
        H-->>C: 206 Partial Content + headers + range body
    else Full content
        H-->>C: 200 OK + headers + file body
    end
    note over H: All read paths use fileInfo.file.openRead(...)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The PR description includes a clear summary, related issue reference (Closes: #168), and a completed checklist, but it contains a material contradiction in the "Breaking Changes" section: it both notes interface changes to createStaticHandler/createFileHandler and marks "No breaking changes." This omission is important because the signature changes and the new FileInfo type affect public API consumers and require explicit migration guidance. Update the "Breaking Changes" section to accurately describe the changed signatures (createStaticHandler/createFileHandler) and the introduction of the public FileInfo class, provide concrete migration steps/examples for callers, and confirm the changelog and public docs are updated before merging.
✅ Passed checks (4 passed)
Check name Status Explanation
Title Check ✅ Passed The title succinctly and accurately describes the primary change: adding per-file Cache-Control support. It is concise, specific to the main change (createStaticHandler/createFileHandler behavior), and easily understood by reviewers scanning history.
Linked Issues Check ✅ Passed The changes implement the linked issue's objective by introducing a cacheControl callback that receives FileInfo, propagating FileInfo through the handler flow, and adding tests (including a per-file caching test) that verify the callback can select headers per file. The implementation and test updates align with the requested per-file Cache-Control capability.
Out of Scope Changes Check ✅ Passed Most additional changes appear to be necessary supporting work for the per-file Cache-Control feature (making FileInfo public, adding file/isStale, updating the LRU cache, and plumbing FileInfo through file-serving paths); smaller refactors like the Stream.firstOrNull and MIME-detection tweaks look like internal robustness improvements rather than unrelated new features. I did not find functionality unrelated to the stated objective.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

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.

@codecov

codecov Bot commented Sep 15, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.42857% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 91.77%. Comparing base (b708b9b) to head (7eb0fdd).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
lib/src/io/static/static_handler.dart 96.42% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #167      +/-   ##
==========================================
- Coverage   91.82%   91.77%   -0.06%     
==========================================
  Files          85       85              
  Lines        3118     3123       +5     
  Branches     1616     1618       +2     
==========================================
+ Hits         2863     2866       +3     
- Misses        255      257       +2     

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@nielsenko
nielsenko force-pushed the custom-cache-control-per-file branch 2 times, most recently from 516aad6 to d12c15b Compare September 15, 2025 10:17
Comment thread lib/src/io/static/static_handler.dart Resolved
@nielsenko
nielsenko force-pushed the custom-cache-control-per-file branch from 940315e to 1496401 Compare September 15, 2025 10:47
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Sep 15, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 29

♻️ Duplicate comments (1)
lib/src/io/static/static_handler.dart (1)

109-113: Breaking change in createFileHandler needs the same backward compatibility treatment

Similar to createStaticHandler, this function now requires the cacheControl parameter, creating a breaking change.

🧹 Nitpick comments (3)
lib/src/io/static/static_handler.dart (2)

449-456: Consider moving the Stream extension to a utility module

The firstOrNull extension on Stream<T> is useful but placing it at the end of this file makes it less discoverable and could lead to duplication if needed elsewhere.

Consider moving this extension to a shared utility module (e.g., lib/src/utils/stream_extensions.dart) where it can be reused across the codebase:

// In lib/src/utils/stream_extensions.dart
extension StreamExtensions<T> on Stream<T> {
  Future<T?> get firstOrNull async {
    await for (final value in this) {
      return value;
    }
    return null;
  }
}

Then import it in this file:

import '../../utils/stream_extensions.dart';

25-29: Potential performance concern with frequent stat calls

The isStale getter calls file.statSync() on every access, which could be expensive if called frequently. Consider caching the fresh stat temporarily or documenting the performance implications.

Consider either:

  1. Document that isStale performs file I/O and should be used judiciously
  2. Or implement a time-based cache for the fresh stat to avoid excessive I/O:
class FileInfo {
  final File file;
  final MimeType? mimeType;
  final FileStat stat;
  final String etag;
  
  // Cache fresh stat for a short duration
  FileStat? _cachedFreshStat;
  DateTime? _cacheTime;
  static const _cacheExpiry = Duration(milliseconds: 100);

  bool get isStale {
    final now = DateTime.now();
    if (_cachedFreshStat == null || 
        _cacheTime == null ||
        now.difference(_cacheTime!) > _cacheExpiry) {
      _cachedFreshStat = file.statSync();
      _cacheTime = now;
    }
    return stat.size != _cachedFreshStat!.size ||
        stat.changed.isBefore(_cachedFreshStat!.changed);
  }

  const FileInfo(this.file, this.mimeType, this.stat, this.etag);
}
test/static/cache_control_test.dart (1)

65-69: Tighten JPG match to avoid false positives.

endsWith('jpg') can match unintended paths; include the dot.

-      cacheControl: (final fileInfo) =>
-          fileInfo.file.path.endsWith('jpg') ? cacheControl : null,
+      cacheControl: (final fileInfo) =>
+          fileInfo.file.path.toLowerCase().endsWith('.jpg') ? cacheControl : null,
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 44378bc and 1496401.

📒 Files selected for processing (16)
  • lib/src/io/static/static_handler.dart (15 hunks)
  • test/static/alternative_root_test.dart (5 hunks)
  • test/static/basic_file_test.dart (14 hunks)
  • test/static/cache_control_test.dart (3 hunks)
  • test/static/content_type_test.dart (3 hunks)
  • test/static/create_file_handler_test.dart (11 hunks)
  • test/static/default_handler_test.dart (1 hunks)
  • test/static/get_handler_test.dart (1 hunks)
  • test/static/if_modified_since_test.dart (1 hunks)
  • test/static/if_none_match_test.dart (1 hunks)
  • test/static/if_range_test.dart (1 hunks)
  • test/static/not_found_test.dart (1 hunks)
  • test/static/range_edge_cases_test.dart (1 hunks)
  • test/static/range_test.dart (1 hunks)
  • test/static/symbolic_link_test.dart (4 hunks)
  • test/static/unsupported_methods_test.dart (1 hunks)
🔇 Additional comments (6)
lib/src/io/static/static_handler.dart (2)

19-32: FileInfo class looks good with efficient staleness check

The new public FileInfo class is well-designed. The isStale getter efficiently detects file changes by comparing size and modification time, which is appropriate for cache invalidation.


208-208: Good defensive programming with firstOrNull extension

The change from first to firstOrNull is a good defensive programming practice that prevents exceptions when dealing with empty streams.

test/static/if_range_test.dart (1)

16-16: Test correctly updated for new API

The test has been properly updated to pass a function for the cacheControl parameter. The use of (final _) => null clearly indicates that cache control is disabled for this test.

test/static/unsupported_methods_test.dart (1)

15-15: Test properly migrated to new API

The test correctly uses the new function-based cacheControl parameter.

test/static/if_modified_since_test.dart (1)

15-15: Consistent test API usage

Test properly updated to use the new cacheControl function parameter.

test/static/not_found_test.dart (1)

16-16: Test migration complete

The test has been correctly updated to use the new function-based cacheControl API.

Comment thread lib/src/io/static/static_handler.dart Resolved
Comment thread test/static/alternative_root_test.dart Resolved
Comment thread test/static/basic_file_test.dart Resolved
Comment thread test/static/cache_control_test.dart Resolved
Comment thread test/static/content_type_test.dart Resolved
Comment thread test/static/range_test.dart Resolved
Comment thread test/static/symbolic_link_test.dart Resolved
Comment thread test/static/symbolic_link_test.dart Resolved
Comment thread test/static/symbolic_link_test.dart Resolved
Comment thread test/static/symbolic_link_test.dart Resolved
@nielsenko
nielsenko marked this pull request as ready for review September 15, 2025 11:21
@nielsenko
nielsenko requested a review from a team September 15, 2025 11:21
@nielsenko nielsenko self-assigned this Sep 15, 2025
@nielsenko nielsenko mentioned this pull request Sep 17, 2025
8 of 9 tasks

@SandPod SandPod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A couple of questions and a test fix requirement.

Comment thread lib/src/io/static/static_handler.dart Resolved
Comment thread test/static/cache_control_test.dart Resolved
Comment thread lib/src/io/static/static_handler.dart Resolved
Comment thread lib/src/io/static/static_handler.dart Resolved
@nielsenko
nielsenko force-pushed the custom-cache-control-per-file branch from a8f3e11 to 2a7d78f Compare September 18, 2025 11:18
@nielsenko
nielsenko requested a review from SandPod September 18, 2025 11:59
@nielsenko
nielsenko force-pushed the custom-cache-control-per-file branch from a50f10c to 7eb0fdd Compare September 18, 2025 13:34
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@SandPod Please disregard the minor fall in code-coverage

@SandPod SandPod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM! 👍

@nielsenko
nielsenko merged commit acef84f into serverpod:main Sep 19, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Oct 6, 2025
6 of 7 tasks
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.

Allow CacheControl header to be set per file

2 participants