Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement conditional requests #352

Merged
merged 2 commits into from
Jan 12, 2025
Merged

Conversation

Southclaws
Copy link
Owner

  • currently only applies to single thread get
  • still exploring internal API design for this
  • will maybe look at proper caching layer too

- currently only applies to single thread get
- still exploring internal API design for this
- will maybe look at proper caching layer too
Copy link

vercel bot commented Jan 11, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
storyden ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 11, 2025 10:37pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
storyden-homepage ⬜️ Ignored (Inspect) Visit Preview Jan 11, 2025 10:37pm

Copy link

coderabbitai bot commented Jan 11, 2025

📝 Walkthrough

Walkthrough

This pull request introduces a comprehensive HTTP caching mechanism across the application's backend and frontend. A new cachecontrol package is created to handle conditional requests, enabling efficient resource retrieval by checking if content has been modified. The implementation spans multiple components, including a new thread_cache for database-level caching, updates to HTTP transport bindings, and modifications to the client-side API handling. The changes aim to optimize resource fetching by leveraging HTTP conditional request headers like If-Modified-Since and If-None-Match.

Changes

File Change Summary
app/resources/cachecontrol/query.go Added new package with Query struct for handling HTTP conditional requests, including methods for checking resource modifications
app/resources/post/thread_cache/cache.go Introduced Cache struct for checking post modification status using database queries
app/resources/resources.go Added import and dependency injection for thread_cache package
app/transports/http/bindings/threads.go Updated Threads struct to include thread caching, modified ThreadGet method to support conditional requests
app/transports/http/openapi/server_gen.go Added new types and fields for handling If-Modified-Since and If-None-Match headers
web/src/api/client.ts Modified request construction to include default caching behavior
web/src/api/common.ts Added optional cache property to request options
web/src/api/openapi-client/threads.ts Updated error handling types for thread retrieval
web/src/api/server.ts Adjusted server-side fetcher revalidation and caching parameters

Possibly related PRs

  • re-enable cache #347: Introduces caching property in request options, similar to the caching mechanisms in this PR

Poem

🐰 Hop, hop, through cache's domain,
Conditional requests, no data strain!
ETag whispers, "Nothing's new,"
304 response, a rabbit's breakthrough!
Efficiency dancing, byte by byte! 🚀

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

- server fetch is force-cache, 60s revalidation
- client fetch is default behaviour which will trigger HTTP Conditional Requests
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (8)
app/resources/post/thread_cache/cache.go (1)

26-40: Consider enhancing error handling and documentation

The IsNotModified implementation could be improved in several ways:

  1. Add documentation explaining the function's behavior with examples
  2. Consider implementing ETag support alongside the timestamp check
  3. Use more specific error handling for database errors (e.g., not found vs other errors)
+// IsNotModified checks if a post has been modified since the last request.
+// It supports conditional requests using If-Modified-Since headers.
+//
+// Example:
+//   notModified, err := cache.IsNotModified(ctx, query, postID)
+//   if err != nil {
+//     return err
+//   }
+//   if notModified {
+//     return 304 // Not Modified
+//   }
 func (c *Cache) IsNotModified(ctx context.Context, cq opt.Optional[cachecontrol.Query], id xid.ID) (bool, error) {
     query, ok := cq.Get()
     if !ok {
         return false, nil
     }

     r, err := c.db.Post.Query().Select(post.FieldUpdatedAt).Where(post.ID(id)).Only(ctx)
     if err != nil {
-        return false, fault.Wrap(err, fctx.With(ctx))
+        if ent.IsNotFound(err) {
+            return false, fault.Wrap(err, fctx.With(ctx, "post_not_found"))
+        }
+        return false, fault.Wrap(err, fctx.With(ctx, "database_error"))
     }

     notModified := query.NotModified(r.UpdatedAt)

     return notModified, nil
 }
app/resources/cachecontrol/query.go (1)

59-61: Enhance time parsing robustness

The time parsing implementation could be more robust by supporting multiple date formats commonly used in HTTP headers.

 func parseConditionalRequestTime(in openapi.IfModifiedSince) (time.Time, error) {
-    return time.Parse(time.RFC1123, in)
+    // Try parsing with different HTTP date formats
+    formats := []string{
+        time.RFC1123,
+        time.RFC1123Z,
+        time.RFC850,
+        time.ANSIC,
+    }
+    
+    var parseErr error
+    for _, format := range formats {
+        if t, err := time.Parse(format, in); err == nil {
+            return t, nil
+        } else {
+            parseErr = err
+        }
+    }
+    return time.Time{}, parseErr
 }
