[Cookies] Refactor for Allocation Improvements, RFC 6265bis Compliance, and SPA Support#777
Open
PingoLee wants to merge 2 commits into
Open
[Cookies] Refactor for Allocation Improvements, RFC 6265bis Compliance, and SPA Support#777PingoLee wants to merge 2 commits into
PingoLee wants to merge 2 commits into
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
This PR performs a major refactor of the
Genie.Cookiesmodule to improve performance, strictness, and compliance with modern browser standards (RFC 6265bis), specifically targeting better support for Single Page Applications (SPAs) like Quasar.Key Changes
Zero-Allocation Retrieval: Replaced
splitandDictcreation in critical hot paths withSubStringviews and iterator-based parsing (eachspliton Julia 1.9+). This significantly reduces GC pressure when reading cookies on high-traffic endpoints.SPA & CORS Friendly: Implemented automatic enforcement of
Secure=truewhenSameSite=Noneis detected. This fixes common issues where modern browsers (Chrome/Edge) reject cross-site cookies during SPA development/production.Strict Type Safety: The
getfunction now strictly throwsArgumentErrorif a cookie exists but cannot be parsed to the requested type (e.g., requesting anIntbut receiving"undefined"). This prevents silent failures and helps detect frontend bugs or tampering.Optimized Configuration: Introduced
load_cookie_settings!in the bootstrap phase to pre-validate and normalize cookie configurations (converting Strings to Symbols/Enums once at startup), rather than per-request.Enhanced Attribute Support: Added support for legacy CamelCase attributes (
Path,HttpOnly,MaxAge,SameSite) with automatic normalization. Implemented logout pattern detection (max_age=0→expires=1970-01-01) for proper browser cookie deletion.Technical Detail: Replaced split(header, ";") which allocates arrays of strings with eachsplit (iterators) and SubString views. Parsing a cookie header now performs 0 allocations in the hot path until the specific key is found and decrypted.
Backward Compatibility (Non-Breaking)
This PR is strictly non-breaking.
cookie_defaultswas added toGenie.Configuration.Settingsinitialized asnothing.nothing. If no defaults are provided (current behavior), the system falls back to the exact previous behavior (empty Dict).Testing
Comprehensive test suite with 1970+ lines covering:
Verified integration with
GenieSessionthrough extensive unit testsdemonstrating session creation, persistence, and attribute handling.
Support & Maintenance
I am fully committed to maintaining this PR. While extensive testing has been performed to ensure backward compatibility, I am ready to promptly address any unforeseen regressions or edge cases that may arise.
Future Plans
If this PR is accepted, I plan to submit follow-up PRs to GenieSession.jl and
GenieAuthentication.jl to leverage these optimizations, ensuring the session ID
retrieval benefits from the zero-allocation parsing.
Detailed Changes
1. Simplified Response Cookie Retrieval (get)
Before: Eagerly created a full
HTTPUtils.Dictand checked both "Set-Cookie" and "set-cookie" headersAfter: Direct delegation to
nullablevalue()which handles header lookup internallyBenefit: Eliminates unnecessary Dict allocation on every request
2. Dispatcher Pattern for
nullablevalue()(Request vs Response)Design: Split
nullablevalue()into two specialized dispatchers:nullablevalue(payload::HTTP.Request, ...)- Looks for "Cookie" header (client→server)nullablevalue(payload::HTTP.Response, ...)- Looks for "Set-Cookie" header (server→client)Why separate?
Cookie: key1=val1; key2=val2vs Response usesSet-Cookie: key=val; Path=/; ...Benefit: Type-directed dispatch at compile-time, zero runtime overhead determining which header to search
3. Configuration Pre-Validation (
load_cookie_settings!())New function: Validates and normalizes cookie config at startup, not per-request
Benefit: Moves validation overhead from hot path to initialization
4. Type-Generic Parsing with
AbstractStringDesign Choice:
nullablevalue(cookie_header::AbstractString, key::Symbol, ...)Why AbstractString (not String)?
Julia's multiple dispatch system compiles specialized code for each concrete type:
eachsplit()returns aSubStringview, the function receives that view directly (zero copy)String, it would allocate and copy the entire substringInline Comments for Code Review
The
set!()andnullablevalue()functions include detailed comments explaining design decisions and optimization rationale to facilitate code review. These comments can be removed after review if preferred by the team.