Skip to content

feat: Implement automatic static file cache busting - #3969

Closed
nicowalter256 wants to merge 2 commits into
serverpod:mainfrom
nicowalter256:feature/automatic-static-file-cache-busting
Closed

nicowalter256 wants to merge 2 commits into
serverpod:mainfrom
nicowalter256:feature/automatic-static-file-cache-busting

Conversation

@nicowalter256

Copy link
Copy Markdown
Contributor
  • Add StaticAssetManager for on-demand hash computation and caching
  • Add StaticAssetsConfig for server startup configuration
  • Add TemplateHelpers for template integration
  • Enhance RouteStaticDirectory with automatic hash stripping and fallback
  • Support multiple hash patterns (content, Flutter, version, timestamp)
  • Add CDN URL support for static assets
  • Include comprehensive test suite with 6 passing tests
  • Add example usage documentation

Features:

  • On-demand content hashing with SHA-256
  • Automatic cache invalidation when files change
  • Memory-efficient caching with LRU cleanup
  • Robust hash pattern recognition
  • Fallback logic for file serving
  • Template integration with assetUrl() helper
  • CDN support for production deployments

@coderabbitai

coderabbitai Bot commented Sep 10, 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.

✨ Finishing touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

- Add StaticAssetManager for on-demand hash computation and caching
- Add StaticAssetsConfig for server startup configuration
- Add TemplateHelpers for template integration
- Enhance RouteStaticDirectory with automatic hash stripping and fallback
- Support multiple hash patterns (content, Flutter, version, timestamp)
- Add CDN URL support for static assets
- Include comprehensive test suite with 6 passing tests
- Add example usage documentation

Features:
- On-demand content hashing with SHA-256
- Automatic cache invalidation when files change
- Memory-efficient caching with LRU cleanup
- Robust hash pattern recognition
- Fallback logic for file serving
- Template integration with assetUrl() helper
- CDN support for production deployments
@nicowalter256
nicowalter256 force-pushed the feature/automatic-static-file-cache-busting branch from 7a78b52 to 3c353f2 Compare September 10, 2025 12:49
@nicowalter256 nicowalter256 changed the title feat: implement automatic static file cache busting feat: Implement automatic static file cache busting Sep 10, 2025

@nielsenko nielsenko left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Hi @nicowalter256 Thank you for taking the time to contribute to serverpod.

I have taken a first look at your PR. I have some questions for you, and some changes I would like you to do. I hope you can find the time to answer and address these.

