-
Notifications
You must be signed in to change notification settings - Fork 10k
[Workers] Expliclity call out Cache Reserve incompatibility - WIP - DO NOT MERGE #17017
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
Closed
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -17,6 +17,12 @@ description: Cache POST requests using the Cache API. | |
|
|
||
| import { TabItem, Tabs } from "~/components"; | ||
|
|
||
| POST requests can be cached either via Cache API or [Workers KV](/kv/). | ||
|
|
||
| ## Using Cache API | ||
|
|
||
| The Cache API allows for a simple API to cache POST requests. However, Cache API does not [support the use of Tiered Caching or Reserve Reserve](/workers/reference/how-the-cache-works/#cache-api). To increase Cache Hit Rates and offload origin load, consider using Workers KV instead (see below). | ||
|
|
||
| <Tabs syncKey="workersExamples"> <TabItem label="JavaScript" icon="seti:javascript"> | ||
|
|
||
| ```js | ||
|
|
@@ -148,3 +154,114 @@ async def on_fetch(request, _, ctx): | |
| ``` | ||
|
|
||
| </TabItem> </Tabs> | ||
|
|
||
|
|
||
| ## Using Workers KV | ||
|
|
||
| KV allows | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I know this PR is still a WIP so may get addressed later but this reads as incomplete for now. |
||
|
|
||
| <Tabs syncKey="workersExamples"> <TabItem label="JavaScript" icon="seti:javascript"> | ||
|
|
||
| ```js | ||
|
|
||
| const serializeResponse() = () => { | ||
| // TODO: Implement Request -> JSON/Text | ||
| } | ||
|
|
||
| const deserializeResponse() = () => { | ||
| // TODO: Implement JSON/Text -> Request | ||
| } | ||
|
|
||
| export default { | ||
| async fetch(request, env, ctx) { | ||
| async function sha256(message) { | ||
| // encode as UTF-8 | ||
| const msgBuffer = await new TextEncoder().encode(message); | ||
| // hash the message | ||
| const hashBuffer = await crypto.subtle.digest("SHA-256", msgBuffer); | ||
| // convert bytes to hex string | ||
| return [...new Uint8Array(hashBuffer)] | ||
| .map((b) => b.toString(16).padStart(2, "0")) | ||
| .join(""); | ||
| } | ||
| try { | ||
| if (request.method.toUpperCase() === "POST") { | ||
| const body = await request.clone().text(); | ||
| // Hash the request body to use it as a part of the cache key | ||
| const hash = await sha256(body); | ||
| const cacheUrl = new URL(request.url); | ||
| // Store the URL in cache by prepending the body's hash | ||
| cacheUrl.pathname = "/posts" + cacheUrl.pathname + hash; | ||
| // Convert to a GET to be able to cache | ||
| const cacheKey = new Request(cacheUrl.toString(), { | ||
| headers: request.headers, | ||
| method: "GET", | ||
| }); | ||
|
|
||
| // Find the cache key in KV | ||
| let response = deserializeResponse(await env.KV.get()); | ||
| // Otherwise, fetch response to POST request from origin | ||
| if (!response) { | ||
| response = await fetch(request); | ||
| // TODO: Add expiry | ||
| ctx.waitUntil(env.KV.put(cacheKey, serializeResponse())); | ||
| } | ||
| return response; | ||
| } | ||
| return fetch(request); | ||
| } catch (e) { | ||
| return new Response("Error thrown " + e.message); | ||
| } | ||
| }, | ||
| }; | ||
| ``` | ||
|
|
||
| </TabItem> <TabItem label="TypeScript" icon="seti:typescript"> | ||
|
|
||
| ```ts | ||
| interface Env {} | ||
| export default { | ||
| async fetch(request, env, ctx): Promise<Response> { | ||
| async function sha256(message) { | ||
| // encode as UTF-8 | ||
| const msgBuffer = await new TextEncoder().encode(message); | ||
| // hash the message | ||
| const hashBuffer = await crypto.subtle.digest("SHA-256", msgBuffer); | ||
| // convert bytes to hex string | ||
| return [...new Uint8Array(hashBuffer)] | ||
| .map((b) => b.toString(16).padStart(2, "0")) | ||
| .join(""); | ||
| } | ||
| try { | ||
| if (request.method.toUpperCase() === "POST") { | ||
| const body = await request.clone().text(); | ||
| // Hash the request body to use it as a part of the cache key | ||
| const hash = await sha256(body); | ||
| const cacheUrl = new URL(request.url); | ||
| // Store the URL in cache by prepending the body's hash | ||
| cacheUrl.pathname = "/posts" + cacheUrl.pathname + hash; | ||
| // Convert to a GET to be able to cache | ||
| const cacheKey = new Request(cacheUrl.toString(), { | ||
| headers: request.headers, | ||
| method: "GET", | ||
| }); | ||
|
|
||
| const cache = caches.default; | ||
| // Find the cache key in the cache | ||
| let response = await cache.match(cacheKey); | ||
| // Otherwise, fetch response to POST request from origin | ||
| if (!response) { | ||
| response = await fetch(request); | ||
| ctx.waitUntil(cache.put(cacheKey, response.clone())); | ||
| } | ||
| return response; | ||
| } | ||
| return fetch(request); | ||
| } catch (e) { | ||
| return new Response("Error thrown " + e.message); | ||
| } | ||
| }, | ||
| } satisfies ExportedHandler<Env>; | ||
| ``` | ||
|
|
||
| </TabItem></Tabs> | ||
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I suggested which part of the text was included as the link to prevent potential confusion.