Repository navigation
feat: Implement automatic static file cache busting - #3969
nicowalter256 wants to merge 2 commits into
Conversation
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the ✨ Finishing touches🧪 Generate unit tests
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. Comment |
- 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
7a78b52 to
3c353f2
Compare
nielsenko
left a comment
There was a problem hiding this comment.
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.
| /// 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'); | ||
| } |
| /// 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'; | ||
| } |
There was a problem hiding this comment.
Can we get rid of this? Has weird semantics.
| static Future<String?> assetUrl(String assetPath) async { | ||
| return await StaticAssetManager().assetUrl(assetPath); | ||
| } |
There was a problem hiding this comment.
Why do we need a separate class for this?
| /// Returns the singleton instance. | ||
| factory StaticAssetManager() => _instance; | ||
|
|
||
| StaticAssetManager._internal(); |
There was a problem hiding this comment.
| StaticAssetManager._internal(); | |
| StaticAssetManager._(); |
|
|
||
| /// Creates a new instance of [StaticAssetManager]. | ||
| /// Returns the singleton instance. | ||
| factory StaticAssetManager() => _instance; |
There was a problem hiding this comment.
Not fan of this singleton pattern. Global state makes testing difficult.
| } | ||
|
|
||
| // Cache the result | ||
| _hashCache[filePath] = _HashCacheEntry(hash, lastModified); |
There was a problem hiding this comment.
Have you considered removing then adding, so it goes to the end of your _hashCache which is a LinkedHashMap? This will make _cleanupCache simpler.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I've refactored the cache to use LinkedHashMap's insertion order for true LRU behavior
| var entries = _hashCache.entries.toList(); | ||
| entries | ||
| .sort((a, b) => a.value.lastModified.compareTo(b.value.lastModified)); |
There was a problem hiding this comment.
If you kept the LinkedHashMap ordered by access, then you could avoid this sort.
| var bytes = await file.readAsBytes(); | ||
| var hash = _sha256(bytes); |
There was a problem hiding this comment.
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') }}"> |
There was a problem hiding this comment.
How is this supposed to work? How will the template engine call out to assetUrl?
BTW, this example project is missing pubspec.yaml
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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).
|
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.
|
@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? |
|
@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. |
|
I have reached out to you in a separate issue. Closing this with the motivation above. |
Features: