- 
                Notifications
    
You must be signed in to change notification settings  - Fork 77
 
Feat cache for the queue #496
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
          
     Merged
      
      
    
  
     Merged
                    Changes from 9 commits
      Commits
    
    
            Show all changes
          
          
            10 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      e983b0f
              
                queue cache
              
              
                conico974 9108255
              
                moved cache out of  the durable queue
              
              
                conico974 e4b6fee
              
                local queue cache
              
              
                conico974 aea3e13
              
                add local in memory cache
              
              
                conico974 54e0d4a
              
                fix rebase
              
              
                conico974 6ff6964
              
                changeset
              
              
                conico974 76d55cf
              
                add cache-tag
              
              
                conico974 9842527
              
                review fix
              
              
                conico974 79a1677
              
                review
              
              
                conico974 56dca94
              
                Update .changeset/large-zoos-approve.md
              
              
                conico974 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 | 
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@opennextjs/cloudflare": patch | ||
| --- | ||
| 
     | 
||
| add an optional cache for the durable queue | ||
  
    
      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
    
  
  
    
              
  
    
      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
    
  
  
    
              
        
          
          
            112 changes: 112 additions & 0 deletions
          
          112 
        
  packages/cloudflare/src/api/overrides/queue/queue-cache.spec.ts
  
  
      
      
   
        
      
      
    
  
    
      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 | 
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| import type { Queue } from "@opennextjs/aws/types/overrides"; | ||
| import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; | ||
| 
     | 
||
| import queueCache from "./queue-cache"; | ||
| 
     | 
||
| const mockedQueue = { | ||
| name: "mocked-queue", | ||
| send: vi.fn(), | ||
| } satisfies Queue; | ||
| 
     | 
||
| const generateMessage = () => ({ | ||
| MessageGroupId: "test", | ||
| MessageBody: { | ||
| eTag: "test", | ||
| url: "test", | ||
| host: "test", | ||
| lastModified: Date.now(), | ||
| }, | ||
| MessageDeduplicationId: "test", | ||
| }); | ||
| 
     | 
||
| const mockedPut = vi.fn(); | ||
| const mockedMatch = vi.fn().mockReturnValue(null); | ||
| 
     | 
