📦 EqualifyEverything / equalify-reflow

📄 storage_service.py · 777 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777"""Storage service for S3 operations."""

import asyncio
import json
import logging
import uuid
from typing import TYPE_CHECKING, Any

from botocore.exceptions import ClientError
from fastapi import HTTPException, UploadFile

from ..config import settings
from ..utils.circuit_breaker import CircuitBreaker, CircuitBreakerOpenError
from ..utils.retry_helpers import retry_with_backoff_for_sync_func

if TYPE_CHECKING:
    from ..shared.models.processing_result import ProcessingResult

logger = logging.getLogger(__name__)


class StorageService:
    """Service for managing document storage in S3."""

    def __init__(self, s3_client: Any, temp_bucket: str, results_bucket: str):
        """Initialize storage service with S3 client and bucket names.

        Args:
            s3_client: Boto3 S3 client instance
            temp_bucket: Name of temporary storage bucket
            results_bucket: Name of results storage bucket
        """
        self.s3_client = s3_client
        self.temp_bucket = temp_bucket
        self.results_bucket = results_bucket

        # Circuit breakers for S3 operation types
        self.upload_circuit = CircuitBreaker(
            name="s3-upload",
            failure_threshold=5,
            success_threshold=2,
            timeout=60.0
        )
        self.download_circuit = CircuitBreaker(
            name="s3-download",
            failure_threshold=5,
            success_threshold=2,
            timeout=60.0
        )

    async def store_document(self, file: UploadFile) -> tuple[str, str]:
        """
        Store uploaded document in S3 temp bucket.

        Args:
            file: Uploaded PDF file

        Returns:
            Tuple of (job_id, s3_key)

        Raises:
            HTTPException: If file validation fails or upload fails
            CircuitBreakerOpenError: If S3 upload circuit breaker is open
        """
        # Check circuit breaker first
        self.upload_circuit.check_state()
        if self.upload_circuit.is_open:
            raise CircuitBreakerOpenError("S3 upload circuit breaker is open due to repeated failures")

        # Validate PDF format
        if file.content_type != "application/pdf":
            raise HTTPException(
                status_code=400,
                detail="Only PDF files are accepted"
            )

        # Validate file size
        try:
            file.file.seek(0, 2)  # Seek to end
            file_size = file.file.tell()
            file.file.seek(0)  # Reset to beginning
        except (OSError, AttributeError) as e:
            raise HTTPException(
                status_code=400,
                detail=f"Unable to read file: {str(e)}"
            )

        # Check minimum file size (empty or corrupt files)
        min_file_size = 100  # 100 bytes minimum
        if file_size < min_file_size:
            raise HTTPException(
                status_code=400,
                detail=f"File too small. Minimum file size is {min_file_size} bytes"
            )

        # Check maximum file size (files up to max_upload_size are accepted)
        if file_size > settings.max_upload_size:
            raise HTTPException(
                status_code=413,
                detail=f"File size exceeds maximum allowed size of {settings.max_upload_size / (1024 * 1024)}MB"
            )

        # Generate unique job ID and S3 key
        job_id = str(uuid.uuid4())
        s3_key = f"temp/{job_id}.pdf"

        try:
            # Upload to S3 with retry logic
            await retry_with_backoff_for_sync_func(
                lambda: self.s3_client.upload_fileobj(
                    file.file,
                    self.temp_bucket,
                    s3_key
                ),
                max_attempts=3,
                base_delay=1.0,
                operation_name=f"upload {s3_key}"
            )

            # Record success in circuit breaker
            self.upload_circuit.record_success()

        except CircuitBreakerOpenError:
            # Circuit breaker already logged the issue
            raise
        except Exception as e:
            # Record failure in circuit breaker
            self.upload_circuit.record_failure()

            raise HTTPException(
                status_code=500,
                detail=f"Failed to upload file to storage: {str(e)}"
            )

        return job_id, s3_key


    async def check_s3_access(self) -> bool:
        """
        Check if S3 is accessible.

        Returns:
            True if S3 is accessible, False otherwise
        """
        try:
            self.s3_client.head_bucket(Bucket=self.temp_bucket)
            return True
        except Exception:
            return False

    async def download_temp_file(self, s3_key: str) -> bytes:
        """
        Download file from temp bucket with retry and circuit breaker.

        Args:
            s3_key: S3 key of file to download

        Returns:
            File contents as bytes

        Raises:
            HTTPException: If download fails
            CircuitBreakerOpenError: If S3 download circuit breaker is open
        """
        # Check circuit breaker
        self.download_circuit.check_state()
        if self.download_circuit.is_open:
            raise CircuitBreakerOpenError("S3 download circuit breaker is open due to repeated failures")

        try:
            # Download with retry logic
            response: Any = await retry_with_backoff_for_sync_func(
                lambda: self.s3_client.get_object(
                    Bucket=self.temp_bucket,
                    Key=s3_key
                ),
                max_attempts=3,
                base_delay=1.0,
                operation_name=f"download {s3_key}"
            )

            # Record success
            self.download_circuit.record_success()

            return response['Body'].read()  # type: ignore[no-any-return]

        except CircuitBreakerOpenError:
            raise
        except ClientError as e:
            # Record failure
            self.download_circuit.record_failure()

            if e.response['Error']['Code'] == 'NoSuchKey':
                raise HTTPException(
                    status_code=404,
                    detail=f"File not found: {s3_key}"
                )
            raise HTTPException(
                status_code=500,
                detail=f"Failed to download file: {str(e)}"
            )
        except Exception as e:
            # Record failure
            self.download_circuit.record_failure()

            raise HTTPException(
                status_code=500,
                detail=f"Unexpected error downloading file: {str(e)}"
            )

    async def download_file(self, s3_key: str) -> bytes:
        """
        Download file from results bucket with retry and circuit breaker.

        Args:
            s3_key: S3 key of file to download

        Returns:
            File contents as bytes

        Raises:
            HTTPException: If download fails
            CircuitBreakerOpenError: If S3 download circuit breaker is open
        """
        # Check circuit breaker
        self.download_circuit.check_state()
        if self.download_circuit.is_open:
            raise CircuitBreakerOpenError(
                "S3 download circuit breaker is open due to repeated failures"
            )

        try:
            # Download with retry logic
            response: Any = await retry_with_backoff_for_sync_func(
                lambda: self.s3_client.get_object(
                    Bucket=self.results_bucket,
                    Key=s3_key
                ),
                max_attempts=3,
                base_delay=1.0,
                operation_name=f"download {s3_key}"
            )

            # Record success
            self.download_circuit.record_success()

            return response['Body'].read()  # type: ignore[no-any-return]

        except CircuitBreakerOpenError:
            raise
        except ClientError as e:
            # Record failure
            self.download_circuit.record_failure()

            if e.response['Error']['Code'] == 'NoSuchKey':
                raise HTTPException(
                    status_code=404,
                    detail=f"File not found: {s3_key}"
                )
            raise HTTPException(
                status_code=500,
                detail=f"Failed to download file: {str(e)}"
            )
        except Exception as e:
            # Record failure
            self.download_circuit.record_failure()

            raise HTTPException(
                status_code=500,
                detail=f"Unexpected error downloading file: {str(e)}"
            )

    async def upload_result(
        self,
        job_id: str,
        content: str,
        format: str,
        suffix: str | None = None
    ) -> str:
        """
        Upload processed result to results bucket with retry and circuit breaker.

        Args:
            job_id: Job identifier
            content: Markdown content as string
            format: File format ('md')
            suffix: Optional suffix for versioning (e.g., 'original', 'corrected')

        Returns:
            S3 key (e.g., "abc-123.md" or "abc-123-original.md")

        Raises:
            HTTPException: If upload fails
            CircuitBreakerOpenError: If S3 upload circuit breaker is open
        """
        # Check circuit breaker
        self.upload_circuit.check_state()
        if self.upload_circuit.is_open:
            raise CircuitBreakerOpenError("S3 upload circuit breaker is open due to repeated failures")

        # Build S3 key with optional suffix
        if suffix:
            s3_key = f"{job_id}-{suffix}.{format}"
        else:
            s3_key = f"{job_id}.{format}"

        # Set correct Content-Type based on format
        content_type_map = {
            'md': 'text/markdown'
        }
        content_type = content_type_map.get(format, 'text/plain')

        try:
            # Upload to results bucket with retry
            body = content if isinstance(content, bytes) else content.encode('utf-8')

            await retry_with_backoff_for_sync_func(
                lambda: self.s3_client.put_object(
                    Bucket=self.results_bucket,
                    Key=s3_key,
                    Body=body,
                    ContentType=content_type,
                    CacheControl='public, max-age=31536000'
                ),
                max_attempts=3,
                base_delay=1.0,
                operation_name=f"upload result {s3_key}"
            )

            # Record success
            self.upload_circuit.record_success()

            # Return S3 key (not URL)
            return s3_key

        except CircuitBreakerOpenError:
            raise
        except ClientError as e:
            # Record failure
            self.upload_circuit.record_failure()

            # Preserve ClientError for retry logic to categorize properly
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            raise HTTPException(
                status_code=500,
                detail=f"Failed to upload result: {error_code}"
            ) from e
        except Exception as e:
            # Record failure
            self.upload_circuit.record_failure()

            raise HTTPException(
                status_code=500,
                detail=f"Failed to upload result: {str(e)}"
            )

    async def upload_image(
        self,
        job_id: str,
        image_data: bytes,
        image_name: str
    ) -> str:
        """Upload extracted image (figure/table) to results bucket with retry and circuit breaker.

        Images are stored in a subfolder structure: {job_id}/images/{image_name}
        This allows grouping all assets for a job together.

        Args:
            job_id: Job identifier
            image_data: PNG image bytes
            image_name: Filename for image (e.g., "figure-1.png", "table-2.png")

        Returns:
            S3 key (e.g., "abc-123/images/figure-1.png")

        Raises:
            HTTPException: If upload fails
            CircuitBreakerOpenError: If S3 upload circuit breaker is open
        """
        # Check circuit breaker
        self.upload_circuit.check_state()
        if self.upload_circuit.is_open:
            raise CircuitBreakerOpenError("S3 upload circuit breaker is open due to repeated failures")

        s3_key = f"{job_id}/images/{image_name}"

        try:
            await retry_with_backoff_for_sync_func(
                lambda: self.s3_client.put_object(
                    Bucket=self.results_bucket,
                    Key=s3_key,
                    Body=image_data,
                    ContentType='image/png',
                    CacheControl='public, max-age=31536000'
                ),
                max_attempts=3,
                base_delay=1.0,
                operation_name=f"upload image {image_name}"
            )

            # Record success
            self.upload_circuit.record_success()

            # Return S3 key (URL generation delegated to S3URLService)
            return s3_key

        except CircuitBreakerOpenError:
            raise
        except ClientError as e:
            # Record failure
            self.upload_circuit.record_failure()

            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            raise HTTPException(
                status_code=500,
                detail=f"Failed to upload image {image_name}: {error_code}"
            ) from e
        except Exception as e:
            # Record failure
            self.upload_circuit.record_failure()

            raise HTTPException(
                status_code=500,
                detail=f"Failed to upload image {image_name}: {str(e)}"
            )

    async def upload_page_image(
        self,
        job_id: str,
        page_num: int,
        image_data: bytes
    ) -> str:
        """Upload page preview image to temp bucket for correction review.

        Page images are stored temporarily for human review of AI corrections.
        They are stored in: {job_id}/pages/page-{num}.png

        These images are deleted after correction approval (7-day TTL).

        Args:
            job_id: Job identifier
            page_num: Page number (1-indexed)
            image_data: PNG image bytes

        Returns:
            S3 key (e.g., "abc-123/pages/page-1.png")

        Raises:
            HTTPException: If upload fails
            CircuitBreakerOpenError: If S3 upload circuit breaker is open
        """
        # Check circuit breaker
        self.upload_circuit.check_state()
        if self.upload_circuit.is_open:
            raise CircuitBreakerOpenError("S3 upload circuit breaker is open due to repeated failures")

        s3_key = f"{job_id}/pages/page-{page_num}.png"

        try:
            await retry_with_backoff_for_sync_func(
                lambda: self.s3_client.put_object(
                    Bucket=self.temp_bucket,
                    Key=s3_key,
                    Body=image_data,
                    ContentType='image/png',
                    CacheControl='public, max-age=604800'  # 7 days
                ),
                max_attempts=3,
                base_delay=1.0,
                operation_name=f"upload page {page_num} image"
            )

            # Record success
            self.upload_circuit.record_success()

            # Return S3 key (not URL)
            return s3_key

        except CircuitBreakerOpenError:
            raise
        except ClientError as e:
            # Record failure
            self.upload_circuit.record_failure()

            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            raise HTTPException(
                status_code=500,
                detail=f"Failed to upload page {page_num} image: {error_code}"
            ) from e
        except Exception as e:
            # Record failure
            self.upload_circuit.record_failure()

            raise HTTPException(
                status_code=500,
                detail=f"Failed to upload page {page_num} image: {str(e)}"
            )


    async def file_exists(self, bucket: str, key: str) -> bool:
        """
        Check if file exists in specified bucket.

        Args:
            bucket: Bucket name
            key: S3 object key

        Returns:
            True if file exists, False otherwise
        """
        try:
            self.s3_client.head_object(Bucket=bucket, Key=key)
            return True
        except ClientError as e:
            if e.response['Error']['Code'] == '404':
                return False
            # For other errors, assume file doesn't exist
            return False
        except Exception:
            return False

    async def load_processing_result(self, job_id: str) -> "ProcessingResult | None":
        """Load ProcessingResult from S3.

        Args:
            job_id: Job identifier

        Returns:
            ProcessingResult if found, None if not found

        Raises:
            HTTPException: If download fails (other than not found)
            CircuitBreakerOpenError: If S3 download circuit breaker is open
        """
        from ..shared.models.processing_result import ProcessingResult

        # Check circuit breaker
        self.download_circuit.check_state()
        if self.download_circuit.is_open:
            raise CircuitBreakerOpenError(
                "S3 download circuit breaker is open due to repeated failures"
            )

        key = f"jobs/{job_id}/processing_result.json"

        try:
            response: Any = await retry_with_backoff_for_sync_func(
                lambda: self.s3_client.get_object(
                    Bucket=self.results_bucket,
                    Key=key
                ),
                max_attempts=3,
                base_delay=1.0,
                operation_name=f"load processing result {job_id}"
            )

            # Record success
            self.download_circuit.record_success()

            data = json.loads(response['Body'].read().decode('utf-8'))
            return ProcessingResult.model_validate(data)

        except CircuitBreakerOpenError:
            raise
        except ClientError as e:
            if e.response['Error']['Code'] == 'NoSuchKey':
                return None
            # Record failure
            self.download_circuit.record_failure()
            raise HTTPException(
                status_code=500,
                detail=f"Failed to load processing result: {str(e)}"
            )
        except Exception as e:
            # Record failure
            self.download_circuit.record_failure()
            raise HTTPException(
                status_code=500,
                detail=f"Unexpected error loading processing result: {str(e)}"
            )

    async def save_processing_result(
        self,
        job_id: str,
        result: "ProcessingResult"
    ) -> str:
        """Save ProcessingResult to S3.

        Args:
            job_id: Job identifier
            result: ProcessingResult to save

        Returns:
            S3 key where result was saved

        Raises:
            HTTPException: If upload fails
            CircuitBreakerOpenError: If S3 upload circuit breaker is open
        """
        # Check circuit breaker
        self.upload_circuit.check_state()
        if self.upload_circuit.is_open:
            raise CircuitBreakerOpenError(
                "S3 upload circuit breaker is open due to repeated failures"
            )

        key = f"jobs/{job_id}/processing_result.json"

        try:
            body = result.model_dump_json(indent=2)

            await retry_with_backoff_for_sync_func(
                lambda: self.s3_client.put_object(
                    Bucket=self.results_bucket,
                    Key=key,
                    Body=body.encode('utf-8'),
                    ContentType='application/json',
                ),
                max_attempts=3,
                base_delay=1.0,
                operation_name=f"save processing result {job_id}"
            )

            # Record success
            self.upload_circuit.record_success()

            logger.info(f"Saved ProcessingResult for job {job_id}")
            return key

        except CircuitBreakerOpenError:
            raise
        except ClientError as e:
            # Record failure
            self.upload_circuit.record_failure()
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            raise HTTPException(
                status_code=500,
                detail=f"Failed to save processing result: {error_code}"
            ) from e
        except Exception as e:
            # Record failure
            self.upload_circuit.record_failure()
            raise HTTPException(
                status_code=500,
                detail=f"Failed to save processing result: {str(e)}"
            )

    async def upload_final_markdown(self, job_id: str, markdown: str) -> str:
        """Upload final reviewed markdown and return URL.

        This is used after all reviews have been applied to save the
        final accessible markdown document.

        Args:
            job_id: Job identifier
            markdown: Final markdown content

        Returns:
            S3 key where markdown was saved

        Raises:
            HTTPException: If upload fails
            CircuitBreakerOpenError: If S3 upload circuit breaker is open
        """
        # Check circuit breaker
        self.upload_circuit.check_state()
        if self.upload_circuit.is_open:
            raise CircuitBreakerOpenError(
                "S3 upload circuit breaker is open due to repeated failures"
            )

        key = f"jobs/{job_id}/final.md"

        try:
            await retry_with_backoff_for_sync_func(
                lambda: self.s3_client.put_object(
                    Bucket=self.results_bucket,
                    Key=key,
                    Body=markdown.encode('utf-8'),
                    ContentType='text/markdown',
                    CacheControl='public, max-age=31536000'
                ),
                max_attempts=3,
                base_delay=1.0,
                operation_name=f"upload final markdown {job_id}"
            )

            # Record success
            self.upload_circuit.record_success()

            logger.info(f"Uploaded final markdown for job {job_id}")
            return key

        except CircuitBreakerOpenError:
            raise
        except ClientError as e:
            # Record failure
            self.upload_circuit.record_failure()
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            raise HTTPException(
                status_code=500,
                detail=f"Failed to upload final markdown: {error_code}"
            ) from e
        except Exception as e:
            # Record failure
            self.upload_circuit.record_failure()
            raise HTTPException(
                status_code=500,
                detail=f"Failed to upload final markdown: {str(e)}"
            )

    async def upload_file(
        self,
        key: str,
        content: bytes,
        content_type: str = "application/octet-stream",
    ) -> str:
        """Upload a file to the results bucket.

        Generic method for uploading any file to S3 results bucket.

        Args:
            key: S3 key (path) for the file
            content: File content as bytes
            content_type: MIME type of the content

        Returns:
            S3 key where file was saved

        Raises:
            HTTPException: If upload fails
            CircuitBreakerOpenError: If S3 upload circuit breaker is open
        """
        # Check circuit breaker
        self.upload_circuit.check_state()
        if self.upload_circuit.is_open:
            raise CircuitBreakerOpenError(
                "S3 upload circuit breaker is open due to repeated failures"
            )

        try:
            await retry_with_backoff_for_sync_func(
                lambda: self.s3_client.put_object(
                    Bucket=self.results_bucket,
                    Key=key,
                    Body=content,
                    ContentType=content_type,
                ),
                max_attempts=3,
                base_delay=1.0,
                operation_name=f"upload file {key}"
            )

            # Record success
            self.upload_circuit.record_success()

            logger.info(f"Uploaded file to {key}")
            return key

        except CircuitBreakerOpenError:
            raise
        except ClientError as e:
            # Record failure
            self.upload_circuit.record_failure()
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            raise HTTPException(
                status_code=500,
                detail=f"Failed to upload file: {error_code}"
            ) from e
        except Exception as e:
            # Record failure
            self.upload_circuit.record_failure()
            raise HTTPException(
                status_code=500,
                detail=f"Failed to upload file: {str(e)}"
            )