@@ -45,6 +45,9 @@ const CORS_HEADERS: Record<string, string> = {
4545 'Access-Control-Max-Age' : '86400' ,
4646} ;
4747
48+ /** Reuse the same download link until near expiry. Microsoft ISO links expire 1 day after creation. */
49+ const LINK_CACHE_MAX_AGE_SEC = 86_400 ; // 24 hours
50+
4851function jsonResponse ( data : unknown , status = 200 ) : Response {
4952 return new Response ( JSON . stringify ( data ) , {
5053 status,
@@ -272,20 +275,59 @@ export default {
272275 const skuId = url . searchParams . get ( 'skuId' ) ?? '' ;
273276 if ( ! skuId ) return errorResponse ( 'Missing skuId parameter.' ) ;
274277
278+ // Cache key is arch+skuId only so all clients reuse the same link (sessionId is irrelevant for links).
279+ const cacheKey = new URL ( url . pathname , url . origin ) ;
280+ cacheKey . searchParams . set ( 'arch' , arch ) ;
281+ cacheKey . searchParams . set ( 'skuId' , skuId ) ;
282+ const cacheRequest = new Request ( cacheKey . toString ( ) , { method : 'GET' } ) ;
283+
284+ // Reuse a recently generated link for the same arch+skuId to avoid spawning extra browsers.
285+ const cached = await caches . default . match ( cacheRequest ) ;
286+ if ( cached ) {
287+ const body = await cached . clone ( ) . text ( ) ;
288+ return new Response ( body , {
289+ status : 200 ,
290+ headers : {
291+ 'Content-Type' : 'application/json' ,
292+ 'Cache-Control' : 'no-store' ,
293+ ...CORS_HEADERS ,
294+ } ,
295+ } ) ;
296+ }
297+
275298 const viaBrowser = await getIsoLinkViaBrowser ( env , arch , skuId ) ;
276299 if ( ! viaBrowser . ok ) {
277300 return jsonResponse ( {
278301 Errors : [ { Key : 'ErrorSettings.BrowserRenderingFailed' , Value : viaBrowser . error , Type : 9 } ] ,
279302 } ) ;
280303 }
281- return jsonResponse ( {
304+
305+ const payload = {
282306 ProductDownloadOptions : [
283307 {
284308 Uri : viaBrowser . href ,
285309 ProductDisplayName : 'Windows 11 ISO' ,
286310 LocalizedLanguage : viaBrowser . label ,
287311 } ,
288312 ] ,
313+ } ;
314+ const body = JSON . stringify ( payload ) ;
315+ const cacheResponse = new Response ( body , {
316+ headers : {
317+ 'Content-Type' : 'application/json' ,
318+ 'Cache-Control' : `private, max-age=${ LINK_CACHE_MAX_AGE_SEC } ` ,
319+ ...CORS_HEADERS ,
320+ } ,
321+ } ) ;
322+ await caches . default . put ( cacheRequest , cacheResponse ) ;
323+
324+ return new Response ( body , {
325+ status : 200 ,
326+ headers : {
327+ 'Content-Type' : 'application/json' ,
328+ 'Cache-Control' : 'no-store' ,
329+ ...CORS_HEADERS ,
330+ } ,
289331 } ) ;
290332 }
291333
0 commit comments