From 7964b22c9da4f3f7386987c27916a98c7d228956 Mon Sep 17 00:00:00 2001 From: Shawn N Date: Sat, 11 Apr 2026 19:52:18 -0700 Subject: [PATCH 1/6] Add adobe api handling Add polling to catch adobe api failures --- .../adobe_autotag_processor.py | 55 +++++++++++++++++-- 1 file changed, 51 insertions(+), 4 deletions(-) diff --git a/adobe-autotag-container/adobe_autotag_processor.py b/adobe-autotag-container/adobe_autotag_processor.py index 0afd7185..dc607837 100644 --- a/adobe-autotag-container/adobe_autotag_processor.py +++ b/adobe-autotag-container/adobe_autotag_processor.py @@ -177,6 +177,49 @@ def add_viewer_preferences(pdf_path, filename): writer.write(f) logger.info(f'Filename : {filename} | Viewer preferences added to the PDF') +def poll_job_until_done(pdf_services, location, result_type, filename, job_name): + """ + Polls Adobe PDF Services job status until completion or failure. + Unlike get_job_result(), this detects 'failed' status immediately + instead of hanging indefinitely on damaged or complex PDFs. + + Args: + pdf_services: PDFServices instance. + location: Polling URL returned by submit(). + result_type: Expected result class (e.g. AutotagPDFResult). + filename: Filename for logging. + job_name: Human-readable job name for logging (e.g. "Autotag"). + + Returns: + PDFServicesResponse on success. + + Raises: + ServiceApiException: If the job fails on Adobe's side. + """ + import time + from adobe.pdfservices.operation.pdf_services_job_status import PDFServicesJobStatus + + while True: + status_response = pdf_services.get_job_status(location) + status = status_response.get_status() + + if status == PDFServicesJobStatus.DONE.get_value(): + logging.info(f'Filename : {filename} | Adobe {job_name} job completed, fetching result...') + return pdf_services.get_job_result(location, result_type) + + if status == PDFServicesJobStatus.FAILED.get_value(): + raise ServiceApiException( + message=f"Adobe {job_name} API job failed - PDF may be damaged or too complex", + status_code=400 + ) + + # Still in progress — wait the interval Adobe tells us to + retry_interval = status_response.get_retry_interval() + wait_time = retry_interval if retry_interval > 0 else 1 + logging.info(f'Filename : {filename} | Adobe {job_name} job in progress, retrying in {wait_time}s...') + time.sleep(wait_time) + + def autotag_pdf_with_options(filename, client_id, client_secret): """ Auto-tags a PDF for accessibility using Adobe PDF Services. @@ -223,9 +266,11 @@ def autotag_pdf_with_options(filename, client_id, client_secret): autotag_pdf_job = AutotagPDFJob(input_asset=input_asset, autotag_pdf_params=autotag_pdf_params) - # Submit the job and gets the job result + # Submit the job and poll for status, catching failures immediately location = pdf_services.submit(autotag_pdf_job) - pdf_services_response = pdf_services.get_job_result(location, AutotagPDFResult) + pdf_services_response = poll_job_until_done( + pdf_services, location, AutotagPDFResult, filename, "Autotag" + ) # Get content from the resulting asset(s) result_asset: CloudAsset = pdf_services_response.get_result().get_tagged_pdf() @@ -290,9 +335,11 @@ def extract_api(filename, client_id, client_secret): # Creates a new job instance extract_pdf_job = ExtractPDFJob(input_asset=input_asset, extract_pdf_params=extract_pdf_params) - # Submit the job and gets the job result + # Submit the job and poll for status, catching failures immediately location = pdf_services.submit(extract_pdf_job) - pdf_services_response = pdf_services.get_job_result(location, ExtractPDFResult) + pdf_services_response = poll_job_until_done( + pdf_services, location, ExtractPDFResult, filename, "Extract" + ) # Get content from the resulting asset(s) result_asset: CloudAsset = pdf_services_response.get_result().get_resource() From b9441faebb6175a29dc7abea502ac9f703c6489f Mon Sep 17 00:00:00 2001 From: Shawn N Date: Sun, 12 Apr 2026 09:41:56 -0700 Subject: [PATCH 2/6] Update missing request tracking id --- adobe-autotag-container/adobe_autotag_processor.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/adobe-autotag-container/adobe_autotag_processor.py b/adobe-autotag-container/adobe_autotag_processor.py index dc607837..47201a12 100644 --- a/adobe-autotag-container/adobe_autotag_processor.py +++ b/adobe-autotag-container/adobe_autotag_processor.py @@ -209,8 +209,9 @@ def poll_job_until_done(pdf_services, location, result_type, filename, job_name) if status == PDFServicesJobStatus.FAILED.get_value(): raise ServiceApiException( - message=f"Adobe {job_name} API job failed - PDF may be damaged or too complex", - status_code=400 + f"Adobe {job_name} API job failed - PDF may be damaged or too complex", + "N/A", + 400 ) # Still in progress — wait the interval Adobe tells us to From a699a29ff6f52a9173f2215c90b4a7dbb287e6c6 Mon Sep 17 00:00:00 2001 From: Shawn N Date: Sun, 12 Apr 2026 11:05:06 -0700 Subject: [PATCH 3/6] Fix inf loop on ECS error --- app.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/app.py b/app.py index 1148d0bd..b3e1cf2f 100644 --- a/app.py +++ b/app.py @@ -201,6 +201,12 @@ def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: ), propagated_tag_source=ecs.PropagatedTagSource.TASK_DEFINITION, ) + + # Disable default retries so damaged/complex PDFs fail fast + adobe_autotag_task.add_retry( + errors=["States.ALL"], + max_attempts=0 + ) alt_text_generation_task = tasks.EcsRunTask(self, "RunAltTextGenerationTask", integration_pattern=sfn.IntegrationPattern.RUN_JOB, @@ -231,6 +237,12 @@ def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: propagated_tag_source=ecs.PropagatedTagSource.TASK_DEFINITION, ) + # Disable default retries so failures fail fast + alt_text_generation_task.add_retry( + errors=["States.ALL"], + max_attempts=0 + ) + # Step Function Map State pdf_chunks_map_state = sfn.Map(self, "ProcessPdfChunksInParallel", max_concurrency=100, From 4d2841e32e5b34949845752196777dae30d361db Mon Sep 17 00:00:00 2001 From: Shawn N Date: Sun, 12 Apr 2026 11:09:25 -0700 Subject: [PATCH 4/6] Update adobe_autotag_processor.py --- .../adobe_autotag_processor.py | 56 ++----------------- 1 file changed, 4 insertions(+), 52 deletions(-) diff --git a/adobe-autotag-container/adobe_autotag_processor.py b/adobe-autotag-container/adobe_autotag_processor.py index 47201a12..ac25aac2 100644 --- a/adobe-autotag-container/adobe_autotag_processor.py +++ b/adobe-autotag-container/adobe_autotag_processor.py @@ -177,50 +177,6 @@ def add_viewer_preferences(pdf_path, filename): writer.write(f) logger.info(f'Filename : {filename} | Viewer preferences added to the PDF') -def poll_job_until_done(pdf_services, location, result_type, filename, job_name): - """ - Polls Adobe PDF Services job status until completion or failure. - Unlike get_job_result(), this detects 'failed' status immediately - instead of hanging indefinitely on damaged or complex PDFs. - - Args: - pdf_services: PDFServices instance. - location: Polling URL returned by submit(). - result_type: Expected result class (e.g. AutotagPDFResult). - filename: Filename for logging. - job_name: Human-readable job name for logging (e.g. "Autotag"). - - Returns: - PDFServicesResponse on success. - - Raises: - ServiceApiException: If the job fails on Adobe's side. - """ - import time - from adobe.pdfservices.operation.pdf_services_job_status import PDFServicesJobStatus - - while True: - status_response = pdf_services.get_job_status(location) - status = status_response.get_status() - - if status == PDFServicesJobStatus.DONE.get_value(): - logging.info(f'Filename : {filename} | Adobe {job_name} job completed, fetching result...') - return pdf_services.get_job_result(location, result_type) - - if status == PDFServicesJobStatus.FAILED.get_value(): - raise ServiceApiException( - f"Adobe {job_name} API job failed - PDF may be damaged or too complex", - "N/A", - 400 - ) - - # Still in progress — wait the interval Adobe tells us to - retry_interval = status_response.get_retry_interval() - wait_time = retry_interval if retry_interval > 0 else 1 - logging.info(f'Filename : {filename} | Adobe {job_name} job in progress, retrying in {wait_time}s...') - time.sleep(wait_time) - - def autotag_pdf_with_options(filename, client_id, client_secret): """ Auto-tags a PDF for accessibility using Adobe PDF Services. @@ -267,11 +223,9 @@ def autotag_pdf_with_options(filename, client_id, client_secret): autotag_pdf_job = AutotagPDFJob(input_asset=input_asset, autotag_pdf_params=autotag_pdf_params) - # Submit the job and poll for status, catching failures immediately + # Submit the job and gets the job result location = pdf_services.submit(autotag_pdf_job) - pdf_services_response = poll_job_until_done( - pdf_services, location, AutotagPDFResult, filename, "Autotag" - ) + pdf_services_response = pdf_services.get_job_result(location, AutotagPDFResult) # Get content from the resulting asset(s) result_asset: CloudAsset = pdf_services_response.get_result().get_tagged_pdf() @@ -336,11 +290,9 @@ def extract_api(filename, client_id, client_secret): # Creates a new job instance extract_pdf_job = ExtractPDFJob(input_asset=input_asset, extract_pdf_params=extract_pdf_params) - # Submit the job and poll for status, catching failures immediately + # Submit the job and gets the job result location = pdf_services.submit(extract_pdf_job) - pdf_services_response = poll_job_until_done( - pdf_services, location, ExtractPDFResult, filename, "Extract" - ) + pdf_services_response = pdf_services.get_job_result(location, AutotagPDFResult) # Get content from the resulting asset(s) result_asset: CloudAsset = pdf_services_response.get_result().get_resource() From 0073b00d04fcc046d9c0a18d0d589f2461eab2b2 Mon Sep 17 00:00:00 2001 From: Shawn N Date: Sun, 12 Apr 2026 11:10:13 -0700 Subject: [PATCH 5/6] Update adobe_autotag_processor.py --- adobe-autotag-container/adobe_autotag_processor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adobe-autotag-container/adobe_autotag_processor.py b/adobe-autotag-container/adobe_autotag_processor.py index ac25aac2..0afd7185 100644 --- a/adobe-autotag-container/adobe_autotag_processor.py +++ b/adobe-autotag-container/adobe_autotag_processor.py @@ -292,7 +292,7 @@ def extract_api(filename, client_id, client_secret): # Submit the job and gets the job result location = pdf_services.submit(extract_pdf_job) - pdf_services_response = pdf_services.get_job_result(location, AutotagPDFResult) + pdf_services_response = pdf_services.get_job_result(location, ExtractPDFResult) # Get content from the resulting asset(s) result_asset: CloudAsset = pdf_services_response.get_result().get_resource() From 1bfb74ad2141d7992eb3f6c62d0a25e79ee6cfdf Mon Sep 17 00:00:00 2001 From: Shawn N Date: Sun, 12 Apr 2026 12:16:46 -0700 Subject: [PATCH 6/6] Push Failed file json to S3 result --- app.py | 25 ++++++++++ lambda/error-handler-lambda/main.py | 74 +++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 lambda/error-handler-lambda/main.py diff --git a/app.py b/app.py index b3e1cf2f..42dc780b 100644 --- a/app.py +++ b/app.py @@ -378,6 +378,31 @@ def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: parallel_accessibility_workflow.branch(remediation_chain) parallel_accessibility_workflow.branch(pre_remediation_accessibility_checker_task) + # Error handler Lambda — writes failure marker to S3 so frontend stops polling + error_handler_lambda = lambda_.Function( + self, 'WorkflowErrorHandlerLambda', + runtime=lambda_.Runtime.PYTHON_3_12, + handler='main.lambda_handler', + code=lambda_.Code.from_asset('lambda/error-handler-lambda'), + timeout=Duration.seconds(30), + memory_size=128, + architecture=lambda_arch, + ) + pdf_processing_bucket.grant_write(error_handler_lambda) + + error_handler_task = tasks.LambdaInvoke( + self, "HandleWorkflowError", + lambda_function=error_handler_lambda, + output_path="$.Payload" + ) + + # Catch any error in the parallel workflow and route to error handler + parallel_accessibility_workflow.add_catch( + error_handler_task, + errors=["States.ALL"], + result_path="$.errorInfo" + ) + pdf_remediation_workflow_log_group = logs.LogGroup(self, "PdfRemediationWorkflowLogs", log_group_name="/aws/states/pdf-accessibility-remediation-workflow", retention=logs.RetentionDays.ONE_MONTH, diff --git a/lambda/error-handler-lambda/main.py b/lambda/error-handler-lambda/main.py new file mode 100644 index 00000000..b24ab5f0 --- /dev/null +++ b/lambda/error-handler-lambda/main.py @@ -0,0 +1,74 @@ +""" +Error handler Lambda for the PDF Accessibility remediation workflow. +Writes a failure status file to S3 so the frontend can detect processing failures +instead of polling indefinitely. +""" +import json +import boto3 +import logging + +logger = logging.getLogger() +logger.setLevel(logging.INFO) + +s3_client = boto3.client('s3') + + +def lambda_handler(event, context): + """ + Handles Step Function errors by writing a failure marker to S3. + + The event contains the original workflow input (s3_bucket, chunks) + plus error details injected by the Step Functions Catch block. + Writes a FAILED_.json file to the result/ prefix so the + frontend can detect the failure and stop polling. + """ + logger.info(f"Error handler invoked with event: {json.dumps(event)}") + + try: + bucket_name = event.get("s3_bucket", "") + chunks = event.get("chunks", []) + error_info = event.get("errorInfo", {}) + error = error_info.get("Error", "Unknown") + cause = error_info.get("Cause", "Unknown") + + # Extract the base filename from the first chunk's s3_key + # Format: temp//_chunk_1.pdf + file_basename = "" + if chunks: + first_key = chunks[0].get("s3_key", "") + parts = first_key.split("/") + if len(parts) >= 2: + file_basename = parts[1] + + if not bucket_name or not file_basename: + logger.error("Could not determine bucket or filename from event") + return {"status": "error", "message": "Missing bucket or filename"} + + # Write failure status file to result/ prefix where the frontend polls + failure_status = { + "status": "FAILED", + "error": error, + "cause": cause, + "filename": file_basename + } + + status_key = f"result/FAILED_{file_basename}.json" + s3_client.put_object( + Bucket=bucket_name, + Key=status_key, + Body=json.dumps(failure_status), + ContentType="application/json" + ) + + logger.info(f"File: {file_basename}, Status: Failed - wrote failure marker to s3://{bucket_name}/{status_key}") + + return { + "status": "FAILED", + "filename": file_basename, + "error": error, + "statusFileKey": status_key + } + + except Exception as e: + logger.error(f"Error handler failed: {e}") + return {"status": "error", "message": str(e)}