Files
EnvelopeGenerator/EnvelopeGenerator.Server/EnvelopeGenerator.Server/Controllers/PdfRenderController.cs
TekH 91e90b322b Add caching to PdfRenderController
Implemented caching in the PdfRenderController using IMemoryCache to improve performance by avoiding redundant PDF rendering. Added a new constructor parameter for IMemoryCache and a static TimeSpan field for cache duration. Introduced a private method, BuildCacheKey, to generate unique cache keys based on the SHA256 hash of PDF bytes. Updated the RenderPages method to check for cached pages before rendering and store results in the cache.
2026-10-27 21:57:35 +01:00

42 lines
1.7 KiB
C#

using DigitalData.Auth.Claims;
using EnvelopeGenerator.Application.Common.Dto;
using EnvelopeGenerator.Application.Common.Interfaces.Doc;
using EnvelopeGenerator.Domain.Constants;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Security.Cryptography;
namespace EnvelopeGenerator.Server.Controllers;
[ApiController]
[Route("api/[controller]")]
public class PdfRenderController(IPdfPageImageRenderer renderer, IMemoryCache memoryCache) : ControllerBase
{
private static readonly TimeSpan RenderCacheDuration = TimeSpan.FromMinutes(5);
// TODO(perf): Replace JSON/base64 transport for PdfBytes with application/octet-stream (or multipart) and stream-based request parsing to reduce payload size and allocation pressure for large PDFs.
[HttpPost("pages")]
[Authorize(AuthenticationSchemes = AuthScheme.Sender)]
public async Task<IActionResult> RenderPages([FromBody] PdfRenderRequestDto? request, CancellationToken cancel)
{
if (request?.PdfBytes is not { Length: > 0 } bytes)
return BadRequest("Missing PDF bytes.");
var cacheKey = BuildCacheKey(bytes);
if (memoryCache.TryGetValue(cacheKey, out IReadOnlyList<PdfPageImageDto>? cachedPages) && cachedPages is not null)
return Ok(cachedPages);
IReadOnlyList<PdfPageImageDto> pages = await renderer.RenderPagesAsImagesAsync(bytes, cancel);
memoryCache.Set(cacheKey, pages, RenderCacheDuration);
return Ok(pages);
}
private static string BuildCacheKey(byte[] pdfBytes)
{
var hash = Convert.ToHexString(SHA256.HashData(pdfBytes));
return $"pdf-render:pages:v1:dpi110:{hash}";
}
}