From 5d0ffe8e7a3d6a4311b8db1c549a255fd43d8508 Mon Sep 17 00:00:00 2001 From: aniebietafia Date: Sun, 28 Jun 2026 23:11:48 +0100 Subject: [PATCH] feat(upload): implement concurrent async upload pipeline with WebSockets and Resilience4j - Refactored synchronous, sequential document uploads to a concurrent, non-blocking pipeline using CompletableFuture and Spring @Async. - Integrated STOMP WebSockets with Redis-backed, one-time ticket authentication for real-time progress updates. - Added Resilience4j circuit breakers, retries, and bulkhead policies to S3 upload and OCR provider integrations (Google Vision, Tesseract). - Configured immediate file-by-file Kafka message publishing to start OCR processing as soon as individual files land in storage. - Added a dedicated thread-pool executor for the upload pipeline and Actuator metrics for circuit breakers. Signed-off-by: aniebietafia --- pom.xml | 25 ++ .../kafka/config/KafkaTopicConfig.java | 10 + .../com/xtraction/api/config/AsyncConfig.java | 49 +++ .../config/CircuitBreakerEventListener.java | 50 +++ .../api/config/ResilienceConfig.java | 124 ++++++++ .../xtraction/api/config/SecurityConfig.java | 3 +- .../xtraction/api/config/WebSocketConfig.java | 49 +++ .../controller/DocumentController.java | 38 ++- .../dto/response/StreamingUploadResponse.java | 23 ++ .../service/StreamingUploadPipeline.java | 293 ++++++++++++++++++ .../controller/OcrDocumentController.java | 35 ++- .../dto/response/ExtractionProgressEvent.java | 37 +++ .../ocrprocessing/events/OcrEventMapper.java | 2 + .../events/OcrMessageListener.java | 27 +- .../events/OcrRequestedEvent.java | 1 + .../service/ExtractionProgressService.java | 212 +++++++++++++ .../service/OcrProcessingService.java | 34 +- .../api/ocrprocessing/service/ProcessOcr.java | 43 ++- .../utils/FileStorageService.java | 22 ++ .../websocket/WebSocketAuthInterceptor.java | 70 +++++ .../websocket/WebSocketTicketController.java | 71 +++++ .../api/websocket/WebSocketTicketService.java | 73 +++++ 22 files changed, 1258 insertions(+), 33 deletions(-) create mode 100644 src/main/java/com/xtraction/api/config/AsyncConfig.java create mode 100644 src/main/java/com/xtraction/api/config/CircuitBreakerEventListener.java create mode 100644 src/main/java/com/xtraction/api/config/ResilienceConfig.java create mode 100644 src/main/java/com/xtraction/api/config/WebSocketConfig.java create mode 100644 src/main/java/com/xtraction/api/documents/dto/response/StreamingUploadResponse.java create mode 100644 src/main/java/com/xtraction/api/documents/service/StreamingUploadPipeline.java create mode 100644 src/main/java/com/xtraction/api/ocrprocessing/dto/response/ExtractionProgressEvent.java create mode 100644 src/main/java/com/xtraction/api/ocrprocessing/service/ExtractionProgressService.java create mode 100644 src/main/java/com/xtraction/api/websocket/WebSocketAuthInterceptor.java create mode 100644 src/main/java/com/xtraction/api/websocket/WebSocketTicketController.java create mode 100644 src/main/java/com/xtraction/api/websocket/WebSocketTicketService.java diff --git a/pom.xml b/pom.xml index 3bebde9..8d34387 100644 --- a/pom.xml +++ b/pom.xml @@ -38,6 +38,7 @@ 31.0.0 7.4.1 1.18.42 + 2.3.0 @@ -74,6 +75,30 @@ spring-boot-starter-elasticsearch + + + org.springframework.boot + spring-boot-starter-websocket + + + + + org.springframework + spring-aspects + + + + + io.github.resilience4j + resilience4j-spring-boot3 + ${resilience4j.version} + + + io.github.resilience4j + resilience4j-micrometer + ${resilience4j.version} + + org.springframework.boot diff --git a/src/main/java/com/xtraction/api/brokers/kafka/config/KafkaTopicConfig.java b/src/main/java/com/xtraction/api/brokers/kafka/config/KafkaTopicConfig.java index 0b7ae1f..c95a8e1 100644 --- a/src/main/java/com/xtraction/api/brokers/kafka/config/KafkaTopicConfig.java +++ b/src/main/java/com/xtraction/api/brokers/kafka/config/KafkaTopicConfig.java @@ -25,6 +25,7 @@ public class KafkaTopicConfig { public static final String TOPIC_TEAM_EVENTS = "unraveldocs-team-events"; public static final String TOPIC_ADMIN_EVENTS = "unraveldocs-admin-events"; public static final String TOPIC_ELASTICSEARCH = "unraveldocs-elasticsearch"; + public static final String TOPIC_EXTRACTION_PROGRESS = "xtraction-extraction-progress"; // Retry topics (intermediate retry before DLQ) public static final String TOPIC_EMAILS_RETRY = "unraveldocs-emails-retry"; @@ -232,6 +233,15 @@ public NewTopic elasticsearchTopic() { .build(); } + @Bean + public NewTopic extractionProgressTopic() { + return TopicBuilder.name(TOPIC_EXTRACTION_PROGRESS) + .partitions(3) + .replicas(1) + .config("retention.ms", "259200000") // 3 days + .build(); + } + // DLQ topics for new topics @Bean public NewTopic ocrDlqTopic() { diff --git a/src/main/java/com/xtraction/api/config/AsyncConfig.java b/src/main/java/com/xtraction/api/config/AsyncConfig.java new file mode 100644 index 0000000..e6c72c9 --- /dev/null +++ b/src/main/java/com/xtraction/api/config/AsyncConfig.java @@ -0,0 +1,49 @@ +package com.xtraction.api.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.task.TaskExecutor; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.RejectedExecutionHandler; +import java.util.concurrent.ThreadPoolExecutor; + +/** + * Async configuration for the upload pipeline. + * Defines a dedicated thread pool for handling file upload operations asynchronously. + * + *

The pool uses a CallerRunsPolicy so that if the pool and queue are full, + * the calling thread runs the task itself — providing natural backpressure.

+ */ +@Configuration +@EnableAsync +public class AsyncConfig { + + /** + * Thread pool executor for the upload pipeline. + * + *
    + *
  • Core pool: 4 threads — handles normal load
  • + *
  • Max pool: 8 threads — scales under burst load
  • + *
  • Queue capacity: 50 — buffers tasks before scaling up
  • + *
  • Rejection policy: CallerRunsPolicy — caller thread executes rejected tasks
  • + *
  • Graceful shutdown: waits up to 60s for in-flight tasks to complete
  • + *
+ * + * @return the configured TaskExecutor + */ + @Bean(name = "uploadPipelineExecutor") + public TaskExecutor uploadPipelineExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(4); + executor.setMaxPoolSize(8); + executor.setQueueCapacity(50); + executor.setThreadNamePrefix("upload-pipeline-"); + executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); + executor.setWaitForTasksToCompleteOnShutdown(true); + executor.setAwaitTerminationSeconds(60); + executor.initialize(); + return executor; + } +} diff --git a/src/main/java/com/xtraction/api/config/CircuitBreakerEventListener.java b/src/main/java/com/xtraction/api/config/CircuitBreakerEventListener.java new file mode 100644 index 0000000..0f00481 --- /dev/null +++ b/src/main/java/com/xtraction/api/config/CircuitBreakerEventListener.java @@ -0,0 +1,50 @@ +package com.xtraction.api.config; + +import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry; +import jakarta.annotation.PostConstruct; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +/** + * Listens to circuit breaker events and logs state transitions. + * + *

Automatically registers event consumers for all circuit breakers + * in the registry. This provides operational visibility into circuit + * breaker behavior without requiring external monitoring.

+ */ +@Slf4j +@Component +@RequiredArgsConstructor +public class CircuitBreakerEventListener { + + private final CircuitBreakerRegistry circuitBreakerRegistry; + + /** + * Register event consumers on all circuit breakers after bean initialization. + * Listens for state transitions and failure rate exceeded events. + */ + @PostConstruct + public void registerEventConsumers() { + circuitBreakerRegistry.getAllCircuitBreakers().forEach(circuitBreaker -> { + String cbName = circuitBreaker.getName(); + + circuitBreaker.getEventPublisher() + .onStateTransition(event -> log.warn( + "Circuit breaker '{}' state transition: {} -> {}", + cbName, + event.getStateTransition().getFromState(), + event.getStateTransition().getToState())) + .onFailureRateExceeded(event -> log.error( + "Circuit breaker '{}' failure rate exceeded threshold: {}%", + cbName, + event.getFailureRate())) + .onSlowCallRateExceeded(event -> log.warn( + "Circuit breaker '{}' slow call rate exceeded threshold: {}%", + cbName, + event.getSlowCallRate())); + + log.info("Registered event consumers for circuit breaker: {}", cbName); + }); + } +} diff --git a/src/main/java/com/xtraction/api/config/ResilienceConfig.java b/src/main/java/com/xtraction/api/config/ResilienceConfig.java new file mode 100644 index 0000000..9a57e5d --- /dev/null +++ b/src/main/java/com/xtraction/api/config/ResilienceConfig.java @@ -0,0 +1,124 @@ +package com.xtraction.api.config; + +import io.github.resilience4j.bulkhead.BulkheadConfig; +import io.github.resilience4j.bulkhead.BulkheadRegistry; +import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig; +import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry; +import io.github.resilience4j.core.IntervalFunction; +import io.github.resilience4j.retry.RetryConfig; +import io.github.resilience4j.retry.RetryRegistry; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import software.amazon.awssdk.core.exception.SdkException; + +import java.io.IOException; +import java.time.Duration; + +/** + * Resilience4j configuration for circuit breakers, retries, and bulkheads. + * + *

All resilience patterns are defined programmatically (not via application.properties) + * for clarity and type-safety.

+ * + *

Circuit Breakers

+ *
    + *
  • s3Upload — protects S3 file uploads
  • + *
  • ocrGoogleVision — protects Google Vision API calls
  • + *
  • ocrTesseract — protects local Tesseract calls (higher failure threshold)
  • + *
+ * + *

Retries

+ *
    + *
  • s3Upload — retries S3 uploads on IOException and SdkException
  • + *
  • ocrProvider — retries OCR provider calls with exponential backoff
  • + *
+ * + *

Bulkheads

+ *
    + *
  • ocrProcessing — limits concurrent OCR processing to 10
  • + *
+ */ +@Configuration +public class ResilienceConfig { + + // ==================== Circuit Breaker Registry ==================== + + @Bean + public CircuitBreakerRegistry circuitBreakerRegistry() { + CircuitBreakerRegistry registry = CircuitBreakerRegistry.ofDefaults(); + + // S3 Upload circuit breaker + registry.circuitBreaker("s3Upload", CircuitBreakerConfig.custom() + .failureRateThreshold(50) + .waitDurationInOpenState(Duration.ofSeconds(30)) + .slidingWindowSize(10) + .slowCallRateThreshold(80) + .slowCallDurationThreshold(Duration.ofSeconds(60)) + .permittedNumberOfCallsInHalfOpenState(3) + .minimumNumberOfCalls(5) + .build()); + + // Google Vision OCR circuit breaker + registry.circuitBreaker("ocrGoogleVision", CircuitBreakerConfig.custom() + .failureRateThreshold(50) + .waitDurationInOpenState(Duration.ofSeconds(60)) + .slidingWindowSize(10) + .slowCallRateThreshold(70) + .slowCallDurationThreshold(Duration.ofSeconds(120)) + .permittedNumberOfCallsInHalfOpenState(3) + .minimumNumberOfCalls(5) + .build()); + + // Tesseract OCR circuit breaker (higher threshold since it's local) + registry.circuitBreaker("ocrTesseract", CircuitBreakerConfig.custom() + .failureRateThreshold(70) + .waitDurationInOpenState(Duration.ofSeconds(15)) + .slidingWindowSize(10) + .slowCallRateThreshold(80) + .slowCallDurationThreshold(Duration.ofSeconds(300)) + .permittedNumberOfCallsInHalfOpenState(3) + .minimumNumberOfCalls(5) + .build()); + + return registry; + } + + // ==================== Retry Registry ==================== + + @Bean + public RetryRegistry retryRegistry() { + RetryRegistry registry = RetryRegistry.ofDefaults(); + + // S3 Upload retry — retries on IOException and AWS SDK exceptions + registry.retry("s3Upload", RetryConfig.custom() + .maxAttempts(3) + .intervalFunction(IntervalFunction.ofExponentialBackoff( + Duration.ofSeconds(1), 2.0)) + .retryExceptions(IOException.class, SdkException.class) + .build()); + + // OCR Provider retry — generic retry for OCR calls + registry.retry("ocrProvider", RetryConfig.custom() + .maxAttempts(2) + .intervalFunction(IntervalFunction.ofExponentialBackoff( + Duration.ofSeconds(2), 2.0)) + .build()); + + return registry; + } + + // ==================== Bulkhead Registry ==================== + + @Bean + public BulkheadRegistry bulkheadRegistry() { + BulkheadRegistry registry = BulkheadRegistry.ofDefaults(); + + // OCR processing bulkhead — limits concurrent OCR calls + registry.bulkhead("ocrProcessing", BulkheadConfig.custom() + .maxConcurrentCalls(10) + .maxWaitDuration(Duration.ofSeconds(5)) + .build()); + + return registry; + } +} diff --git a/src/main/java/com/xtraction/api/config/SecurityConfig.java b/src/main/java/com/xtraction/api/config/SecurityConfig.java index c4888b3..bf69cef 100644 --- a/src/main/java/com/xtraction/api/config/SecurityConfig.java +++ b/src/main/java/com/xtraction/api/config/SecurityConfig.java @@ -103,7 +103,8 @@ public SecurityFilterChain securityFilterChain( "/api/v1/paypal/plans", "/api/v1/paypal/return", "/api/v1/paypal/cancel", - "/api/v1/currency/**") + "/api/v1/currency/**", + "/ws/**") .permitAll() .requestMatchers( "/api/v1/admin/**") diff --git a/src/main/java/com/xtraction/api/config/WebSocketConfig.java b/src/main/java/com/xtraction/api/config/WebSocketConfig.java new file mode 100644 index 0000000..5bc1ffd --- /dev/null +++ b/src/main/java/com/xtraction/api/config/WebSocketConfig.java @@ -0,0 +1,49 @@ +package com.xtraction.api.config; + +import com.xtraction.api.websocket.WebSocketAuthInterceptor; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; +import org.springframework.messaging.simp.config.ChannelRegistration; +import org.springframework.messaging.simp.config.MessageBrokerRegistry; +import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; +import org.springframework.web.socket.config.annotation.StompEndpointRegistry; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; + +/** + * WebSocket configuration for real-time extraction progress notifications. + *

+ * Configures a STOMP endpoint at {@code /ws/extraction-progress} with SockJS fallback, + * an in-memory message broker for {@code /topic} and {@code /user/queue} destinations, + * and registers the {@link WebSocketAuthInterceptor} for ticket-based authentication. + */ +@Configuration +@EnableWebSocketMessageBroker +@RequiredArgsConstructor +public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { + + private final WebSocketAuthInterceptor webSocketAuthInterceptor; + + @Value("${app.frontend.url:http://localhost:4200}") + private String frontendUrl; + + @Override + public void configureMessageBroker(MessageBrokerRegistry registry) { + registry.enableSimpleBroker("/topic", "/queue"); + registry.setApplicationDestinationPrefixes("/app"); + registry.setUserDestinationPrefix("/user"); + } + + @Override + public void registerStompEndpoints(StompEndpointRegistry registry) { + registry.addEndpoint("/ws/extraction-progress") + .setAllowedOrigins(frontendUrl) + .setAllowedOriginPatterns("http://localhost:[*]", "https://localhost:[*]") + .withSockJS(); + } + + @Override + public void configureClientInboundChannel(ChannelRegistration registration) { + registration.interceptors(webSocketAuthInterceptor); + } +} diff --git a/src/main/java/com/xtraction/api/documents/controller/DocumentController.java b/src/main/java/com/xtraction/api/documents/controller/DocumentController.java index eacd5ed..b64d94d 100644 --- a/src/main/java/com/xtraction/api/documents/controller/DocumentController.java +++ b/src/main/java/com/xtraction/api/documents/controller/DocumentController.java @@ -4,13 +4,16 @@ import com.xtraction.api.documents.dto.request.UpdateCollectionRequest; import com.xtraction.api.documents.dto.request.UpdateDocumentRequest; import com.xtraction.api.documents.dto.response.*; -import com.xtraction.api.documents.dto.response.*; +import com.xtraction.api.documents.dto.response.StreamingUploadResponse; import com.xtraction.api.documents.service.DocumentService; +import com.xtraction.api.documents.service.StreamingUploadPipeline; import com.xtraction.api.exceptions.custom.BadRequestException; import com.xtraction.api.exceptions.custom.ForbiddenException; import com.xtraction.api.exceptions.custom.TooManyRequestsException; +import com.xtraction.api.storage.service.StorageAllocationService; import com.xtraction.api.user.model.User; import com.xtraction.api.user.repository.UserRepository; +import com.xtraction.api.utils.imageupload.FileUploadValidationUtil; import io.github.bucket4j.Bandwidth; import io.github.bucket4j.Bucket; import io.github.bucket4j.Refill; @@ -23,6 +26,7 @@ import jakarta.validation.Valid; import jakarta.validation.constraints.NotNull; import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; @@ -30,6 +34,7 @@ import org.springframework.web.multipart.MultipartFile; import java.time.Duration; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -41,6 +46,8 @@ public class DocumentController { private final DocumentService documentService; private final UserRepository userRepository; + private final StreamingUploadPipeline streamingUploadPipeline; + private final StorageAllocationService storageAllocationService; private final Map rateLimitBuckets = new ConcurrentHashMap<>(); private User getAuthenticatedUser(Authentication authenticatedUser) { @@ -60,7 +67,7 @@ private User getAuthenticatedUser(Authentication authenticatedUser) { @ApiResponse(responseCode = "403", description = "Forbidden - User not logged in or not found") }) @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - public ResponseEntity> uploadDocuments( + public ResponseEntity uploadDocuments( @Parameter(description = "Files to be uploaded and extracted", required = true, content = @Content(mediaType = MediaType.MULTIPART_FORM_DATA_VALUE)) @RequestParam("files") @NotNull MultipartFile[] files, @Parameter(description = "Optional name for the collection") @RequestParam(value = "collectionName", required = false) String collectionName, @Parameter(description = "Enable encryption (premium feature)") @RequestParam(value = "enableEncryption", defaultValue = "false") boolean enableEncryption, @@ -77,10 +84,29 @@ public ResponseEntity> throw new BadRequestException("No files provided for upload."); } - DocumentCollectionResponse response = documentService - .uploadDocuments(files, user, collectionName, enableEncryption); - - return ResponseEntity.ok(response); + // Synchronous validation before going async + FileUploadValidationUtil.validateTotalFileSize(files); + long totalUploadSize = Arrays.stream(files).mapToLong(MultipartFile::getSize).sum(); + storageAllocationService.checkStorageAvailable(user, totalUploadSize); + + // Generate collection ID upfront for the client + String collectionId = java.util.UUID.randomUUID().toString(); + + // Trigger async pipeline (upload only, no extraction) + streamingUploadPipeline.processUploadAsync( + files, user, collectionName, false, collectionId, + null, null, null); + + StreamingUploadResponse response = StreamingUploadResponse.builder() + .statusCode(HttpStatus.ACCEPTED.value()) + .status("ACCEPTED") + .message(String.format("%d document(s) accepted for processing.", files.length)) + .collectionId(collectionId) + .totalFiles(files.length) + .wsSubscriptionTopic("/user/queue/extraction-progress") + .build(); + + return ResponseEntity.status(HttpStatus.ACCEPTED).body(response); } private Bucket createRateLimitBucket(String userId) { diff --git a/src/main/java/com/xtraction/api/documents/dto/response/StreamingUploadResponse.java b/src/main/java/com/xtraction/api/documents/dto/response/StreamingUploadResponse.java new file mode 100644 index 0000000..44aee2c --- /dev/null +++ b/src/main/java/com/xtraction/api/documents/dto/response/StreamingUploadResponse.java @@ -0,0 +1,23 @@ +package com.xtraction.api.documents.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * Immediate response DTO for streaming upload endpoints. + * Returned with HTTP 202 Accepted when the upload pipeline starts processing. + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class StreamingUploadResponse { + private int statusCode; + private String status; + private String message; + private String collectionId; + private int totalFiles; + private String wsSubscriptionTopic; +} diff --git a/src/main/java/com/xtraction/api/documents/service/StreamingUploadPipeline.java b/src/main/java/com/xtraction/api/documents/service/StreamingUploadPipeline.java new file mode 100644 index 0000000..ae00eeb --- /dev/null +++ b/src/main/java/com/xtraction/api/documents/service/StreamingUploadPipeline.java @@ -0,0 +1,293 @@ +package com.xtraction.api.documents.service; + +import com.xtraction.api.documents.datamodel.DocumentStatus; +import com.xtraction.api.documents.datamodel.DocumentUploadState; +import com.xtraction.api.documents.model.DocumentCollection; +import com.xtraction.api.documents.model.FileEntry; +import com.xtraction.api.documents.repository.DocumentCollectionRepository; +import com.xtraction.api.documents.utils.SanitizeLogging; +import com.xtraction.api.exceptions.custom.BadRequestException; +import com.xtraction.api.ocrprocessing.datamodel.OcrStatus; +import com.xtraction.api.ocrprocessing.events.OcrEventPublisher; +import com.xtraction.api.ocrprocessing.events.OcrRequestedEvent; +import com.xtraction.api.ocrprocessing.model.OcrData; +import com.xtraction.api.ocrprocessing.repository.OcrDataRepository; +import com.xtraction.api.ocrprocessing.service.ExtractionProgressService; +import com.xtraction.api.ocrprocessing.utils.FileStorageService; +import com.xtraction.api.storage.service.StorageAllocationService; +import com.xtraction.api.user.model.User; +import com.xtraction.api.utils.imageupload.FileUploadValidationUtil; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Async streaming upload pipeline that processes files concurrently and triggers + * OCR extraction immediately per-file without waiting for sibling files. + * + *

Key behaviors:

+ *
    + *
  • Files are uploaded to S3 concurrently using CompletableFuture
  • + *
  • Each successful upload immediately publishes a Kafka OCR event (when autoExtract=true)
  • + *
  • Real-time WebSocket progress events are sent at every stage
  • + *
  • Circuit breakers protect S3 uploads from cascading failures
  • + *
+ */ +@Slf4j +@Service +@RequiredArgsConstructor +public class StreamingUploadPipeline { + + private final DocumentCollectionRepository documentCollectionRepository; + private final OcrDataRepository ocrDataRepository; + private final Optional ocrEventPublisher; + private final SanitizeLogging s; + private final FileStorageService fileStorageService; + private final StorageAllocationService storageAllocationService; + private final ExtractionProgressService progressService; + private final Executor uploadPipelineExecutor; + + @Autowired + @Lazy + private StreamingUploadPipeline self; + + /** + * Process file uploads asynchronously. This method returns immediately and + * processes files in background threads. + * + * @param files Files to upload + * @param user Authenticated user + * @param collectionName Optional collection name + * @param autoExtract Whether to trigger OCR extraction after upload + * @param collectionId Pre-generated collection ID + * @param startPage Optional start page for PDF extraction + * @param endPage Optional end page for PDF extraction + * @param pages Optional specific pages for PDF extraction + */ + @Async("uploadPipelineExecutor") + public void processUploadAsync( + MultipartFile[] files, + User user, + String collectionName, + boolean autoExtract, + String collectionId, + Integer startPage, + Integer endPage, + List pages) { + + String userId = user.getId(); + int totalFiles = files.length; + + log.info("Starting async upload pipeline for collection {} with {} files for user {}", + s.sanitizeLogging(collectionId), totalFiles, s.sanitizeLogging(userId)); + + // Send upload started progress + progressService.sendUploadStarted(userId, collectionId, totalFiles); + + // Create initial DocumentCollection with PROCESSING status + String resolvedCollectionName = collectionName != null ? collectionName : + "Collection-" + java.time.LocalDateTime.now().format( + java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd-HHmmss")); + + DocumentCollection collection = DocumentCollection.builder() + .user(user) + .name(resolvedCollectionName) + .files(new ArrayList<>()) + .collectionStatus(DocumentStatus.PROCESSING) + .uploadTimestamp(OffsetDateTime.now()) + .build(); + DocumentCollection savedCollection = documentCollectionRepository.saveAndFlush(collection); + String savedCollectionId = savedCollection.getId(); + + // Thread-safe collections for aggregating results + ConcurrentLinkedQueue successfulEntries = new ConcurrentLinkedQueue<>(); + ConcurrentLinkedQueue ocrDataToSave = new ConcurrentLinkedQueue<>(); + AtomicInteger successCount = new AtomicInteger(0); + AtomicInteger failedCount = new AtomicInteger(0); + + // Process each file concurrently + List> futures = new ArrayList<>(); + + for (int i = 0; i < files.length; i++) { + final int fileIndex = i; + final MultipartFile file = files[i]; + + CompletableFuture future = CompletableFuture.runAsync(() -> + processFileUpload( + file, fileIndex, totalFiles, userId, savedCollectionId, + autoExtract, startPage, endPage, pages, user, + successfulEntries, ocrDataToSave, successCount, failedCount + ), uploadPipelineExecutor); + + futures.add(future); + } + + // Wait for all file uploads to complete + CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); + + // Aggregate results and update the collection + self.finalizeCollection(savedCollection, successfulEntries, ocrDataToSave, + userId, totalFiles, successCount.get(), failedCount.get()); + } + + /** + * Process a single file upload: validate, upload to S3, create OcrData, + * and trigger extraction. + */ + private void processFileUpload( + MultipartFile file, + int fileIndex, + int totalFiles, + String userId, + String collectionId, + boolean autoExtract, + Integer startPage, + Integer endPage, + List pages, + User user, + ConcurrentLinkedQueue successfulEntries, + ConcurrentLinkedQueue ocrDataToSave, + AtomicInteger successCount, + AtomicInteger failedCount) { + + String originalFilename = Objects.requireNonNullElse(file.getOriginalFilename(), "unnamed_file"); + + try { + // Validate individual file + FileUploadValidationUtil.validateIndividualFile(file); + + // Upload to S3 (protected by circuit breaker) + FileEntry fileEntry = fileStorageService.handleSuccessfulFileUpload(file, originalFilename); + successfulEntries.add(fileEntry); + + // Send file uploaded progress + progressService.sendFileUploaded(userId, collectionId, fileEntry.getDocumentId(), + originalFilename, fileIndex + 1, totalFiles); + + // Create OcrData record for this file + if (autoExtract) { + OcrData ocrData = new OcrData(); + ocrData.setDocumentId(fileEntry.getDocumentId()); + ocrData.setStatus(OcrStatus.PENDING); + ocrDataToSave.add(ocrData); + + // Publish Kafka OCR event immediately (no waiting for other files) + ocrEventPublisher.ifPresent(publisher -> { + OcrRequestedEvent event = OcrRequestedEvent.builder() + .collectionId(collectionId) + .documentId(fileEntry.getDocumentId()) + .userId(userId) + .startPage(startPage) + .endPage(endPage) + .pages(pages) + .build(); + publisher.publishOcrRequest(event); + log.info("Published OCR event for document {} in collection {}", + s.sanitizeLogging(fileEntry.getDocumentId()), + s.sanitizeLogging(collectionId)); + }); + + // Send extraction queued progress + progressService.sendExtractionQueued(userId, collectionId, + fileEntry.getDocumentId(), originalFilename); + } + + successCount.incrementAndGet(); + + } catch (BadRequestException | IllegalArgumentException validationEx) { + log.warn("Validation failed for file {}: {}", s.sanitizeLogging(originalFilename), + s.sanitizeLogging(validationEx.getMessage())); + progressService.sendFileUploadFailed(userId, collectionId, originalFilename, + "Validation failed: " + validationEx.getMessage(), fileIndex + 1, totalFiles); + failedCount.incrementAndGet(); + + } catch (Exception e) { + log.error("Failed to upload file {} to storage: {}", s.sanitizeLogging(originalFilename), + s.sanitizeLogging(e.getMessage()), e); + progressService.sendFileUploadFailed(userId, collectionId, originalFilename, + "Upload failed: " + e.getMessage(), fileIndex + 1, totalFiles); + failedCount.incrementAndGet(); + } + } + + /** + * Finalize the collection after all files have been processed. + * Updates the DocumentCollection with file entries, saves OcrData, and + * sends pipeline completion progress. + */ + @Transactional + protected void finalizeCollection( + DocumentCollection collection, + ConcurrentLinkedQueue successfulEntries, + ConcurrentLinkedQueue ocrDataToSave, + String userId, + int totalFiles, + int successCount, + int failedCount) { + + String collectionId = collection.getId(); + + // Reload the collection within the transaction + DocumentCollection managedCollection = documentCollectionRepository.findById(collectionId) + .orElse(collection); + + List fileEntries = new ArrayList<>(successfulEntries); + + if (!fileEntries.isEmpty()) { + managedCollection.setFiles(fileEntries); + + if (successCount > 0 && failedCount == 0) { + managedCollection.setCollectionStatus(DocumentStatus.PROCESSING); + } else if (successCount > 0) { + managedCollection.setCollectionStatus(DocumentStatus.PROCESSING); + } else { + managedCollection.setCollectionStatus(DocumentStatus.FAILED_UPLOAD); + } + + documentCollectionRepository.saveAndFlush(managedCollection); + + // Save OcrData records + if (!ocrDataToSave.isEmpty()) { + ocrDataRepository.saveAll(new ArrayList<>(ocrDataToSave)); + ocrDataRepository.flush(); + } + + // Update storage usage + if (successCount > 0) { + try { + storageAllocationService.updateMonthlyDocumentsUploaded(userId, successCount); + } catch (Exception e) { + log.error("Failed to update storage allocation for user {}: {}", + s.sanitizeLogging(userId), e.getMessage()); + } + } + + log.info("Collection {} finalized with {} successful, {} failed uploads for user {}", + s.sanitizeLogging(collectionId), successCount, failedCount, + s.sanitizeLogging(userId)); + } else { + managedCollection.setCollectionStatus(DocumentStatus.FAILED_UPLOAD); + documentCollectionRepository.save(managedCollection); + log.info("No files uploaded successfully for collection {}", + s.sanitizeLogging(collectionId)); + } + + // Send pipeline completed progress + progressService.sendPipelineCompleted(userId, collectionId, totalFiles, successCount, failedCount); + } +} diff --git a/src/main/java/com/xtraction/api/ocrprocessing/controller/OcrDocumentController.java b/src/main/java/com/xtraction/api/ocrprocessing/controller/OcrDocumentController.java index f0d7183..fe460ba 100644 --- a/src/main/java/com/xtraction/api/ocrprocessing/controller/OcrDocumentController.java +++ b/src/main/java/com/xtraction/api/ocrprocessing/controller/OcrDocumentController.java @@ -2,6 +2,8 @@ import com.xtraction.api.documents.dto.response.DocumentCollectionResponse; import com.xtraction.api.documents.dto.response.DocumentCollectionUploadData; +import com.xtraction.api.documents.dto.response.StreamingUploadResponse; +import com.xtraction.api.documents.service.StreamingUploadPipeline; import com.xtraction.api.exceptions.custom.BadRequestException; import com.xtraction.api.exceptions.custom.ForbiddenException; import com.xtraction.api.ocrprocessing.dto.request.UpdateOcrContentRequest; @@ -9,8 +11,10 @@ import com.xtraction.api.ocrprocessing.dto.response.FileResultData; import com.xtraction.api.ocrprocessing.model.OcrData; import com.xtraction.api.ocrprocessing.service.OcrService; +import com.xtraction.api.storage.service.StorageAllocationService; import com.xtraction.api.user.model.User; import com.xtraction.api.user.repository.UserRepository; +import com.xtraction.api.utils.imageupload.FileUploadValidationUtil; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; @@ -27,6 +31,8 @@ import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; +import java.util.Arrays; + @RestController @RequestMapping("/api/v1/collections") @RequiredArgsConstructor @@ -34,6 +40,8 @@ public class OcrDocumentController { private final OcrService ocrService; private final UserRepository userRepository; + private final StreamingUploadPipeline streamingUploadPipeline; + private final StorageAllocationService storageAllocationService; private User getAuthenticatedUser(Authentication authenticatedUser) { if (authenticatedUser == null) { @@ -84,7 +92,7 @@ public ResponseEntity> extractTextFromFile( @ApiResponse(responseCode = "500", description = "Internal Server Error - OCR processing failed") }) @PostMapping(value = "/upload/extract-all", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) - public ResponseEntity> extractTextFromAllFiles( + public ResponseEntity extractTextFromAllFiles( @Parameter(description = "Files to be uploaded and extracted", required = true, content = @Content(mediaType = MediaType.MULTIPART_FORM_DATA_VALUE)) @RequestParam("files") @NotNull MultipartFile[] files, @Parameter(description = "Start page for PDF extraction (1-indexed, inclusive). Only applies to PDF files.") @RequestParam(required = false) Integer startPage, @@ -100,10 +108,29 @@ public ResponseEntity> throw new BadRequestException("No files provided for extraction."); } - DocumentCollectionResponse response = ocrService.uploadDocuments(files, - user, startPage, endPage, pages); + // Synchronous validation before going async + FileUploadValidationUtil.validateTotalFileSize(files); + long totalUploadSize = Arrays.stream(files).mapToLong(MultipartFile::getSize).sum(); + storageAllocationService.checkStorageAvailable(user, totalUploadSize); - return ResponseEntity.ok(response); + // Generate collection ID upfront for the client + String collectionId = java.util.UUID.randomUUID().toString(); + + // Trigger async pipeline (upload + extract) + streamingUploadPipeline.processUploadAsync( + files, user, null, true, collectionId, + startPage, endPage, pages); + + StreamingUploadResponse response = StreamingUploadResponse.builder() + .statusCode(HttpStatus.ACCEPTED.value()) + .status("ACCEPTED") + .message(String.format("%d document(s) accepted for upload and extraction.", files.length)) + .collectionId(collectionId) + .totalFiles(files.length) + .wsSubscriptionTopic("/user/queue/extraction-progress") + .build(); + + return ResponseEntity.status(HttpStatus.ACCEPTED).body(response); } @Operation(summary = "Get OCR results for a document collection", description = "Retrieves the OCR results for a specific document collection.", responses = { diff --git a/src/main/java/com/xtraction/api/ocrprocessing/dto/response/ExtractionProgressEvent.java b/src/main/java/com/xtraction/api/ocrprocessing/dto/response/ExtractionProgressEvent.java new file mode 100644 index 0000000..23ce987 --- /dev/null +++ b/src/main/java/com/xtraction/api/ocrprocessing/dto/response/ExtractionProgressEvent.java @@ -0,0 +1,37 @@ +package com.xtraction.api.ocrprocessing.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.OffsetDateTime; +import java.util.Map; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class ExtractionProgressEvent { + private String collectionId; + private String documentId; + private String fileName; + private ProgressEventType eventType; + private int progress; // 0-100 + private String message; + private OffsetDateTime timestamp; + private Map metadata; + + public enum ProgressEventType { + UPLOAD_STARTED, + FILE_UPLOADING, + FILE_UPLOADED, + FILE_UPLOAD_FAILED, + EXTRACTION_QUEUED, + EXTRACTION_STARTED, + EXTRACTION_PROGRESS, + EXTRACTION_COMPLETED, + EXTRACTION_FAILED, + PIPELINE_COMPLETED + } +} diff --git a/src/main/java/com/xtraction/api/ocrprocessing/events/OcrEventMapper.java b/src/main/java/com/xtraction/api/ocrprocessing/events/OcrEventMapper.java index d42299d..0b880ac 100644 --- a/src/main/java/com/xtraction/api/ocrprocessing/events/OcrEventMapper.java +++ b/src/main/java/com/xtraction/api/ocrprocessing/events/OcrEventMapper.java @@ -9,6 +9,7 @@ @Mapper(componentModel = "spring") public interface OcrEventMapper { + @Mapping(target = "userId", ignore = true) @Mapping(target = "collectionId", source = "collectionId") @Mapping(target = "documentId", source = "fileEntry.documentId") @Mapping(target = "startPage", ignore = true) @@ -16,6 +17,7 @@ public interface OcrEventMapper { @Mapping(target = "pages", ignore = true) OcrRequestedEvent toOcrRequestedEvent(FileEntry fileEntry, String collectionId); + @Mapping(target = "userId", ignore = true) @Mapping(target = "collectionId", source = "collectionId") @Mapping(target = "documentId", source = "fileEntry.documentId") @Mapping(target = "startPage", source = "startPage") diff --git a/src/main/java/com/xtraction/api/ocrprocessing/events/OcrMessageListener.java b/src/main/java/com/xtraction/api/ocrprocessing/events/OcrMessageListener.java index e22c02b..a3626c9 100644 --- a/src/main/java/com/xtraction/api/ocrprocessing/events/OcrMessageListener.java +++ b/src/main/java/com/xtraction/api/ocrprocessing/events/OcrMessageListener.java @@ -3,6 +3,7 @@ import com.xtraction.api.brokers.kafka.config.KafkaTopicConfig; import com.xtraction.api.documents.utils.SanitizeLogging; import com.xtraction.api.ocrprocessing.interfaces.ProcessOcrService; +import com.xtraction.api.ocrprocessing.service.ExtractionProgressService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.clients.consumer.ConsumerRecord; @@ -16,17 +17,21 @@ * - High throughput for batch document processing * - Better partitioning for parallel processing * - Stream processing capabilities - * + *

* OCR engine selection is handled by OcrProcessingService based on user * subscription: * - FREE tier: Tesseract (local) * - Paid subscribers: Google Cloud Vision + *

+ * Sends real-time WebSocket progress events via ExtractionProgressService + * when userId is available in the event payload. */ @Slf4j @Component @RequiredArgsConstructor public class OcrMessageListener { private final ProcessOcrService ocrService; + private final ExtractionProgressService extractionProgressService; private final SanitizeLogging s; @KafkaListener(topics = KafkaTopicConfig.TOPIC_DOCUMENTS, groupId = "unraveldocs-ocr-group", containerFactory = "kafkaListenerContainerFactory") @@ -47,12 +52,32 @@ public void receiveOcrRequestedEvent( acknowledgment.acknowledge(); // Manual acknowledgment after successful processing log.debug("OCR processing completed successfully for document ID: {}", s.sanitizeLogging(payload.getDocumentId())); + + // Send WebSocket extraction completed notification + if (payload.getUserId() != null) { + extractionProgressService.sendExtractionCompleted( + payload.getUserId(), + payload.getCollectionId(), + payload.getDocumentId(), + null); + } } catch (Exception e) { log.error("Error processing OCR request for collection ID: {}, document ID: {}. Partition key: {}. Error: {}", s.sanitizeLogging(payload.getCollectionId()), s.sanitizeLogging(payload.getDocumentId()), s.sanitizeLogging(partitionKey), e.getMessage(), e); + + // Send WebSocket extraction failed notification + if (payload.getUserId() != null) { + extractionProgressService.sendExtractionFailed( + payload.getUserId(), + payload.getCollectionId(), + payload.getDocumentId(), + null, + e.getMessage()); + } + // Do not acknowledge - message will be redelivered or sent to DLQ throw e; } diff --git a/src/main/java/com/xtraction/api/ocrprocessing/events/OcrRequestedEvent.java b/src/main/java/com/xtraction/api/ocrprocessing/events/OcrRequestedEvent.java index 6c126c2..5a489d0 100644 --- a/src/main/java/com/xtraction/api/ocrprocessing/events/OcrRequestedEvent.java +++ b/src/main/java/com/xtraction/api/ocrprocessing/events/OcrRequestedEvent.java @@ -15,6 +15,7 @@ public class OcrRequestedEvent implements Serializable { private String collectionId; private String documentId; + private String userId; private Integer startPage; private Integer endPage; private List pages; diff --git a/src/main/java/com/xtraction/api/ocrprocessing/service/ExtractionProgressService.java b/src/main/java/com/xtraction/api/ocrprocessing/service/ExtractionProgressService.java new file mode 100644 index 0000000..fbd4827 --- /dev/null +++ b/src/main/java/com/xtraction/api/ocrprocessing/service/ExtractionProgressService.java @@ -0,0 +1,212 @@ +package com.xtraction.api.ocrprocessing.service; + +import com.xtraction.api.documents.utils.SanitizeLogging; +import com.xtraction.api.ocrprocessing.dto.response.ExtractionProgressEvent; +import com.xtraction.api.ocrprocessing.dto.response.ExtractionProgressEvent.ProgressEventType; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.stereotype.Service; + +import java.time.OffsetDateTime; +import java.util.Map; + +/** + * Service for sending real-time extraction progress events to users via WebSocket. + *

+ * All methods in this service are designed to be fail-safe — exceptions are caught + * and logged so that progress notification failures never break the extraction pipeline. + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class ExtractionProgressService { + + private static final String DESTINATION = "/queue/extraction-progress"; + + private final SimpMessagingTemplate messagingTemplate; + private final SanitizeLogging sanitizer; + + /** + * Sends a progress event to the specified user. + * + * @param userId the user ID (used as the STOMP user principal) + * @param event the progress event to send + */ + public void sendProgress(String userId, ExtractionProgressEvent event) { + try { + messagingTemplate.convertAndSendToUser(userId, DESTINATION, event); + log.debug( + "Sent {} event to user [{}] for document [{}]", + sanitizer.sanitizeLoggingObject(event.getEventType()), + sanitizer.sanitizeLogging(userId), + sanitizer.sanitizeLogging(event.getDocumentId()) + ); + } catch (Exception e) { + log.error( + "Failed to send progress event {} to user [{}]: {}", + sanitizer.sanitizeLoggingObject(event.getEventType()), + sanitizer.sanitizeLogging(userId), e.getMessage(), e); + } + } + + /** + * Notifies the user that an upload batch has started. + */ + public void sendUploadStarted(String userId, String collectionId, int totalFiles) { + sendProgress(userId, ExtractionProgressEvent.builder() + .collectionId(collectionId) + .eventType(ProgressEventType.UPLOAD_STARTED) + .progress(0) + .message("Starting upload of " + totalFiles + " file(s)") + .timestamp(OffsetDateTime.now()) + .metadata(Map.of("totalFiles", totalFiles)) + .build()); + } + + /** + * Notifies the user that a file has been uploaded successfully. + */ + public void sendFileUploaded(String userId, String collectionId, String documentId, + String fileName, int fileIndex, int totalFiles) { + int progress = (int) ((fileIndex / (double) totalFiles) * 50); + sendProgress(userId, ExtractionProgressEvent.builder() + .collectionId(collectionId) + .documentId(documentId) + .fileName(fileName) + .eventType(ProgressEventType.FILE_UPLOADED) + .progress(progress) + .message("Uploaded " + fileName + " (" + fileIndex + "/" + totalFiles + ")") + .timestamp(OffsetDateTime.now()) + .metadata(Map.of( + "fileIndex", fileIndex, + "totalFiles", totalFiles + )) + .build()); + } + + /** + * Notifies the user that a file upload has failed. + */ + public void sendFileUploadFailed(String userId, String collectionId, String fileName, + String error, int fileIndex, int totalFiles) { + sendProgress(userId, ExtractionProgressEvent.builder() + .collectionId(collectionId) + .fileName(fileName) + .eventType(ProgressEventType.FILE_UPLOAD_FAILED) + .progress((int) ((fileIndex / (double) totalFiles) * 50)) + .message("Failed to upload " + fileName + ": " + error) + .timestamp(OffsetDateTime.now()) + .metadata(Map.of( + "fileIndex", fileIndex, + "totalFiles", totalFiles, + "error", error + )) + .build()); + } + + /** + * Notifies the user that a document has been queued for extraction. + */ + public void sendExtractionQueued(String userId, String collectionId, + String documentId, String fileName) { + sendProgress(userId, ExtractionProgressEvent.builder() + .collectionId(collectionId) + .documentId(documentId) + .fileName(fileName) + .eventType(ProgressEventType.EXTRACTION_QUEUED) + .progress(50) + .message("Queued " + fileName + " for extraction") + .timestamp(OffsetDateTime.now()) + .build()); + } + + /** + * Notifies the user that extraction has started for a document. + */ + public void sendExtractionStarted(String userId, String collectionId, + String documentId, String fileName) { + sendProgress(userId, ExtractionProgressEvent.builder() + .collectionId(collectionId) + .documentId(documentId) + .fileName(fileName) + .eventType(ProgressEventType.EXTRACTION_STARTED) + .progress(55) + .message("Extracting text from " + fileName) + .timestamp(OffsetDateTime.now()) + .build()); + } + + /** + * Notifies the user of extraction progress for multi-page documents. + * + * @param progress 0-100 representing extraction completion percentage + */ + public void sendExtractionProgress(String userId, String collectionId, + String documentId, String fileName, int progress) { + int scaledProgress = 55 + (int) ((progress / 100.0) * 40); + sendProgress(userId, ExtractionProgressEvent.builder() + .collectionId(collectionId) + .documentId(documentId) + .fileName(fileName) + .eventType(ProgressEventType.EXTRACTION_PROGRESS) + .progress(scaledProgress) + .message("Extracting " + fileName + " — " + progress + "% complete") + .timestamp(OffsetDateTime.now()) + .metadata(Map.of("rawProgress", progress)) + .build()); + } + + /** + * Notifies the user that extraction has completed for a document. + */ + public void sendExtractionCompleted(String userId, String collectionId, + String documentId, String fileName) { + sendProgress(userId, ExtractionProgressEvent.builder() + .collectionId(collectionId) + .documentId(documentId) + .fileName(fileName) + .eventType(ProgressEventType.EXTRACTION_COMPLETED) + .progress(95) + .message("Extraction completed for " + fileName) + .timestamp(OffsetDateTime.now()) + .build()); + } + + /** + * Notifies the user that extraction has failed for a document. + */ + public void sendExtractionFailed(String userId, String collectionId, + String documentId, String fileName, String error) { + sendProgress(userId, ExtractionProgressEvent.builder() + .collectionId(collectionId) + .documentId(documentId) + .fileName(fileName) + .eventType(ProgressEventType.EXTRACTION_FAILED) + .progress(0) + .message("Extraction failed for " + fileName + ": " + error) + .timestamp(OffsetDateTime.now()) + .metadata(Map.of("error", error)) + .build()); + } + + /** + * Sends a final summary event when the entire extraction pipeline is complete. + */ + public void sendPipelineCompleted(String userId, String collectionId, + int totalFiles, int successCount, int failedCount) { + sendProgress(userId, ExtractionProgressEvent.builder() + .collectionId(collectionId) + .eventType(ProgressEventType.PIPELINE_COMPLETED) + .progress(100) + .message("Pipeline completed: " + successCount + " succeeded, " + + failedCount + " failed out of " + totalFiles + " file(s)") + .timestamp(OffsetDateTime.now()) + .metadata(Map.of( + "totalFiles", totalFiles, + "successCount", successCount, + "failedCount", failedCount + )) + .build()); + } +} diff --git a/src/main/java/com/xtraction/api/ocrprocessing/service/OcrProcessingService.java b/src/main/java/com/xtraction/api/ocrprocessing/service/OcrProcessingService.java index 7bcb9ab..aca7f7c 100644 --- a/src/main/java/com/xtraction/api/ocrprocessing/service/OcrProcessingService.java +++ b/src/main/java/com/xtraction/api/ocrprocessing/service/OcrProcessingService.java @@ -6,10 +6,12 @@ import com.xtraction.api.ocrprocessing.exception.OcrProcessingException; import com.xtraction.api.ocrprocessing.metrics.OcrMetrics; import com.xtraction.api.ocrprocessing.provider.*; -import com.xtraction.api.ocrprocessing.provider.*; import com.xtraction.api.ocrprocessing.quota.OcrQuotaService; import com.xtraction.api.storage.service.StorageAllocationService; import com.xtraction.api.subscription.service.SubscriptionFeatureService; +import io.github.resilience4j.bulkhead.annotation.Bulkhead; +import io.github.resilience4j.circuitbreaker.CircuitBreaker; +import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry; import io.micrometer.core.instrument.Timer; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -34,11 +36,12 @@ public class OcrProcessingService { private final SanitizeLogging sanitizer; private final CreditBalanceService creditBalanceService; private final SubscriptionFeatureService subscriptionFeatureService; + private final CircuitBreakerRegistry circuitBreakerRegistry; /** * Process an OCR request with automatic provider selection based on * subscription plan and credit balance. - * + *

* Provider selection rules: * - Paid plan (any tier) → Google Vision (no credits deducted) * - Free plan + enough credits → Google Vision (credits deducted) @@ -50,6 +53,7 @@ public class OcrProcessingService { * @throws OcrProcessingException if processing fails and fallback is not * available */ + @Bulkhead(name = "ocrProcessing") public OcrResult processOcr(OcrRequest request, String userId) { Timer.Sample timerSample = ocrMetrics.startTimer(); OcrProvider primaryProvider = null; @@ -67,7 +71,7 @@ public OcrResult processOcr(OcrRequest request, String userId) { isPaid); // Process with primary provider - OcrResult result = primaryProvider.extractText(request); + OcrResult result = executeWithCircuitBreaker(primaryProvider, request); if (result.isSuccess()) { storageAllocationService.updateOcrUsage(userId, 1); @@ -103,7 +107,7 @@ public OcrResult processOcr(OcrRequest request, String userId) { /** * Resolve the OCR provider based on subscription plan and credit balance. - * + *

* - Paid plan → Google Vision (no credits deducted) * - Free plan + enough credits → Google Vision (credits deducted after OCR) * - Free plan + not enough credits → Tesseract (no credits deducted) @@ -187,7 +191,7 @@ public OcrResult processOcrWithProvider( Timer.Sample timerSample = ocrMetrics.startTimer(); try { - OcrResult result = provider.extractText(request); + OcrResult result = executeWithCircuitBreaker(provider, request); if (result.isSuccess()) { storageAllocationService.updateOcrUsage(userId, 1); @@ -279,7 +283,7 @@ private OcrResult executeFallback( Timer.Sample timerSample = ocrMetrics.startTimer(); try { - OcrResult result = fallbackProvider.extractText(request); + OcrResult result = executeWithCircuitBreaker(fallbackProvider, request); if (result.isSuccess()) { storageAllocationService.updateOcrUsage(userId, 1); @@ -319,4 +323,22 @@ private Optional getFallbackProvider(OcrProviderType failedType) { return providerFactory.getProviderOptional(fallbackType); } + + /** + * Execute OCR text extraction through the appropriate circuit breaker. + * Selects the circuit breaker name based on the provider type. + * + * @param provider The OCR provider to execute + * @param request The OCR request + * @return The OCR result + */ + private OcrResult executeWithCircuitBreaker(OcrProvider provider, OcrRequest request) { + String cbName = switch (provider.getProviderType()) { + case GOOGLE_VISION -> "ocrGoogleVision"; + case TESSERACT -> "ocrTesseract"; + }; + + CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker(cbName); + return circuitBreaker.executeSupplier(() -> provider.extractText(request)); + } } diff --git a/src/main/java/com/xtraction/api/ocrprocessing/service/ProcessOcr.java b/src/main/java/com/xtraction/api/ocrprocessing/service/ProcessOcr.java index a4ce585..c5011b3 100644 --- a/src/main/java/com/xtraction/api/ocrprocessing/service/ProcessOcr.java +++ b/src/main/java/com/xtraction/api/ocrprocessing/service/ProcessOcr.java @@ -38,13 +38,14 @@ @RequiredArgsConstructor public class ProcessOcr implements ProcessOcrService { private final DocumentCollectionRepository documentCollectionRepository; - private final SanitizeLogging sanitizeLogging; + private final SanitizeLogging sanitizer; private final OcrDataRepository ocrDataRepository; private final OcrProcessingService ocrProcessingService; private final CreditBalanceService creditBalanceService; private final UserRepository userRepository; private final Optional elasticsearchIndexingService; private final NotificationService notificationService; + private final ExtractionProgressService progressService; @Override @Transactional @@ -69,15 +70,24 @@ public void processOcrRequest(String collectionId, String documentId, "OCR data not found for document ID: " + fileEntry.getDocumentId())); if (ocrData.getStatus() == OcrStatus.COMPLETED) { - log.info("File {} already processed. Skipping.", sanitizeLogging.sanitizeLogging(documentId)); + log.info("File {} already processed. Skipping.", sanitizer.sanitizeLogging(documentId)); return; } ocrData.setStatus(OcrStatus.PROCESSING); ocrDataRepository.save(ocrData); + // Extract userId early so it's available in both try and catch blocks + String userId = collection.getUser().getId(); + String fileName = fileEntry.getOriginalFileName(); + + // Send WebSocket extraction started progress + progressService.sendExtractionStarted(userId, collectionId, documentId, fileName); + try { - log.info("Starting OCR text extraction for document: {}", sanitizeLogging.sanitizeLogging(documentId)); + log.info( + "Starting OCR text extraction for document: {}", + sanitizer.sanitizeLogging(documentId)); // Send OCR started notification sendOcrNotification(collection.getUser().getId(), NotificationType.OCR_PROCESSING_STARTED, @@ -88,9 +98,6 @@ public void processOcrRequest(String collectionId, String documentId, // Build OCR request using the new abstraction OcrRequest ocrRequest = buildOcrRequest(fileEntry, collection, startPage, endPage, pages); - // Get user ID - String userId = collection.getUser().getId(); - // Process using provider abstraction (provider resolved internally by plan + // credits) OcrResult result = ocrProcessingService.processOcr(ocrRequest, userId); @@ -99,7 +106,7 @@ public void processOcrRequest(String collectionId, String documentId, updateOcrDataFromResult(ocrData, result); log.info("OCR text extraction completed for document: {} using provider: {}", - sanitizeLogging.sanitizeLogging(documentId), + sanitizer.sanitizeLogging(documentId), result.getProviderType()); // Deduct credits only for free plan users when Google Vision was used @@ -110,33 +117,39 @@ public void processOcrRequest(String collectionId, String documentId, creditBalanceService.deductCredits(user, 1, documentId, "OCR processing (Google Vision) for document " + documentId); log.info("Deducted 1 credit for Google Vision OCR of document {} for user {}", - sanitizeLogging.sanitizeLogging(documentId), - sanitizeLogging.sanitizeLogging(userId)); + sanitizer.sanitizeLogging(documentId), + sanitizer.sanitizeLogging(userId)); } }); } catch (Exception e) { log.error("Failed to deduct credit for user {}: {}", - sanitizeLogging.sanitizeLogging(userId), e.getMessage(), e); + sanitizer.sanitizeLogging(userId), e.getMessage(), e); } } // Send OCR completed notification - sendOcrNotification(collection.getUser().getId(), NotificationType.OCR_PROCESSING_COMPLETED, + sendOcrNotification(userId, NotificationType.OCR_PROCESSING_COMPLETED, "OCR Processing Completed", "OCR processing completed successfully. Your document is now searchable.", documentId, collection.getId()); + // Send WebSocket extraction completed progress + progressService.sendExtractionCompleted(userId, collectionId, documentId, fileName); + } catch (Exception e) { log.error("OCR processing failed for document {}: {}", - sanitizeLogging.sanitizeLogging(documentId), e.getMessage(), e); + sanitizer.sanitizeLogging(documentId), e.getMessage(), e); ocrData.setStatus(OcrStatus.FAILED); ocrData.setErrorMessage(e.getMessage()); // Send OCR failed notification - sendOcrNotification(collection.getUser().getId(), NotificationType.OCR_PROCESSING_FAILED, + sendOcrNotification(userId, NotificationType.OCR_PROCESSING_FAILED, "OCR Processing Failed", "OCR processing failed: " + e.getMessage(), documentId, collection.getId()); + + // Send WebSocket extraction failed progress + progressService.sendExtractionFailed(userId, collectionId, documentId, fileName, e.getMessage()); } finally { updateCollectionStatus(collection); ocrDataRepository.save(ocrData); @@ -213,7 +226,7 @@ private void updateCollectionStatus(DocumentCollection collection) { collection.setCollectionStatus(DocumentStatus.PROCESSING); } log.info("Collection {} status updated to: {}", - sanitizeLogging.sanitizeLogging(collection.getId()), collection.getCollectionStatus()); + sanitizer.sanitizeLogging(collection.getId()), collection.getCollectionStatus()); } /** @@ -227,7 +240,7 @@ private void sendOcrNotification(String userId, NotificationType type, data.put("collectionId", collectionId); notificationService.sendToUser(userId, type, title, message, data); - log.debug("Sent {} notification to user {}", type, sanitizeLogging.sanitizeLogging(userId)); + log.debug("Sent {} notification to user {}", type, sanitizer.sanitizeLogging(userId)); } catch (Exception e) { log.error("Failed to send OCR notification: {}", e.getMessage()); } diff --git a/src/main/java/com/xtraction/api/ocrprocessing/utils/FileStorageService.java b/src/main/java/com/xtraction/api/ocrprocessing/utils/FileStorageService.java index edb942f..8119a7f 100644 --- a/src/main/java/com/xtraction/api/ocrprocessing/utils/FileStorageService.java +++ b/src/main/java/com/xtraction/api/ocrprocessing/utils/FileStorageService.java @@ -4,13 +4,17 @@ import com.xtraction.api.documents.model.FileEntry; import com.xtraction.api.documents.utils.SanitizeLogging; import com.xtraction.api.utils.imageupload.aws.AwsS3Service; +import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker; +import io.github.resilience4j.retry.annotation.Retry; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import java.util.List; +@Slf4j @Component @RequiredArgsConstructor public class FileStorageService { @@ -39,11 +43,14 @@ public static int getStorageFailures( /** * Handles the successful upload of a file to storage. + * Protected by a circuit breaker and retry mechanism for S3 resilience. * * @param file The uploaded file. * @param originalFileName The original filename of the uploaded file. * @return A FileEntry object containing details of the uploaded file. */ + @CircuitBreaker(name = "s3Upload", fallbackMethod = "handleUploadFallback") + @Retry(name = "s3Upload") public FileEntry handleSuccessfulFileUpload(MultipartFile file, String originalFileName) { String fileName = awsS3Service.generateFileName(originalFileName, AwsS3Service.getDOCUMENT_PICTURE_FOLDER()); String fileUrl = awsS3Service.uploadFile(file, fileName); @@ -59,4 +66,19 @@ public FileEntry handleSuccessfulFileUpload(MultipartFile file, String originalF .uploadStatus(DocumentUploadState.SUCCESS.toString()) .build(); } + + /** + * Fallback method invoked when the S3 upload circuit breaker is open or all retries are exhausted. + * + * @param file The uploaded file. + * @param originalFileName The original filename. + * @param e The exception that triggered the fallback. + * @return never returns — always throws RuntimeException. + */ + private FileEntry handleUploadFallback(MultipartFile file, String originalFileName, Exception e) { + log.error("S3 upload failed for file '{}' after circuit breaker/retry exhaustion: {}", + originalFileName, e.getMessage(), e); + throw new RuntimeException( + "S3 storage service is currently unavailable. Upload failed for file: " + originalFileName, e); + } } diff --git a/src/main/java/com/xtraction/api/websocket/WebSocketAuthInterceptor.java b/src/main/java/com/xtraction/api/websocket/WebSocketAuthInterceptor.java new file mode 100644 index 0000000..00323df --- /dev/null +++ b/src/main/java/com/xtraction/api/websocket/WebSocketAuthInterceptor.java @@ -0,0 +1,70 @@ +package com.xtraction.api.websocket; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.simp.stomp.StompCommand; +import org.springframework.messaging.simp.stomp.StompHeaderAccessor; +import org.springframework.messaging.support.ChannelInterceptor; +import org.springframework.messaging.support.MessageHeaderAccessor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Optional; + +/** + * Channel interceptor that authenticates STOMP WebSocket connections. + *

+ * On STOMP CONNECT frames, this interceptor extracts a {@code ticket} from + * the native headers and validates it via {@link WebSocketTicketService}. + * If valid, a {@link UsernamePasswordAuthenticationToken} is set on the + * accessor so the user is authenticated for the session. + */ +@Slf4j +@Component +@RequiredArgsConstructor +public class WebSocketAuthInterceptor implements ChannelInterceptor { + + private final WebSocketTicketService webSocketTicketService; + + @Override + public Message preSend(Message message, MessageChannel channel) { + StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor( + message, StompHeaderAccessor.class); + + if (accessor == null || accessor.getCommand() != StompCommand.CONNECT) { + return message; + } + + List ticketHeaders = accessor.getNativeHeader("ticket"); + String ticket = (ticketHeaders != null && !ticketHeaders.isEmpty()) + ? ticketHeaders.getFirst() + : null; + + if (ticket == null || ticket.isBlank()) { + log.warn("WebSocket CONNECT rejected: missing ticket header"); + throw new IllegalArgumentException("WebSocket authentication ticket is required"); + } + + Optional userIdOpt = webSocketTicketService.validateAndConsumeTicket(ticket); + + if (userIdOpt.isEmpty()) { + log.warn("WebSocket CONNECT rejected: invalid or expired ticket"); + throw new IllegalArgumentException("Invalid or expired WebSocket authentication ticket"); + } + + String userId = userIdOpt.get(); + UsernamePasswordAuthenticationToken authentication = + new UsernamePasswordAuthenticationToken( + userId, null, + List.of(new SimpleGrantedAuthority("ROLE_USER"))); + + accessor.setUser(authentication); + log.debug("WebSocket CONNECT authenticated for user [{}]", userId); + + return message; + } +} diff --git a/src/main/java/com/xtraction/api/websocket/WebSocketTicketController.java b/src/main/java/com/xtraction/api/websocket/WebSocketTicketController.java new file mode 100644 index 0000000..38cd0a0 --- /dev/null +++ b/src/main/java/com/xtraction/api/websocket/WebSocketTicketController.java @@ -0,0 +1,71 @@ +package com.xtraction.api.websocket; + +import com.xtraction.api.exceptions.custom.ForbiddenException; +import com.xtraction.api.user.model.User; +import com.xtraction.api.user.repository.UserRepository; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Map; + +/** + * REST controller for issuing one-time WebSocket authentication tickets. + *

+ * Clients call this endpoint to obtain a short-lived ticket, then pass it + * as a STOMP header during the WebSocket CONNECT handshake. + */ +@RestController +@RequestMapping("/api/v1/ws") +@RequiredArgsConstructor +@Tag(name = "WebSocket", description = "Endpoints for WebSocket ticket-based authentication") +public class WebSocketTicketController { + + private final WebSocketTicketService webSocketTicketService; + private final UserRepository userRepository; + + @Operation( + summary = "Issue a WebSocket authentication ticket", + description = "Generates a one-time, short-lived ticket that the client uses to authenticate " + + "the STOMP WebSocket connection. The ticket expires after 30 seconds and can only be used once.", + responses = { + @ApiResponse( + responseCode = "200", + description = "Ticket issued successfully", + content = @Content( + mediaType = "application/json", + schema = @Schema( + type = "object", + example = "{\"ticket\": \"a1b2c3d4-e5f6-7890-abcd-ef1234567890\", \"wsUrl\": \"/ws/extraction-progress\"}" + ) + ) + ), + @ApiResponse(responseCode = "403", description = "Forbidden - User not authenticated or not found") + } + ) + @PostMapping("/ticket") + public ResponseEntity> issueTicket(Authentication authenticatedUser) { + if (authenticatedUser == null) { + throw new ForbiddenException("You must be logged in to perform this action."); + } + + String email = authenticatedUser.getName(); + User user = userRepository.findByEmail(email) + .orElseThrow(() -> new ForbiddenException("User not found. Please log in again.")); + + String ticket = webSocketTicketService.issueTicket(user.getId()); + + return ResponseEntity.ok(Map.of( + "ticket", ticket, + "wsUrl", "/ws/extraction-progress" + )); + } +} diff --git a/src/main/java/com/xtraction/api/websocket/WebSocketTicketService.java b/src/main/java/com/xtraction/api/websocket/WebSocketTicketService.java new file mode 100644 index 0000000..5e503d4 --- /dev/null +++ b/src/main/java/com/xtraction/api/websocket/WebSocketTicketService.java @@ -0,0 +1,73 @@ +package com.xtraction.api.websocket; + +import com.xtraction.api.documents.utils.SanitizeLogging; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Service; + +import java.time.Duration; +import java.util.Optional; +import java.util.UUID; + +/** + * Service for issuing and validating one-time WebSocket authentication tickets. + *

+ * Tickets are stored in Redis with a 30-second TTL and are consumed (deleted) + * upon first use to prevent replay attacks. + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class WebSocketTicketService { + + private static final String TICKET_KEY_PREFIX = "ws:ticket:"; + private static final Duration TICKET_TTL = Duration.ofSeconds(30); + private final SanitizeLogging sanitizer; + + private final StringRedisTemplate stringRedisTemplate; + + /** + * Issues a one-time WebSocket authentication ticket for the given user. + * + * @param userId the ID of the authenticated user + * @return the generated ticket string + */ + public String issueTicket(String userId) { + String ticket = UUID.randomUUID().toString(); + String key = TICKET_KEY_PREFIX + ticket; + stringRedisTemplate.opsForValue().set(key, userId, TICKET_TTL); + log.debug("Issued WebSocket ticket for user [{}]", sanitizer.sanitizeLogging(userId)); + return ticket; + } + + /** + * Validates and consumes a one-time WebSocket authentication ticket. + *

+ * If the ticket is valid, the associated user ID is returned and the ticket + * is deleted from Redis so it cannot be reused. + * + * @param ticket the ticket to validate + * @return an {@link Optional} containing the user ID if valid, or empty if invalid/expired + */ + public Optional validateAndConsumeTicket(String ticket) { + if (ticket == null || ticket.isBlank()) { + return Optional.empty(); + } + + String key = TICKET_KEY_PREFIX + ticket; + String userId = stringRedisTemplate.opsForValue().get(key); + + if (userId == null) { + log.warn("Invalid or expired WebSocket ticket attempted"); + return Optional.empty(); + } + + // Delete the ticket so it cannot be reused (one-time use) + stringRedisTemplate.delete(key); + log.debug( + "Validated and consumed WebSocket ticket for user [{}]", + sanitizer.sanitizeLogging(userId)); + return Optional.of(userId); + } +}