Comment on lines +188 to +195
/// Simple SHA-256-like hash implementation.
String _sha256(List<int> bytes) {
var hash = 0;
for (var byte in bytes) {
hash = ((hash << 5) - hash + byte) & 0xffffffff;
}
return hash.abs().toRadixString(16).padLeft(8, '0');
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Replace with SHA256 from crypto package.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

okay

Comment on lines +27 to +35
/// Synchronous version of assetUrl for use in templates.
/// Note: This will return the asset path without hash if the file
/// hasn't been processed yet. Use the async version when possible.
static String assetUrlSync(String assetPath) {
// For synchronous templates, we can't compute hashes on-demand
// Return the original path - the static directory route will handle
// hash removal if needed
return '/$assetPath';
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Can we get rid of this? Has weird semantics.

Comment on lines +23 to +25
static Future<String?> assetUrl(String assetPath) async {
return await StaticAssetManager().assetUrl(assetPath);
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Why do we need a separate class for this?

/// Returns the singleton instance.
factory StaticAssetManager() => _instance;

StaticAssetManager._internal();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
StaticAssetManager._internal();
StaticAssetManager._();


/// Creates a new instance of [StaticAssetManager].
/// Returns the singleton instance.
factory StaticAssetManager() => _instance;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Not fan of this singleton pattern. Global state makes testing difficult.

}

// Cache the result
_hashCache[filePath] = _HashCacheEntry(hash, lastModified);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Have you considered removing then adding, so it goes to the end of your _hashCache which is a LinkedHashMap? This will make _cleanupCache simpler.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Actually this is a weird LRU. You store lastModified from the file.stat() call. Then you clean out the oldest files from _hashCache, but these may well be the hottest in the cache!? The correct approach would be to track access time in the cache.

Or just use the fact that LinkedHashMap maintains insert order.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I've refactored the cache to use LinkedHashMap's insertion order for true LRU behavior

Comment on lines +163 to +165
var entries = _hashCache.entries.toList();
entries
.sort((a, b) => a.value.lastModified.compareTo(b.value.lastModified));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

If you kept the LinkedHashMap ordered by access, then you could avoid this sort.

Comment on lines +134 to +135
var bytes = await file.readAsBytes();
var hash = _sha256(bytes);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Don't read full file into memory. Use streaming.

<head>
<title>Static Assets Example</title>
<!-- Cache-busted CSS -->
<link rel="stylesheet" href="{{ assetUrl('css/style.css') }}">

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

How is this supposed to work? How will the template engine call out to assetUrl?

BTW, this example project is missing pubspec.yaml

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Also, does this work if the assets are mounted under a custom path?

mimeType: mimeType,
);
return context.withResponse(Response.ok(body: body, headers: headers));
return await _serveFile(file, path, context);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

So, if a request arrives for a file with a specific hash, we may potentially return a file that would hash differently?! Is that intended?

We strip hash from requested file. Check if we can find it on disk (regardless of content). Then return whatever is in there, if found? Only if we don't find it we try to look for the hashed path (originalFilePath).

@vlidholt

Copy link
Copy Markdown
Collaborator

A thought on this. @nielsenko, perhaps this could mostly be done in the Relic package and the static file handler? As I understand it, does it already create hashes to be used in the headers? When looking up a path there, it could optionally remove the hash part of the name, and there could be a method that retrieves the hash for a file. The static file handler may even have some awareness of which path it is mounted under?

## Code Review Fixes

### StaticAssetManager Improvements
- Replace custom SHA-256-like hash with crypto package SHA256
- Remove singleton pattern for better testability (dependency injection)
- Implement proper LRU cache using LinkedHashMap insertion order
- Use streaming for hash computation instead of loading full files into memory
- Make _hashCache explicitly LinkedHashMap for clarity

### TemplateHelpers Refactoring
- Remove assetUrlSync method with 'weird semantics'
- Use static reference to singleton instead of creating new instances
- Update documentation to recommend RouteStaticDirectory approach

### Static Assets Example
- Create complete working example with proper pubspec.yaml
- Fix template integration issues (remove async assetUrl calls)
- Add example static files (CSS, JS, images)
- Create proper widget structure
- Fix Protocol class to properly extend SerializationManagerServer
- Resolve all dependency and compilation errors

## Key Improvements
- Better performance: O(1) LRU operations instead of O(n log n) sorting
- Memory efficiency: Streaming hash computation for large files
- Testability: Removed global state, added dependency injection
- Clarity: Explicit types and proper documentation
- Working example: Complete static assets demonstration

Addresses all code review comments from nielsenko and vlidholt.
@SandPod

SandPod commented Sep 12, 2025

Copy link
Copy Markdown
Contributor

@nicowalter256 - Thanks for the swift work of drafting up an implementation on this.

However, after reviewing the code, we have realized that we need to rethink the specification of this feature before it can be implemented.

I suggest we close this PR, and I'll direct you towards a more refined feature you could support us with.

Does that sound OK with you?

@nicowalter256

Copy link
Copy Markdown
Contributor Author

@SandPod Thanks for the feedback. That sounds good to me. Please go ahead and point me towards the refined feature—I’d be happy to contribute there.

@SandPod

SandPod commented Sep 12, 2025 •

Copy link
Copy Markdown
Contributor

I have reached out to you in a separate issue.

Closing this with the motivation above.

@SandPod SandPod closed this Sep 12, 2025
@github-actions github-actions Bot locked and limited conversation to collaborators Sep 12, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants