File
Blob: src/workerd/server/tests/weakref/index.mjs
| 1 | // Copyright (c) 2025 Cloudflare, Inc. |
| 2 | // Licensed under the Apache 2.0 license found in the LICENSE file or at: |
| 3 | // https://opensource.org/licenses/Apache-2.0 |
| 4 | let frCounter = 0; |
| 5 | let weakRefState = { isDereferenced: false, value: null }; |
| 6 | |
| 7 | const fr = new FinalizationRegistry(() => { |
| 8 | ++frCounter; |
| 9 | }); |
| 10 | |
| 11 | export default { |
| 12 | async fetch(request, env, ctx) { |
| 13 | const url = new URL(request.url); |
| 14 | const test = url.searchParams.get('test') || 'fr'; |
| 15 | |
| 16 | if (test === 'fr') { |
| 17 | // Test FinalizationRegistry |
| 18 | (function () { |
| 19 | fr.register({}, ''); |
| 20 | })(); |
| 21 | |
| 22 | // Ensure obj gets GC'd |
| 23 | gc(); |
| 24 | |
| 25 | if (frCounter > 0) { |
| 26 | await scheduler.wait(10); |
| 27 | } |
| 28 | |
| 29 | return new Response(frCounter.toString()); |
| 30 | } else if (test === 'weakref') { |
| 31 | // Test WeakRef |
| 32 | if (url.searchParams.has('create')) { |
| 33 | const obj = { message: "I'm alive!" }; |
| 34 | const ref = new WeakRef(obj); |
| 35 | |
| 36 | // Store the WeakRef for later testing |
| 37 | weakRefState.ref = ref; |
| 38 | weakRefState.isDereferenced = false; |
| 39 | weakRefState.value = ref.deref()?.message || null; |
| 40 | |
| 41 | return Response.json({ |
| 42 | created: true, |
| 43 | value: weakRefState.value, |
| 44 | }); |
| 45 | } |
| 46 | if (url.searchParams.has('gc')) { |
| 47 | // Force garbage collection and check if the WeakRef has been cleared |
| 48 | gc(); |
| 49 | await scheduler.wait(10); // Give GC time to clean up |
| 50 | } |
| 51 | |
| 52 | // Just return the current state |
| 53 | const value = weakRefState.ref?.deref()?.message || null; |
| 54 | weakRefState.isDereferenced = value === null; |
| 55 | weakRefState.value = value; |
| 56 | |
| 57 | return Response.json({ |
| 58 | isDereferenced: weakRefState.isDereferenced, |
| 59 | value: weakRefState.value, |
| 60 | }); |
| 61 | } |
| 62 | |
| 63 | return new Response('Invalid test', { status: 400 }); |
| 64 | }, |
| 65 | }; |