* Fetch and load policy limits with file caching * Fails open - returns null if fetch fails and no cache exists
()
| 430 | * Fails open - returns null if fetch fails and no cache exists |
| 431 | */ |
| 432 | async function fetchAndLoadPolicyLimits(): Promise< |
| 433 | PolicyLimitsResponse['restrictions'] | null |
| 434 | > { |
| 435 | if (!isPolicyLimitsEligible()) { |
| 436 | return null |
| 437 | } |
| 438 | |
| 439 | const cachedRestrictions = loadCachedRestrictions() |
| 440 | |
| 441 | const cachedChecksum = cachedRestrictions |
| 442 | ? computeChecksum(cachedRestrictions) |
| 443 | : undefined |
| 444 | |
| 445 | try { |
| 446 | const result = await fetchWithRetry(cachedChecksum) |
| 447 | |
| 448 | if (!result.success) { |
| 449 | if (cachedRestrictions) { |
| 450 | logForDebugging('Policy limits: Using stale cache after fetch failure') |
| 451 | sessionCache = cachedRestrictions |
| 452 | return cachedRestrictions |
| 453 | } |
| 454 | return null |
| 455 | } |
| 456 | |
| 457 | // Handle 304 Not Modified |
| 458 | if (result.restrictions === null && cachedRestrictions) { |
| 459 | logForDebugging('Policy limits: Cache still valid (304 Not Modified)') |
| 460 | sessionCache = cachedRestrictions |
| 461 | return cachedRestrictions |
| 462 | } |
| 463 | |
| 464 | const newRestrictions = result.restrictions || {} |
| 465 | const hasContent = Object.keys(newRestrictions).length > 0 |
| 466 | |
| 467 | if (hasContent) { |
| 468 | sessionCache = newRestrictions |
| 469 | await saveCachedRestrictions(newRestrictions) |
| 470 | logForDebugging('Policy limits: Applied new restrictions successfully') |
| 471 | return newRestrictions |
| 472 | } |
| 473 | |
| 474 | // Empty restrictions (404 response) - delete cached file if it exists |
| 475 | sessionCache = newRestrictions |
| 476 | try { |
| 477 | await unlink(getCachePath()) |
| 478 | logForDebugging('Policy limits: Deleted cached file (404 response)') |
| 479 | } catch (e) { |
| 480 | if (isNodeError(e) && e.code !== 'ENOENT') { |
| 481 | logForDebugging( |
| 482 | `Policy limits: Failed to delete cached file - ${e.message}`, |
| 483 | ) |
| 484 | } |
| 485 | } |
| 486 | return newRestrictions |
| 487 | } catch { |
| 488 | if (cachedRestrictions) { |
| 489 | logForDebugging('Policy limits: Using stale cache after error') |
no test coverage detected