||
| describe("queue-cache", () => { | ||
| beforeEach(() => { | ||
| // @ts-ignore | ||
| globalThis.caches = { | ||
| open: vi.fn().mockReturnValue({ | ||
| put: mockedPut, | ||
| match: mockedMatch, | ||
| }), | ||
| }; | ||
| }); | ||
| 
     | 
||
| afterEach(() => { | ||
| vi.resetAllMocks(); | ||
| }); | ||
| test("should send the message to the original queue", async () => { | ||
| const msg = generateMessage(); | ||
| const queue = queueCache(mockedQueue, {}); | ||
| expect(queue.name).toBe("cached-mocked-queue"); | ||
| await queue.send(msg); | ||
| expect(mockedQueue.send).toHaveBeenCalledWith(msg); | ||
| }); | ||
| 
     | 
||
| test("should use the local cache", async () => { | ||
| const msg = generateMessage(); | ||
| const queue = queueCache(mockedQueue, {}); | ||
| await queue.send(msg); | ||
| 
     | 
||
| expect(queue.localCache.size).toBe(1); | ||
| expect(queue.localCache.has(`queue/test/test`)).toBe(true); | ||
| expect(mockedPut).toHaveBeenCalled(); | ||
| 
     | 
||
| const spiedHas = vi.spyOn(queue.localCache, "has"); | ||
| await queue.send(msg); | ||
| expect(spiedHas).toHaveBeenCalled(); | ||
| 
     | 
||
| expect(mockedQueue.send).toHaveBeenCalledTimes(1); | ||
| 
     | 
||
| expect(mockedMatch).toHaveBeenCalledTimes(1); | ||
| }); | ||
| 
     | 
||
| test("should clear the local cache after 5s", async () => { | ||
| vi.useFakeTimers(); | ||
| const msg = generateMessage(); | ||
| const queue = queueCache(mockedQueue, {}); | ||
| await queue.send(msg); | ||
| expect(queue.localCache.size).toBe(1); | ||
| expect(queue.localCache.has(`queue/test/test`)).toBe(true); | ||
| 
     | 
||
| vi.advanceTimersByTime(5001); | ||
| const alteredMsg = generateMessage(); | ||
| alteredMsg.MessageGroupId = "test2"; | ||
| await queue.send(alteredMsg); | ||
| expect(queue.localCache.size).toBe(1); | ||
| console.log(queue.localCache); | ||
| expect(queue.localCache.has(`queue/test2/test`)).toBe(true); | ||
| expect(queue.localCache.has(`queue/test/test`)).toBe(false); | ||
| vi.useRealTimers(); | ||
| }); | ||
| 
     | 
||
| test("should use the regional cache if not in local cache", async () => { | ||
| const msg = generateMessage(); | ||
| const queue = queueCache(mockedQueue, {}); | ||
| await queue.send(msg); | ||
| 
     | 
||
| expect(mockedMatch).toHaveBeenCalledTimes(1); | ||
| expect(mockedPut).toHaveBeenCalledTimes(1); | ||
| expect(queue.localCache.size).toBe(1); | ||
| expect(queue.localCache.has(`queue/test/test`)).toBe(true); | ||
| // We need to delete the local cache to test the regional cache | ||
| queue.localCache.delete(`queue/test/test`); | ||
| 
     | 
||
| const spiedHas = vi.spyOn(queue.localCache, "has"); | ||
| await queue.send(msg); | ||
| expect(spiedHas).toHaveBeenCalled(); | ||
| expect(mockedMatch).toHaveBeenCalledTimes(2); | ||
| }); | ||
| 
     | 
||
| test("should return early if the message is in the regional cache", async () => { | ||
| const msg = generateMessage(); | ||
| const queue = queueCache(mockedQueue, {}); | ||
| 
     | 
||
| mockedMatch.mockReturnValueOnce(new Response(null, { status: 200 })); | ||
| 
     | 
||
| const spiedSend = mockedQueue.send; | ||
| await queue.send(msg); | ||
| expect(spiedSend).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | 
        
          
          
            122 changes: 122 additions & 0 deletions
          
          122 
        
  packages/cloudflare/src/api/overrides/queue/queue-cache.ts
  
  
      
      
   
        
      
      
    
  
    
      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 | 
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| import { error } from "@opennextjs/aws/adapters/logger.js"; | ||
| import type { Queue, QueueMessage } from "@opennextjs/aws/types/overrides"; | ||
| 
     | 
||
| interface QueueCachingOptions { | ||
| /** | ||
| * The TTL for the regional cache in seconds. | ||
| * @default 5 | ||
| */ | ||
| regionalCacheTtlSec?: number; | ||
| 
     | 
||
| /** | ||
| * Whether to wait for the queue ack before returning. | ||
| * When set to false, the cache will be populated asap and the queue will be called after. | ||
| * When set to true, the cache will be populated only after the queue ack is received. | ||
| * @default false | ||
| */ | ||
| waitForQueueAck?: boolean; | ||
| } | ||
| 
     | 
||
| const DEFAULT_QUEUE_CACHE_TTL_SEC = 5; | ||
| 
     | 
||
| class QueueCache implements Queue { | ||
| readonly name; | ||
| readonly regionalCacheTtlSec: number; | ||
| readonly waitForQueueAck: boolean; | ||
| cache: Cache | undefined; | ||
| // Local mapping from key to insertedAtSec | ||
| localCache: Map<string, number> = new Map(); | ||
                
      
                  conico974 marked this conversation as resolved.
               
          
            Show resolved
            Hide resolved
         | 
||
| 
     | 
||
| constructor( | ||
| private originalQueue: Queue, | ||
| options: QueueCachingOptions | ||
| ) { | ||
| this.name = `cached-${originalQueue.name}`; | ||
| this.regionalCacheTtlSec = options.regionalCacheTtlSec ?? DEFAULT_QUEUE_CACHE_TTL_SEC; | ||
| this.waitForQueueAck = options.waitForQueueAck ?? false; | ||
| } | ||
| 
     | 
||
| async send(msg: QueueMessage) { | ||
| try { | ||
| const isCached = await this.isInCache(msg); | ||
| if (isCached) { | ||
| return; | ||
| } | ||
| if (!this.waitForQueueAck) { | ||
| await this.putToCache(msg); | ||
| await this.originalQueue.send(msg); | ||
| } else { | ||
| await this.originalQueue.send(msg); | ||
| await this.putToCache(msg); | ||
| } | ||
| } catch (e) { | ||
| error("Error sending message to queue", e); | ||
| } finally { | ||
| this.clearLocalCache(); | ||
| } | ||
| } | ||
| 
     | 
||
| private async getCache() { | ||
| if (!this.cache) { | ||
| this.cache = await caches.open("durable-queue"); | ||
| } | ||
| return this.cache; | ||
| } | ||
| 
     | 
||
| private getCacheUrlString(msg: QueueMessage) { | ||
| return `queue/${msg.MessageGroupId}/${msg.MessageDeduplicationId}`; | ||
| } | ||
                
      
                  conico974 marked this conversation as resolved.
               
          
            Show resolved
            Hide resolved
         | 
||
| 
     | 
||
| private getCacheKey(msg: QueueMessage) { | ||
| return "http://local.cache" + this.getCacheUrlString(msg); | ||
| } | ||
| 
     | 
||
| private async putToCache(msg: QueueMessage) { | ||
| this.localCache.set(this.getCacheUrlString(msg), Date.now()); | ||
| const cacheKey = this.getCacheKey(msg); | ||
| const cache = await this.getCache(); | ||
| await cache.put( | ||
| cacheKey, | ||
| new Response(null, { | ||
| status: 200, | ||
| headers: { | ||
| "Cache-Control": `max-age=${this.regionalCacheTtlSec}`, | ||
| // Tag cache is set to the value of the soft tag assigned by Next.js | ||
| // This way you can invalidate this cache as well as any other regional cache | ||
| "Cache-Tag": `_N_T_/${msg.MessageBody.url}`, | ||
                
      
                  conico974 marked this conversation as resolved.
               
          
            Show resolved
            Hide resolved
         | 
||
| }, | ||
| }) | ||
| ); | ||
| } | ||
| 
     | 
||
| private async isInCache(msg: QueueMessage) { | ||
| if (this.localCache.has(this.getCacheUrlString(msg))) { | ||
| const insertedAt = this.localCache.get(this.getCacheUrlString(msg))!; | ||
| if (Date.now() - insertedAt < this.regionalCacheTtlSec * 1000) { | ||
| return true; | ||
| } | ||
| this.localCache.delete(this.getCacheUrlString(msg)); | ||
| return false; | ||
| } | ||
| const cacheKey = this.getCacheKey(msg); | ||
| const cache = await this.getCache(); | ||
| const cachedResponse = await cache.match(cacheKey); | ||
| if (cachedResponse) { | ||
| return true; | ||
| } | ||
| } | ||
| 
     | 
||
| /** | ||
| * Remove any value older than the TTL from the local cache | ||
| */ | ||
| private clearLocalCache() { | ||
| const insertAtSecMax = Date.now() - this.regionalCacheTtlSec * 1000; | ||
| for (const [key, insertAtSec] of this.localCache.entries()) { | ||
| if (insertAtSec < insertAtSecMax) { | ||
| this.localCache.delete(key); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| 
     | 
||
| export default (originalQueue: Queue, opts: QueueCachingOptions = {}) => new QueueCache(originalQueue, opts); | ||
  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.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.