web/src/api/server.ts (1)

25-40: Consider dynamic revalidation periods

While the current implementation uses a fixed 60-second revalidation period, consider making it dynamic based on content type or user interaction patterns.

The revalidation period could be adjusted based on:

  • Content type (e.g., shorter for frequently updated content)
  • User interaction patterns (e.g., longer for static content)
  • Time of day (e.g., shorter during peak hours)
web/src/api/common.ts (1)

14-14: Add documentation for cache options

Consider adding JSDoc comments explaining the available cache options and their implications.

+/**
+ * Cache options for requests:
+ * - "default": Use browser's default cache behavior
+ * - "force-cache": Force cache use without revalidation
+ * - "no-cache": Validate cached response with server
+ * - "no-store": Don't use cache
+ * - "only-if-cached": Use cache only, fail if not cached
+ * - "reload": Bypass cache for request
+ */
 cache?: RequestCache;
app/transports/http/bindings/threads.go (1)

236-242: Consider increasing the Cache-Control max-age value.

The current max-age=1 is very short and might lead to unnecessary revalidation requests. Consider increasing this value based on your content update patterns.

-				CacheControl: "max-age=1",
+				CacheControl: "max-age=300", // 5 minutes, adjust based on your needs
web/src/api/openapi-client/threads.ts (1)

161-162: Replace void with undefined in union types.

Using void in union types can be confusing. In TypeScript, undefined is more idiomatic for representing the absence of a value in this context.

export type ThreadGetQueryError =
-  | void
+  | undefined
  | UnauthorisedResponse
  | NotFoundResponse
  | InternalServerErrorResponse;

export const useThreadGet = <
  TError =
-    | void
+    | undefined
    | UnauthorisedResponse
    | NotFoundResponse
    | InternalServerErrorResponse,
>

Also applies to: 171-172

🧰 Tools
🪛 Biome (1.9.4)

[error] 161-162: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)

app/transports/http/openapi/server_gen.go (1)

26799-26812: Consider using a safer string conversion for header values.

While the implementation is functional, using fmt.Sprint for header values might not handle all edge cases correctly.

Consider this safer approach:

-w.Header().Set("Cache-Control", fmt.Sprint(response.Headers.CacheControl))
-w.Header().Set("ETag", fmt.Sprint(response.Headers.ETag))
-w.Header().Set("Last-Modified", fmt.Sprint(response.Headers.LastModified))
+w.Header().Set("Cache-Control", response.Headers.CacheControl)
+w.Header().Set("ETag", response.Headers.ETag)
+w.Header().Set("Last-Modified", response.Headers.LastModified)
web/src/api/client.ts (1)

8-17: LGTM! Consider making cache behavior configurable.

The implementation correctly leverages browser's built-in caching mechanisms and works well with SWR. However, consider making the cache behavior configurable through the Options type for cases where different caching strategies might be needed.

export const fetcher = async <T>(opts: Options): Promise<T> => {
  const request = buildRequest({
    ...opts,
-   cache: "default",
+   cache: opts.cache ?? "default",
  });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a5c8215 and 9b608bb.

⛔ Files ignored due to path filters (1)
  • api/openapi.yaml is excluded by !**/*.yaml
📒 Files selected for processing (9)
  • app/resources/cachecontrol/query.go (1 hunks)
  • app/resources/post/thread_cache/cache.go (1 hunks)
  • app/resources/resources.go (2 hunks)
  • app/transports/http/bindings/threads.go (5 hunks)
  • app/transports/http/openapi/server_gen.go (7 hunks)
  • web/src/api/client.ts (1 hunks)
  • web/src/api/common.ts (3 hunks)
  • web/src/api/openapi-client/threads.ts (2 hunks)
  • web/src/api/server.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
web/src/api/openapi-client/threads.ts

[error] 161-162: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)


[error] 171-172: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)

🔇 Additional comments (10)
app/resources/resources.go (1)

43-43: LGTM! Clean dependency injection setup.

The thread cache integration follows the established dependency injection pattern.

Also applies to: 76-76

app/transports/http/bindings/threads.go (1)

219-226: LGTM! Clean implementation of conditional requests.

The implementation correctly handles HTTP conditional requests using If-None-Match and If-Modified-Since headers.

app/transports/http/openapi/server_gen.go (6)

3076-3081: LGTM! Well-defined type aliases for HTTP caching headers.

The type definitions for IfModifiedSince and IfNoneMatch are correctly defined as string aliases, following HTTP header naming conventions.


3808-3813: LGTM! Well-structured parameter additions for cache control.

The new fields are properly defined as optional pointers with appropriate JSON tags and clear documentation.


11462-11486: LGTM! Robust header handling implementation.

The implementation correctly sets conditional request headers with proper error handling and parameter styling.


21906-21936: LGTM! Thorough header parsing with validation.

The implementation includes proper validation of header value counts and clear error messages.


22284-22293: LGTM! Well-structured response types for cache headers.

The response types properly encapsulate all necessary cache control headers.


30319-30694: Generated swagger specification.

Skipping review of generated code.

web/src/api/client.ts (2)

8-19: Verify cache implementation scope.

The PR objectives mention this is for single-threaded GET requests, but the current implementation applies to all requests. We should either:

  1. Add a check to only enable caching for GET requests, or
  2. Document why the broader implementation is intentional.

Let's verify the request types being cached:

✅ Verification successful

Cache implementation correctly aligns with GET-only objective

The current implementation using cache: "default" is correct because:

  • Browser's default caching behavior naturally only applies to GET requests
  • Non-GET requests bypass cache by default in browsers
  • The implementation is well documented, explaining integration with SWR and browser's HTTP Conditional Requests
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for request method checks in the codebase
rg -A 5 "method.*GET" --type ts

Length of output: 26211


13-15: Please clarify the server-side performance impact.

The comment mentions that the experience is "slowed down a bit by the server side behaviour" but doesn't provide details. This information would be valuable for future maintenance and optimization.

Let's check the server-side implementation:

✅ Verification successful

Server-side caching trade-offs are well documented

The server-side implementation uses a 60-second cache with force-cache strategy. This can result in either:

  • Best case: Single database read with a 304 Not Modified response
  • Worst case: Two database reads when content changes or on first visit

The slight performance impact is a conscious trade-off between data freshness and server load, which will improve once Next.js adds native support for HTTP Conditional Requests and ETag headers.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for server-side caching implementation
rg -l "ETag|If-None-Match|If-Modified-Since" --type go

Length of output: 134


Script:

#!/bin/bash
# Check the implementation details
cat app/resources/cachecontrol/query.go

# Look for any performance-related comments
rg -i "performance|slow" -C 3 --type go

Length of output: 11064


Script:

#!/bin/bash
# Find and check server.ts files
fd server.ts

# If found, check their content for performance-related comments
rg -i "performance|slow|cache|etag" -C 3 --type typescript

Length of output: 232


Script:

#!/bin/bash
# Check the content of the server.ts file
cat web/src/api/server.ts

Length of output: 2382

Comment on lines +40 to +57
func (q Query) NotModified(resourceUpdated time.Time) bool {
// truncate the resourceUpdated to the nearest second because the actual
// HTTP header is already truncated but the database time is in nanoseconds.
// If we didn't do this, the resource updated will always be slightly ahead.
truncated := resourceUpdated.Truncate(time.Second)

if ms, ok := q.ModifiedSince.Get(); ok {

// If the resource update time is ahead of the HTTP Last-Modified check,
// modified = 1, meaning the resource has been modified since the last
// request and should be returned from the DB, instead of a 304 status.
modified := truncated.Compare(ms)

return modified <= 0
}

return false
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider implementing ETag comparison

The NotModified method currently only checks If-Modified-Since. Consider implementing ETag comparison for better caching support.

 func (q Query) NotModified(resourceUpdated time.Time) bool {
     // truncate the resourceUpdated to the nearest second because the actual
     // HTTP header is already truncated but the database time is in nanoseconds.
     // If we didn't do this, the resource updated will always be slightly ahead.
     truncated := resourceUpdated.Truncate(time.Second)
 
+    // Check ETag first if available
+    if etag, ok := q.ETag.Get(); ok {
+        // TODO: Implement ETag comparison logic
+        // This would require the resource to provide its current ETag
+        // return resourceEtag == etag
+    }
+
     if ms, ok := q.ModifiedSince.Get(); ok {
         // If the resource update time is ahead of the HTTP Last-Modified check,
         // modified = 1, meaning the resource has been modified since the last
         // request and should be returned from the DB, instead of a 304 status.
         modified := truncated.Compare(ms)
 
         return modified <= 0
     }
 
     return false
 }

Committable suggestion skipped: line range outside the PR's diff.

@Southclaws Southclaws merged commit d4cf781 into main Jan 12, 2025
4 checks passed
@Southclaws Southclaws deleted the server-side-conditional-cache branch January 12, 2025 12:07
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.

1 participant