-
Notifications
You must be signed in to change notification settings - Fork 623
Expand file tree
/
Copy pathdestination_connector.py
More file actions
1987 lines (1726 loc) · 82.4 KB
/
destination_connector.py
File metadata and controls
1987 lines (1726 loc) · 82.4 KB
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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Destination Connector for Workflow Output Handling
This module provides specialized destination connector for handling workflow outputs,
extracted from the monolithic workflow_service.py to improve maintainability.
Handles:
- Filesystem destination output
- Database destination output
- API destination output
- Manual review queue output
- Output processing and validation
"""
import ast
import base64
import json
import os
import time
import uuid
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Optional
from shared.enums import DestinationConfigKey, QueueResultStatus
# Import database utils (stable path)
from shared.infrastructure.database.utils import WorkerDatabaseUtils
from shared.infrastructure.logging import WorkerLogger
from shared.infrastructure.logging.helpers import log_file_error, log_file_info
from shared.models.result_models import QueueResult
from shared.utils.api_result_cache import get_api_cache_manager
from shared.utils.manual_review_factory import (
get_manual_review_service,
has_manual_review_plugin,
)
from shared.workflow.connectors.service import WorkerConnectorService
from shared.workflow.logger_helper import WorkflowLoggerHelper
from unstract.connectors.connectorkit import Connectorkit
from unstract.connectors.exceptions import ConnectorError
from unstract.core.data_models import ConnectionType as CoreConnectionType
from unstract.core.data_models import FileHashData
from unstract.core.exceptions import FileExecutionStageException
from unstract.core.file_execution_tracker import (
FileExecutionStage,
FileExecutionStageData,
FileExecutionStageStatus,
FileExecutionStatusTracker,
)
from unstract.filesystem import FileStorageType, FileSystem
from unstract.sdk1.constants import ToolExecKey
from unstract.sdk1.tool.mime_types import EXT_MIME_MAP
from unstract.workflow_execution.constants import (
MetaDataKey,
ToolMetadataKey,
ToolOutputType,
)
from unstract.workflow_execution.execution_file_handler import (
ExecutionFileHandler,
)
if TYPE_CHECKING:
from ..api_client import InternalAPIClient
logger = WorkerLogger.get_logger(__name__)
@dataclass
class HandleOutputResult:
"""Result of handle_output method."""
output: dict[str, Any] | str | None
metadata: dict[str, Any] | None
connection_type: str
@dataclass
class ExecutionContext:
"""Execution context for destination processing."""
workflow_id: str
execution_id: str
organization_id: str
file_execution_id: str
api_client: Optional["InternalAPIClient"] = None
workflow_log: Any = None
@dataclass
class FileContext:
"""File-specific context for processing."""
file_hash: FileHashData
file_name: str
input_file_path: str
workflow: dict[str, Any]
execution_error: str | None = None
@dataclass
class HITLDecision:
"""Result of HITL routing decision."""
should_route_to_hitl: bool = False
reason: str | None = None # Human-readable reason for the decision
@dataclass
class ProcessingResult:
"""Result of destination processing."""
tool_execution_result: dict | str | None = None
metadata: dict[str, Any] | None = None
has_hitl: bool = False
hitl_reason: str | None = None # Reason why file was sent to HITL
@dataclass
class DestinationConfig:
"""Worker-compatible DestinationConfig implementation."""
connection_type: str
source_connection_type: str
settings: dict[str, Any] = None
is_api: bool = False
use_file_history: bool = True
# New connector instance fields from backend API
connector_id: str | None = None
connector_settings: dict[str, Any] = None
connector_name: str | None = None
# Manual review / HITL support
hitl_queue_name: str | None = None
hitl_packet_id: str | None = None
# Source connector configuration for reading files
source_connector_id: str | None = None
source_connector_settings: dict[str, Any] = None
file_execution_id: str | None = None
def __post_init__(self):
if self.settings is None:
self.settings = {}
if self.connector_settings is None:
self.connector_settings = {}
if self.source_connector_settings is None:
self.source_connector_settings = {}
# Determine if this is an API destination
if self.connection_type and "api" in self.connection_type.lower():
self.is_api = True
def get_core_connection_type(self) -> CoreConnectionType:
"""Convert string connection_type to CoreConnectionType enum."""
try:
# Use the enum directly for consistent mapping
connection_type_upper = self.connection_type.upper()
# Try to get enum member by value
for connection_type_enum in CoreConnectionType:
if connection_type_enum.value == connection_type_upper:
return connection_type_enum
# Fallback: handle legacy/unknown types
logger.warning(
f"Unknown connection type '{self.connection_type}', defaulting to DATABASE"
)
return CoreConnectionType.DATABASE
except Exception as e:
logger.error(
f"Failed to convert connection type '{self.connection_type}' to enum: {e}"
)
return CoreConnectionType.DATABASE
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "DestinationConfig":
"""Create DestinationConfig from dictionary data."""
connector_instance = data.get("connector_instance", {})
return cls(
connection_type=data.get("connection_type", ""),
source_connection_type=data.get("source_connection_type"),
settings=data.get("configuration", {}),
use_file_history=data.get("use_file_history", True),
connector_id=connector_instance.get("connector_id"),
connector_settings=connector_instance.get("connector_metadata", {}),
connector_name=connector_instance.get("connector_name"),
hitl_queue_name=data.get("hitl_queue_name"),
hitl_packet_id=data.get("hitl_packet_id"),
source_connector_id=data.get("source_connector_id"),
source_connector_settings=data.get("source_connector_settings", {}),
file_execution_id=data.get("file_execution_id"),
)
class WorkerDestinationConnector:
"""Worker-compatible destination connector following production patterns.
This class replicates the functionality of backend DestinationConnector
from workflow_manager/endpoint_v2/destination.py without Django dependencies.
"""
# Use CoreConnectionType directly - no need for wrapper class
def __init__(self, config: DestinationConfig, workflow_log=None):
self.config = config
self.connection_type = config.connection_type
self.is_api = config.is_api
self.use_file_history = config.use_file_history
self.settings = config.settings
self.workflow_log = workflow_log
# Initialize logger helper for safe logging operations
self.logger_helper = WorkflowLoggerHelper(workflow_log)
# Store destination connector instance details
self.connector_id = config.connector_id
self.connector_settings = config.connector_settings
self.connector_name = config.connector_name
# Store source connector instance details for file reading
self.source_connector_id = config.source_connector_id
self.source_connector_settings = config.source_connector_settings
# Manual review / HITL support
self.hitl_queue_name = config.hitl_queue_name
self.hitl_packet_id = config.hitl_packet_id
# Workflow and execution context (will be set when handling output)
self.organization_id = None
self.workflow_id = None
self.execution_id = None
self.file_execution_id = None
# Manual review service and API client (will be set when first needed)
self.manual_review_service = None
self._api_client = None
@staticmethod
def _extract_confidence_from_highlight_data(data: Any) -> float | None:
"""Extract confidence from 5th element of highlight data coordinate arrays.
Recursively searches through nested arrays/objects to find coordinate arrays
with 5 elements where the 5th element (index 4) is the confidence score.
Args:
data: Highlight data structure (can be nested arrays/dicts)
Returns:
Average confidence score if found, None otherwise
"""
if not data:
return None
confidence_values = []
def extract_from_array(arr):
if isinstance(arr, list):
for item in arr:
if isinstance(item, list):
# Check if this is a coordinate array with 5 elements
if len(item) >= 5 and isinstance(item[4], (int, float)):
confidence_values.append(float(item[4]))
else:
# Recursively check nested arrays
extract_from_array(item)
elif isinstance(item, dict):
# Recursively check objects
for val in item.values():
extract_from_array(val)
elif isinstance(arr, dict):
for val in arr.values():
extract_from_array(val)
extract_from_array(data)
# Calculate average confidence if we found any values
if confidence_values:
return sum(confidence_values) / len(confidence_values)
return None
def _prepare_result_for_rule_evaluation(
self, file_name: str, tool_execution_result: dict | str | None
) -> dict | None:
"""Prepare result for rule evaluation by wrapping in expected structure.
The rule engine expects: {"output": {...}, "metadata": {...}}
Args:
file_name: Name of the file (for logging)
tool_execution_result: Raw tool execution result
Returns:
Wrapped result dict or None if no result
"""
if not tool_execution_result:
return None
if not isinstance(tool_execution_result, dict):
logger.warning(
f"{file_name}: tool_execution_result is not a dict: {type(tool_execution_result)}"
)
return None
# Check if tool_execution_result already has the correct structure
if "output" in tool_execution_result:
# Already in correct format with metadata - use directly
return tool_execution_result
# Legacy format: wrap in expected structure
metadata = self.get_metadata()
# 3-tier fallback hierarchy for confidence:
# 1. word_confidence_data (if available)
# 2. Extract from 5th element of highlight_data
# 3. confidence_data (last resort)
highlight_data = metadata.get("highlight_data", {}) if metadata else {}
word_confidence_data = (
metadata.get("word_confidence_data", {}) if metadata else {}
)
confidence_data = metadata.get("confidence_data", {}) if metadata else {}
# If word_confidence_data is not available, try extracting from highlight_data
if not word_confidence_data and highlight_data:
extracted_confidence = self._extract_confidence_from_highlight_data(
highlight_data
)
# Use extracted confidence if available, otherwise fall back to confidence_data
if extracted_confidence is not None:
# For rule engine, we provide a single confidence score
confidence_data = {"_extracted_average": extracted_confidence}
return {
"output": tool_execution_result,
"metadata": {
"confidence_data": confidence_data,
"word_confidence_data": word_confidence_data,
"highlight_data": highlight_data,
"whisper-hash": metadata.get("whisper-hash") if metadata else None,
"extracted_text": metadata.get("extracted_text") if metadata else None,
},
}
@classmethod
def from_config(cls, workflow_log, config: DestinationConfig):
"""Create destination connector from config (matching Django backend interface)."""
return cls(config, workflow_log)
def _ensure_manual_review_service(
self, api_client: Optional["InternalAPIClient"] = None
):
"""Ensure manual review service is initialized (lazy loading)."""
if self.manual_review_service is None and api_client is not None:
self._api_client = api_client
self.manual_review_service = get_manual_review_service(
api_client, api_client.organization_id
)
return self.manual_review_service
def _get_destination_display_name(self) -> str:
"""Get human-readable destination name for logging."""
if self.connection_type == CoreConnectionType.DATABASE.value:
# Try to get database type from settings
if self.connector_name:
return f"database ({self.connector_name})"
elif self.settings and "table" in self.settings:
return f"database table '{self.settings['table']}'"
return "database"
elif self.connection_type == CoreConnectionType.FILESYSTEM.value:
if self.connector_name:
return f"filesystem ({self.connector_name})"
return "filesystem destination"
elif self.connection_type == CoreConnectionType.API.value:
if self.connector_name:
return f"API ({self.connector_name})"
return "API endpoint"
elif self.connection_type == CoreConnectionType.MANUALREVIEW.value:
return "manual review queue"
else:
return f"{self.connection_type} destination"
def _setup_execution_context(
self,
workflow_id: str,
execution_id: str,
organization_id: str,
file_execution_id: str,
api_client: Optional["InternalAPIClient"],
) -> ExecutionContext:
"""Setup and store execution context."""
# Store in instance for backward compatibility with other methods
self.workflow_id = workflow_id
self.execution_id = execution_id
self.organization_id = organization_id
self.file_execution_id = file_execution_id
return ExecutionContext(
workflow_id=workflow_id,
execution_id=execution_id,
organization_id=organization_id,
file_execution_id=file_execution_id,
api_client=api_client,
workflow_log=self.workflow_log,
)
def _setup_file_context(
self,
file_hash: FileHashData,
workflow: dict[str, Any],
execution_error: str | None,
) -> FileContext:
"""Setup file processing context."""
return FileContext(
file_hash=file_hash,
file_name=file_hash.file_name,
input_file_path=file_hash.file_path,
workflow=workflow,
execution_error=execution_error,
)
def _extract_processing_data(
self, exec_ctx: ExecutionContext, file_ctx: FileContext
) -> ProcessingResult:
"""Extract tool results and metadata for processing."""
tool_result = None
if not file_ctx.execution_error:
tool_result = self.get_tool_execution_result_from_execution_context(
workflow_id=exec_ctx.workflow_id,
execution_id=exec_ctx.execution_id,
file_execution_id=exec_ctx.file_execution_id,
organization_id=exec_ctx.organization_id,
)
metadata = self.get_metadata()
return ProcessingResult(tool_execution_result=tool_result, metadata=metadata)
def _check_and_acquire_destination_lock(
self, exec_ctx: ExecutionContext, file_ctx: FileContext
) -> bool:
"""Check if destination already processed and atomically acquire lock using Redis SET NX.
Returns:
bool: True if lock acquired successfully, False if already processed (duplicate)
This method provides duplicate prevention using Redis SET NX for atomic lock:
1. Check if DESTINATION_PROCESSING, FINALIZATION, or COMPLETED stage already exists
2. If yes, this is a duplicate attempt (e.g., from worker restart) -> skip
3. If no, atomically acquire lock using Redis SET ... NX (single atomic operation)
4. If lock acquisition succeeds, set DESTINATION_PROCESSING stage with longer TTL
5. If lock acquisition fails, another worker has the lock -> skip
"""
try:
tracker = FileExecutionStatusTracker()
# Get TTL values from environment
LOCK_TTL = int(
os.environ.get("DESTINATION_PROCESSING_LOCK_TTL_IN_SECOND", 120)
)
STAGE_TTL = int(
os.environ.get("DESTINATION_PROCESSING_STAGE_TTL_IN_SECOND", 600)
)
# Get lock key for atomic operations
lock_key = tracker.get_destination_lock_key(
exec_ctx.execution_id, exec_ctx.file_execution_id
)
lock_token = str(uuid.uuid4()) # Unique token for debugging
# STEP 1: Try to acquire lock atomically (SOURCE OF TRUTH)
# This is atomic - if lock exists, another worker is processing
logger.info(
f"Attempting to acquire destination lock for file '{file_ctx.file_name}' "
f"(lock_key={lock_key}, lock_ttl={LOCK_TTL}s, stage_ttl={STAGE_TTL}s)"
)
lock_acquired = tracker.redis_client.set(
lock_key, lock_token, nx=True, ex=LOCK_TTL
)
# STEP 2: If lock acquisition failed, another worker is processing - WAIT
if not lock_acquired:
logger.info(
f"Lock already held by another worker for file '{file_ctx.file_name}'. "
f"Waiting for lock release to prevent premature chord cleanup (max {LOCK_TTL}s)..."
)
wait_start = time.time()
max_wait = min(LOCK_TTL, 120) # Wait up to lock TTL or 120s
# Poll until lock released or timeout
while time.time() - wait_start < max_wait:
# Check if lock released
if not tracker.redis_client.exists(lock_key):
wait_duration = time.time() - wait_start
# Lock released BEFORE timeout → Other worker finished (success or error) → Skip
logger.info(
f"Lock released for '{file_ctx.file_name}' after {wait_duration:.1f}s - "
f"other worker completed processing. Skipping as duplicate."
)
return False # Skip immediately
time.sleep(2) # Poll every 2 seconds
# STEP 3: After wait, try to acquire lock again
lock_acquired = tracker.redis_client.set(
lock_key, lock_token, nx=True, ex=LOCK_TTL
)
if not lock_acquired:
# Still can't acquire lock (timeout or another worker grabbed it)
if tracker.redis_client.exists(lock_key):
logger.warning(
f"Lock still held after {max_wait}s timeout for '{file_ctx.file_name}'. "
f"Another worker may have acquired it. Skipping as duplicate."
)
else:
logger.warning(
f"Failed to acquire lock for '{file_ctx.file_name}' after wait. "
f"Another worker may have grabbed it first. Skipping as duplicate."
)
return False # Skip
# Lock acquired successfully - now set DESTINATION_PROCESSING stage
logger.info(
f"Lock acquired successfully for file '{file_ctx.file_name}' (token={lock_token})"
)
try:
tracker.update_stage_status(
exec_ctx.execution_id,
exec_ctx.file_execution_id,
FileExecutionStageData(
stage=FileExecutionStage.DESTINATION_PROCESSING,
status=FileExecutionStageStatus.IN_PROGRESS,
),
ttl_in_second=STAGE_TTL, # Use longer TTL for stage tracker
)
logger.info(
f"Successfully set DESTINATION_PROCESSING stage for file '{file_ctx.file_name}' "
f"with stage TTL {STAGE_TTL}s"
)
return True # Lock acquired and stage set successfully
except FileExecutionStageException:
# Stage transition failed (shouldn't happen after lock acquired, but handle it)
logger.exception(
f"Failed to set DESTINATION_PROCESSING stage after lock acquisition "
f"for file '{file_ctx.file_name}'. "
f"Releasing lock."
)
# Release the lock since we failed to set the stage
tracker.redis_client.delete(lock_key)
return False
except Exception as e:
# If Redis fails or other unexpected error, log but allow processing to continue
# This ensures graceful degradation if tracking system is unavailable
logger.exception(
f"Failed to check/acquire destination lock for file '{file_ctx.file_name}': {e}. "
f"Allowing processing to continue (graceful degradation)."
)
return True # Allow processing on infrastructure failure
def _check_and_handle_hitl(
self,
exec_ctx: ExecutionContext,
file_ctx: FileContext,
result: ProcessingResult,
) -> HITLDecision:
"""Check HITL requirements and push to queue if needed.
Returns:
HITLDecision: Decision object with should_route_to_hitl flag and reason
"""
hitl_decision = self._should_handle_hitl(
file_name=file_ctx.file_name,
file_hash=file_ctx.file_hash,
workflow=file_ctx.workflow,
api_client=exec_ctx.api_client,
tool_execution_result=result.tool_execution_result,
error=file_ctx.execution_error,
)
# Update result with HITL metadata
result.has_hitl = hitl_decision.should_route_to_hitl
result.hitl_reason = hitl_decision.reason
if hitl_decision.should_route_to_hitl:
self._push_data_to_queue(
file_name=file_ctx.file_name,
workflow=file_ctx.workflow,
input_file_path=file_ctx.input_file_path,
file_execution_id=exec_ctx.file_execution_id,
tool_execution_result=result.tool_execution_result,
api_client=exec_ctx.api_client,
hitl_reason=hitl_decision.reason,
)
return hitl_decision
def _process_destination(
self,
exec_ctx: ExecutionContext,
file_ctx: FileContext,
result: ProcessingResult,
):
"""Route to appropriate destination handler."""
handlers = {
CoreConnectionType.API.value: self._handle_api_destination,
CoreConnectionType.FILESYSTEM.value: self._handle_filesystem_destination,
CoreConnectionType.DATABASE.value: self._handle_database_destination,
CoreConnectionType.MANUALREVIEW.value: self._handle_manual_review_destination,
}
handler = handlers.get(self.connection_type)
if handler:
handler(exec_ctx, file_ctx, result)
else:
logger.warning(f"Unknown destination connection type: {self.connection_type}")
def _handle_api_destination(
self,
exec_ctx: ExecutionContext,
file_ctx: FileContext,
result: ProcessingResult,
):
"""Handle API destination processing."""
log_file_info(
exec_ctx.workflow_log,
exec_ctx.file_execution_id,
f"🔌 File '{file_ctx.file_name}' marked for API processing - preparing response",
)
# Enrich metadata with usage and pages processed data
api_metadata = self.get_combined_metadata(exec_ctx.api_client, result.metadata)
# Add HITL info only if plugin is available (cloud feature)
if has_manual_review_plugin():
api_metadata["hitl"] = {
"file_sent_to_hitl": result.has_hitl,
"reason": result.hitl_reason,
}
self.cache_api_result(
api_client=exec_ctx.api_client,
file_hash=file_ctx.file_hash,
workflow_id=exec_ctx.workflow_id,
execution_id=exec_ctx.execution_id,
result=result.tool_execution_result if not result.has_hitl else None,
file_execution_id=exec_ctx.file_execution_id,
organization_id=exec_ctx.organization_id,
error=file_ctx.execution_error,
metadata=api_metadata,
)
def _handle_filesystem_destination(
self,
exec_ctx: ExecutionContext,
file_ctx: FileContext,
result: ProcessingResult,
):
"""Handle filesystem destination processing."""
if not result.has_hitl:
if not result.tool_execution_result and not file_ctx.execution_error:
error_msg = (
f"No tool execution result for file '{file_ctx.file_name}' "
f"- filesystem copy skipped"
)
logger.error(error_msg)
log_file_error(
exec_ctx.workflow_log,
exec_ctx.file_execution_id,
f"❌ {error_msg}",
)
raise RuntimeError(error_msg)
log_file_info(
exec_ctx.workflow_log,
exec_ctx.file_execution_id,
f"📤 File '{file_ctx.file_name}' marked for FILESYSTEM processing - copying to destination",
)
self.copy_output_to_output_directory(
file_ctx.input_file_path,
exec_ctx.file_execution_id,
exec_ctx.api_client,
)
else:
logger.info(
f"File '{file_ctx.file_name}' sent to HITL queue - FILESYSTEM processing will be handled after review"
)
def _handle_database_destination(
self,
exec_ctx: ExecutionContext,
file_ctx: FileContext,
result: ProcessingResult,
):
"""Handle database destination processing."""
if not result.has_hitl:
log_file_info(
exec_ctx.workflow_log,
exec_ctx.file_execution_id,
f"📤 File '{file_ctx.file_name}' marked for DATABASE processing - preparing to insert data",
)
if result.tool_execution_result or file_ctx.execution_error:
self.insert_into_db(
file_ctx.input_file_path,
result.tool_execution_result,
result.metadata,
exec_ctx.file_execution_id,
error_message=file_ctx.execution_error,
api_client=exec_ctx.api_client,
)
else:
error_msg = (
f"No tool execution result for file '{file_ctx.file_name}' "
f"- database insertion skipped"
)
logger.error(error_msg)
log_file_error(
exec_ctx.workflow_log,
exec_ctx.file_execution_id,
f"❌ {error_msg}",
)
raise RuntimeError(error_msg)
else:
logger.info(
f"File '{file_ctx.file_name}' sent to HITL queue - DATABASE processing will be handled after review"
)
def _handle_manual_review_destination(
self,
exec_ctx: ExecutionContext,
file_ctx: FileContext,
result: ProcessingResult,
):
"""Handle manual review destination processing."""
log_file_info(
exec_ctx.workflow_log,
exec_ctx.file_execution_id,
f"🔄 File '{file_ctx.file_name}' explicitly configured for MANUAL REVIEW - sending to queue",
)
if not result.has_hitl:
self._push_data_to_queue(
file_name=file_ctx.file_name,
workflow=file_ctx.workflow,
input_file_path=file_ctx.input_file_path,
file_execution_id=exec_ctx.file_execution_id,
tool_execution_result=result.tool_execution_result,
api_client=exec_ctx.api_client,
hitl_reason="Destination configured for manual review",
)
def _handle_destination_error(
self, exec_ctx: ExecutionContext, file_ctx: FileContext, error: Exception
):
"""Handle destination processing errors."""
logger.error(f"Destination handle_output failed: {str(error)}")
log_file_error(
exec_ctx.workflow_log,
exec_ctx.file_execution_id,
f"❌ File '{file_ctx.file_name}' failed to send to destination: {str(error)}",
)
def _log_processing_success(
self, exec_ctx: ExecutionContext, file_ctx: FileContext, has_hitl: bool
):
"""Log successful processing."""
if has_hitl:
destination_name = "HITL/MANUAL REVIEW"
else:
destination_name = self._get_destination_display_name()
log_file_info(
exec_ctx.workflow_log,
exec_ctx.file_execution_id,
f"✅ File '{file_ctx.file_name}' successfully sent to {destination_name}",
)
def cache_api_result(
self,
file_hash: FileHashData,
workflow_id: str,
execution_id: str,
file_execution_id: str,
organization_id: str,
api_client: Any | None,
# file_history: dict[str, Any] | None,
result: dict[str, Any] | None,
error: str | None = None,
metadata: dict[str, Any] | None = None,
) -> bool:
"""Cache API result using APIResultCacheManager."""
try:
# Calculate accurate elapsed time from workflow start time
if metadata and MetaDataKey.WORKFLOW_START_TIME in metadata:
workflow_start_time = metadata[MetaDataKey.WORKFLOW_START_TIME]
current_time = time.time()
actual_elapsed_time = current_time - workflow_start_time
# Update total_elapsed_time with accurate measurement
metadata[MetaDataKey.TOTAL_ELAPSED_TIME] = actual_elapsed_time
logger.info(
f"TIMING: Calculated accurate elapsed time for API caching: {actual_elapsed_time:.3f}s "
f"(from workflow start: {workflow_start_time:.6f} to now: {current_time:.6f})"
)
# Use APIResultCacheManager for consistent caching behavior
api_cache_manager = get_api_cache_manager()
success = api_cache_manager.cache_api_result_direct(
file_name=file_hash.file_name,
file_execution_id=file_execution_id,
workflow_id=workflow_id,
execution_id=execution_id,
result=result,
error=error,
organization_id=organization_id,
metadata=metadata,
)
if success:
logger.info(
f"Successfully cached API result for execution {execution_id}"
)
else:
logger.warning(f"Failed to cache API result for execution {execution_id}")
return success
except Exception as e:
logger.error(
f"Failed to cache API result for execution {execution_id}: {str(e)}"
)
# Return False but don't re-raise - caching failures shouldn't stop execution
raise
def handle_output(
self,
is_success: bool,
file_hash: FileHashData,
# file_history: dict[str, Any] | None,
workflow: dict[str, Any],
file_execution_id: str = None,
api_client: Optional["InternalAPIClient"] = None,
workflow_id: str = None,
execution_id: str = None,
organization_id: str = None,
execution_error: str = None,
) -> HandleOutputResult | None:
"""Handle the output based on the connection type.
This refactored version uses clean architecture with context objects
and single-responsibility methods for better maintainability.
"""
# Setup contexts
exec_ctx = self._setup_execution_context(
workflow_id, execution_id, organization_id, file_execution_id, api_client
)
file_ctx = self._setup_file_context(file_hash, workflow, execution_error)
# Log if HITL queue is configured (reduced debug logging)
if self.hitl_queue_name:
logger.debug(f"HITL queue configured: {self.hitl_queue_name}")
# Check if destination already processed and atomically acquire lock FIRST
# This prevents duplicate insertions during warm shutdown scenarios
# IMPORTANT: Check lock BEFORE extracting data to avoid unnecessary work
lock_acquired = self._check_and_acquire_destination_lock(exec_ctx, file_ctx)
if not lock_acquired:
# Duplicate detected or another worker has the lock - abort ALL processing
logger.info(
f"Duplicate detected for file '{file_ctx.file_name}' - "
f"aborting ALL processing (lock not acquired, already processed or being processed by another worker)"
)
# Return None to signal to caller that this is a duplicate skip
# Caller should not create file history, update stages, or clean up locks
return None
# Only extract data if lock was acquired (not a duplicate)
result = self._extract_processing_data(exec_ctx, file_ctx)
# Check and handle HITL if needed (this updates result.has_hitl and result.hitl_reason)
self._check_and_handle_hitl(exec_ctx, file_ctx, result)
# Process through appropriate destination
try:
self._process_destination(exec_ctx, file_ctx, result)
except Exception as e:
self._handle_destination_error(exec_ctx, file_ctx, e)
raise
finally:
# Release lock after destination processing completes
# Critical section (stage set + data extraction + destination write) is done
# File history and stage updates don't need the lock (protected by stage checks)
try:
tracker = FileExecutionStatusTracker()
lock_key = tracker.get_destination_lock_key(
exec_ctx.execution_id, exec_ctx.file_execution_id
)
tracker.redis_client.delete(lock_key)
logger.info(
f"Released destination lock for '{file_ctx.file_name}' "
f"after destination processing (lock_key={lock_key})"
)
except Exception as lock_error:
logger.warning(
f"Failed to release destination lock for '{file_ctx.file_name}': {lock_error}"
)
# Log success
self._log_processing_success(exec_ctx, file_ctx, result.has_hitl)
return HandleOutputResult(
output=result.tool_execution_result,
metadata=result.metadata,
connection_type=self.connection_type,
)
def get_combined_metadata(
self, api_client: "InternalAPIClient", metadata: dict[str, Any] = None
) -> dict[str, Any]:
"""Get combined workflow and usage metadata.
Returns:
dict[str, Any]: Combined metadata including workflow and usage data.
"""
if metadata is None:
metadata = {}
if not api_client:
return metadata
file_execution_id = self.file_execution_id
usage_metadata = api_client.get_aggregated_token_count(file_execution_id)
if usage_metadata:
metadata["usage"] = usage_metadata.to_dict()
if file_execution_id:
metadata["total_pages_processed"] = api_client.get_aggregated_pages_processed(
file_execution_id
)
return metadata
def insert_into_db(
self,
input_file_path: str,
tool_execution_result: str = None,
metadata: dict[str, Any] = None,
file_execution_id: str = None,
error_message: str = None,
api_client: "InternalAPIClient" = None,
) -> None:
"""Insert data into the database (following production pattern)."""
# If no data and no error, don't execute CREATE or INSERT query
if not (tool_execution_result or error_message):
raise ValueError("No tool_execution_result or error_message provided")
if error_message:
logger.info(
f"Proceeding with error record insertion for {input_file_path}: {error_message}"
)
# Store file_execution_id for logging
if file_execution_id:
self.current_file_execution_id = file_execution_id
# Extract connector instance details from instance variables (now properly set)
connector_id = self.connector_id
connector_settings = self.connector_settings
logger.info(f"Database destination - Connector ID: {connector_id}")
logger.info(
f"Database destination - Connector settings available: {bool(connector_settings)}"
)
logger.info(
f"Database destination - Settings keys: {list(self.settings.keys()) if self.settings else 'None'}"
)
if not connector_id:
raise ValueError("No connector_id provided in destination configuration")
if not connector_settings:
raise ValueError(
"No connector_settings provided in destination configuration"
)
db_class = WorkerDatabaseUtils.get_db_class(
connector_id=connector_id,
connector_settings=connector_settings,
)
# Get combined metadata including usage data
metadata = self.get_combined_metadata(api_client, metadata)
logger.info(f"Database destination - Metadata: {metadata}")
# Get table configuration from destination settings (table-specific config)
table_name = str(self.settings.get("table", "unstract_results"))
include_agent = bool(self.settings.get("includeAgent", False))
include_timestamp = bool(self.settings.get("includeTimestamp", False))
agent_name = str(self.settings.get("agentName", "UNSTRACT_DBWRITER"))
column_mode = str(
self.settings.get("columnMode", "WRITE_JSON_TO_A_SINGLE_COLUMN")
)
single_column_name = str(self.settings.get("singleColumnName", "data"))
file_path_name = str(self.settings.get("filePath", "file_path"))