Skip to content

API Reference

This page provides comprehensive API documentation for all ApiLinker classes and modules.

Core Classes

ApiLinker

Main orchestrator class for API integration workflows.

apilinker.ApiLinker

Main class for connecting, mapping and transferring data between APIs.

This class orchestrates the entire process of: 1. Connecting to source and target APIs 2. Fetching data from the source 3. Mapping fields according to configuration 4. Transforming data as needed 5. Sending data to the target 6. Scheduling recurring operations

Parameters:

Name Type Description Default
config_path Optional[str]

Path to YAML/JSON configuration file

None
source_config Optional[Dict[str, Any]]

Direct source configuration dictionary

None
target_config Optional[Dict[str, Any]]

Direct target configuration dictionary

None
mapping_config Optional[Dict[str, Any]]

Direct mapping configuration dictionary

None
schedule_config Optional[Dict[str, Any]]

Direct scheduling configuration dictionary

None
log_level str

Logging level (DEBUG, INFO, WARNING, ERROR)

'INFO'
log_file Optional[str]

Path to log file

None
Source code in apilinker/api_linker.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
class ApiLinker:
    """
    Main class for connecting, mapping and transferring data between APIs.

    This class orchestrates the entire process of:
    1. Connecting to source and target APIs
    2. Fetching data from the source
    3. Mapping fields according to configuration
    4. Transforming data as needed
    5. Sending data to the target
    6. Scheduling recurring operations

    Args:
        config_path: Path to YAML/JSON configuration file
        source_config: Direct source configuration dictionary
        target_config: Direct target configuration dictionary
        mapping_config: Direct mapping configuration dictionary
        schedule_config: Direct scheduling configuration dictionary
        log_level: Logging level (DEBUG, INFO, WARNING, ERROR)
        log_file: Path to log file
    """

    def __init__(
        self,
        config_path: Optional[str] = None,
        source_config: Optional[Dict[str, Any]] = None,
        target_config: Optional[Dict[str, Any]] = None,
        mapping_config: Optional[Dict[str, Any]] = None,
        schedule_config: Optional[Dict[str, Any]] = None,
        error_handling_config: Optional[Dict[str, Any]] = None,
        security_config: Optional[Dict[str, Any]] = None,
        validation_config: Optional[Dict[str, Any]] = None,
        observability_config: Optional[Dict[str, Any]] = None,
        secret_manager_config: Optional[Dict[str, Any]] = None,
        log_level: str = "INFO",
        log_file: Optional[str] = None,
    ) -> None:
        # Initialize logger
        self.logger = setup_logger(log_level, log_file)
        self.logger.info("Initializing ApiLinker")

        # Initialize components
        self.source: Optional[ApiConnector] = None
        self.target: Optional[ApiConnector] = None
        self.sources: Dict[str, ApiConnector] = {}
        self.mapper = FieldMapper()
        self.multi_source_aggregator = MultiSourceAggregator(self.mapper)
        self.scheduler = Scheduler()
        self.validation_config = validation_config or {"strict_mode": False}
        self.provenance = ProvenanceRecorder()
        self.deduplicator = InMemoryDeduplicator()
        self.state_store: Optional[StateStore] = None

        # Initialize observability
        self.telemetry = self._initialize_observability(observability_config)

        # Initialize secret management
        self.secret_manager = self._initialize_secret_manager(secret_manager_config)

        # Initialize security system
        self.security_manager = self._initialize_security(security_config)

        # Initialize auth manager and integrate with security
        self.auth_manager = AuthManager()
        integrate_security_with_auth_manager(self.security_manager, self.auth_manager)

        # Initialize error handling system
        self.dlq, self.error_recovery_manager, self.error_analytics = (
            create_error_handler()
        )

        # Load configuration if provided
        if config_path:
            self.load_config(config_path)
        else:
            # Set up direct configurations if provided
            if source_config:
                self.add_source(**source_config)
            if target_config:
                self.add_target(**target_config)
            if mapping_config:
                self.add_mapping(**mapping_config)
            if schedule_config:
                self.add_schedule(**schedule_config)
            if error_handling_config:
                self._configure_error_handling(error_handling_config)
            if security_config:
                self._configure_security(security_config)

    def load_config(self, config_path: str) -> None:
        """
        Load configuration from a YAML or JSON file.

        Args:
            config_path: Path to the configuration file
        """
        self.logger.info(f"Loading configuration from {config_path}")

        # Resolve environment variables in config path
        config_path = os.path.expandvars(config_path)

        if not os.path.exists(config_path):
            raise FileNotFoundError(f"Configuration file not found: {config_path}")

        with open(config_path, "r") as f:
            config = yaml.safe_load(f)

        # Set up components from config
        if "source" in config:
            self.add_source(**config["source"])

        if "sources" in config:
            sources_config = config["sources"]
            if isinstance(sources_config, dict):
                for source_name, source_config in sources_config.items():
                    self.add_named_source(source_name, **source_config)
            else:
                for source_config in sources_config:
                    named_source_config = dict(source_config)
                    source_name = named_source_config.pop("name")
                    self.add_named_source(source_name, **named_source_config)

        if "target" in config:
            self.add_target(**config["target"])

        if "mapping" in config:
            if isinstance(config["mapping"], list):
                for mapping in config["mapping"]:
                    self.add_mapping(**mapping)
            else:
                self.add_mapping(**config["mapping"])

        if "schedule" in config:
            self.add_schedule(**config["schedule"])

        # Configure error handling if specified
        if "error_handling" in config:
            self._configure_error_handling(config["error_handling"])

        # Configure security if specified
        if "security" in config:
            self._configure_security(config["security"])

        # Configure secret management if specified
        if "secrets" in config:
            self.secret_manager = self._initialize_secret_manager(config["secrets"])

        # Validation configuration
        if "validation" in config:
            self.validation_config = config["validation"]

        if "logging" in config:
            log_config = config["logging"]
            log_level = log_config.get("level", "INFO")
            log_file = log_config.get("file")
            self.logger = setup_logger(log_level, log_file)

        # Provenance options
        if "provenance" in config:
            prov_cfg = config["provenance"]
            output_dir = prov_cfg.get("output_dir")
            jsonl_log = prov_cfg.get("jsonl_log")
            self.provenance = ProvenanceRecorder(
                output_dir=output_dir, jsonl_log_path=jsonl_log
            )

        # Idempotency
        if "idempotency" in config:
            self.idempotency_config = config["idempotency"]
        else:
            self.idempotency_config = {"enabled": False, "salt": ""}

        # State store
        if "state" in config:
            st_cfg = config["state"]
            st_type = st_cfg.get("type", "file")
            if st_type == "file":
                path = st_cfg.get("path", ".apilinker/state.json")
                default_last_sync = st_cfg.get("default_last_sync")
                self.state_store = FileStateStore(
                    path, default_last_sync=default_last_sync
                )
            elif st_type == "sqlite":
                path = st_cfg.get("path", ".apilinker/state.db")
                default_last_sync = st_cfg.get("default_last_sync")
                self.state_store = SQLiteStateStore(
                    path, default_last_sync=default_last_sync
                )

    def _create_connector(
        self,
        type: str,
        base_url: str,
        auth: Optional[Dict[str, Any]] = None,
        endpoints: Optional[Dict[str, Any]] = None,
        **kwargs: Any,
    ) -> ApiConnector:
        """Create a connector while resolving auth secrets consistently."""
        if auth:
            auth = self._resolve_auth_secrets(auth)
            auth_config = self.auth_manager.configure_auth(auth)
        else:
            auth_config = None

        return ApiConnector(
            connector_type=type,
            base_url=base_url,
            auth_config=auth_config,
            endpoints=endpoints or {},
            **kwargs,
        )

    def add_source(
        self,
        type: str,
        base_url: str,
        auth: Optional[Dict[str, Any]] = None,
        endpoints: Optional[Dict[str, Any]] = None,
        **kwargs: Any,
    ) -> None:
        """
        Add a source API connector.

        Args:
            type: Type of API connector (rest, graphql, etc.)
            base_url: Base URL of the API
            auth: Authentication configuration
            endpoints: Configured endpoints
            **kwargs: Additional configuration parameters
        """
        self.logger.info(f"Adding source connector: {type} for {base_url}")
        self.source = self._create_connector(type, base_url, auth, endpoints, **kwargs)
        self.sources["source"] = self.source

    def add_named_source(
        self,
        name: str,
        type: str,
        base_url: str,
        auth: Optional[Dict[str, Any]] = None,
        endpoints: Optional[Dict[str, Any]] = None,
        **kwargs: Any,
    ) -> None:
        """
        Register an additional named source connector for aggregation workflows.

        Args:
            name: Logical source name used in aggregation requests
            type: Type of API connector (rest, graphql, etc.)
            base_url: Base URL of the API
            auth: Authentication configuration
            endpoints: Configured endpoints
            **kwargs: Additional connector configuration
        """
        self.logger.info(f"Adding named source connector '{name}': {type} for {base_url}")
        connector = self._create_connector(type, base_url, auth, endpoints, **kwargs)
        self.sources[name] = connector

        if name == "source":
            self.source = connector

    def add_target(
        self,
        type: str,
        base_url: str,
        auth: Optional[Dict[str, Any]] = None,
        endpoints: Optional[Dict[str, Any]] = None,
        **kwargs: Any,
    ) -> None:
        """
        Add a target API connector.

        Args:
            type: Type of API connector (rest, graphql, etc.)
            base_url: Base URL of the API
            auth: Authentication configuration
            endpoints: Configured endpoints
            **kwargs: Additional configuration parameters
        """
        self.logger.info(f"Adding target connector: {type} for {base_url}")
        self.target = self._create_connector(type, base_url, auth, endpoints, **kwargs)

    def add_mapping(
        self, source: str, target: str, fields: List[Dict[str, Any]]
    ) -> None:
        """
        Add a field mapping between source and target endpoints.

        Args:
            source: Source endpoint name
            target: Target endpoint name
            fields: List of field mappings
        """
        self.logger.info(
            f"Adding mapping from {source} to {target} with {len(fields)} fields"
        )
        self.mapper.add_mapping(source, target, fields)

    def add_schedule(self, type: str, **kwargs: Any) -> None:
        """
        Add a schedule for recurring syncs.

        Args:
            type: Type of schedule (interval, cron)
            **kwargs: Schedule-specific parameters
        """
        self.logger.info(f"Adding schedule: {type}")
        self.scheduler.add_schedule(type, **kwargs)

    def _initialize_security(
        self, config: Optional[Dict[str, Any]] = None
    ) -> SecurityManager:
        """
        Initialize the security system based on provided configuration.

        Args:
            config: Security configuration dictionary

        Returns:
            SecurityManager instance
        """
        if not config:
            config = {}

        # Extract security configuration
        master_password = config.get("master_password")
        storage_path = config.get("credential_storage_path")
        encryption_level = config.get("encryption_level", "none")
        encryption_key = config.get("encryption_key")
        enable_access_control = config.get("enable_access_control", False)

        # Initialize security manager
        security_manager = SecurityManager(
            master_password=master_password,
            storage_path=storage_path,
            encryption_level=encryption_level,
            encryption_key=encryption_key,
            enable_access_control=enable_access_control,
        )

        # Set up initial users if access control is enabled
        if enable_access_control and "users" in config:
            for user_config in config["users"]:
                username = user_config.get("username")
                role = user_config.get("role", "viewer")
                api_key = user_config.get("api_key")

                if username:
                    security_manager.add_user(username, role, api_key)

        return security_manager

    def _initialize_observability(
        self, config: Optional[Dict[str, Any]] = None
    ) -> TelemetryManager:
        """
        Initialize the observability system based on provided configuration.

        Args:
            config: Observability configuration dictionary

        Returns:
            TelemetryManager instance
        """
        if not config:
            config = {}

        # Create observability configuration
        obs_config = ObservabilityConfig(
            enabled=config.get("enabled", True),
            service_name=config.get("service_name", "apilinker"),
            enable_tracing=config.get("enable_tracing", True),
            enable_metrics=config.get("enable_metrics", True),
            export_to_console=config.get("export_to_console", False),
            export_to_prometheus=config.get("export_to_prometheus", False),
            prometheus_host=config.get("prometheus_host", "0.0.0.0"),
            prometheus_port=config.get("prometheus_port", 9090),
        )

        return TelemetryManager(obs_config)

    def _initialize_secret_manager(
        self, config: Optional[Dict[str, Any]] = None
    ) -> Optional[SecretManager]:
        """
        Initialize the secret management system based on provided configuration.

        Args:
            config: Secret manager configuration dictionary

        Returns:
            SecretManager instance or None if not configured
        """
        if not config:
            return None

        try:
            # Create secret manager configuration
            from apilinker.core.secrets import SecretProvider, RotationStrategy

            provider_str = config.get("provider", "env")
            provider = SecretProvider(provider_str)

            rotation_str = config.get("rotation_strategy", "manual")
            rotation_strategy = RotationStrategy(rotation_str)

            secret_config = SecretManagerConfig(
                provider=provider,
                vault_config=config.get("vault"),
                aws_config=config.get("aws"),
                azure_config=config.get("azure"),
                gcp_config=config.get("gcp"),
                rotation_strategy=rotation_strategy,
                rotation_interval_days=config.get("rotation_interval_days", 90),
                cache_ttl_seconds=config.get("cache_ttl_seconds", 300),
                enable_least_privilege=config.get("enable_least_privilege", True),
            )

            self.logger.info(f"Initialized secret manager with provider: {provider}")
            return SecretManager(secret_config)

        except Exception as e:
            self.logger.warning(f"Failed to initialize secret manager: {e}")
            return None

    def _resolve_secret(self, value: Any) -> Any:
        """
        Resolve a secret reference to its actual value.

        Secret references can be specified as:
        - String starting with "secret://" (e.g., "secret://api-key")
        - Dict with "secret" key (e.g., {"secret": "api-key"})

        Args:
            value: Value that may contain a secret reference

        Returns:
            Resolved secret value or original value if not a secret reference
        """
        if not self.secret_manager:
            return value

        # Handle string secret references
        if isinstance(value, str) and value.startswith("secret://"):
            secret_name = value[9:]  # Remove "secret://" prefix
            try:
                secret_value = self.secret_manager.get_secret(secret_name)
                self.logger.debug(f"Retrieved secret: {secret_name}")
                return secret_value
            except (SecretNotFoundError, SecretAccessError) as e:
                self.logger.error(f"Failed to retrieve secret '{secret_name}': {e}")
                raise

        # Handle dict secret references
        if isinstance(value, dict) and "secret" in value:
            secret_name = value["secret"]
            version = value.get("version")
            try:
                secret_value = self.secret_manager.get_secret(secret_name, version)
                self.logger.debug(f"Retrieved secret: {secret_name}")
                return secret_value
            except (SecretNotFoundError, SecretAccessError) as e:
                self.logger.error(f"Failed to retrieve secret '{secret_name}': {e}")
                raise

        return value

    def _resolve_auth_secrets(self, auth_config: Dict[str, Any]) -> Dict[str, Any]:
        """
        Recursively resolve secret references in authentication configuration.

        Args:
            auth_config: Authentication configuration that may contain secret references

        Returns:
            Authentication configuration with resolved secrets
        """
        if not self.secret_manager:
            return auth_config

        resolved_config = {}
        for key, value in auth_config.items():
            if isinstance(value, dict):
                # Recursively resolve nested dicts
                resolved_config[key] = self._resolve_auth_secrets(value)
            elif isinstance(value, list):
                # Resolve each item in list
                resolved_config[key] = [  # type: ignore[assignment]
                    (
                        self._resolve_secret(item)
                        if isinstance(item, (str, dict))
                        else item
                    )
                    for item in value
                ]
            else:
                # Resolve individual value
                resolved_config[key] = self._resolve_secret(value)

        return resolved_config

    def _configure_security(self, config: Dict[str, Any]) -> None:
        """
        Configure security features based on provided configuration.

        Args:
            config: Security configuration dictionary
        """
        self.logger.info("Configuring security features")

        # Update encryption level if specified
        if "encryption_level" in config:
            encryption_level = config["encryption_level"]
            try:
                if isinstance(encryption_level, str):
                    encryption_level = EncryptionLevel[encryption_level.upper()]
                self.security_manager.request_encryption.encryption_level = (
                    encryption_level
                )
                self.logger.debug(f"Updated encryption level to {encryption_level}")
            except (KeyError, ValueError):
                self.logger.warning(f"Invalid encryption level: {encryption_level}")

        # Add users if specified and access control is enabled
        if self.security_manager.enable_access_control and "users" in config:
            for user_config in config["users"]:
                username = user_config.get("username")
                role = user_config.get("role", "viewer")
                api_key = user_config.get("api_key")

                if username:
                    self.security_manager.add_user(username, role, api_key)
                    self.logger.debug(f"Added user {username} with role {role}")

    def _configure_error_handling(self, config: Dict[str, Any]) -> None:
        """
        Configure the error handling system based on provided configuration.

        Args:
            config: Error handling configuration dictionary
        """
        self.logger.info("Configuring error handling system")

        # Configure circuit breakers
        if "circuit_breakers" in config:
            for cb_name, cb_config in config["circuit_breakers"].items():
                failure_threshold = cb_config.get("failure_threshold", 5)
                reset_timeout = cb_config.get("reset_timeout_seconds", 60)
                half_open_max_calls = cb_config.get("half_open_max_calls", 1)

                # Create and register circuit breaker
                circuit: CircuitBreaker = CircuitBreaker(
                    name=cb_name,
                    failure_threshold=failure_threshold,
                    reset_timeout_seconds=reset_timeout,
                    half_open_max_calls=half_open_max_calls,
                )

                self.error_recovery_manager.circuit_breakers[cb_name] = circuit
                self.logger.debug(f"Configured circuit breaker: {cb_name}")

        # Configure recovery strategies
        if "recovery_strategies" in config:
            for category_name, strategies in config["recovery_strategies"].items():
                try:
                    error_category = ErrorCategory[category_name.upper()]
                    strategy_list = [
                        RecoveryStrategy[str(s).upper()] for s in strategies
                    ]

                    self.error_recovery_manager.set_strategy(
                        error_category, strategy_list
                    )
                    self.logger.debug(
                        f"Configured recovery strategies for {category_name}: {strategies}"
                    )

                except (KeyError, ValueError) as e:
                    self.logger.warning(
                        f"Invalid recovery strategy configuration: {str(e)}"
                    )

        # Configure DLQ
        if "dlq" in config:
            dlq_dir = config["dlq"].get("directory")
            if dlq_dir:
                self.dlq = DeadLetterQueue(dlq_dir)
                self.error_recovery_manager.dlq = self.dlq
                self.logger.info(f"Configured Dead Letter Queue at {dlq_dir}")

    def get_error_analytics(self) -> Dict[str, Any]:
        """
        Get error analytics summary.

        Returns:
            Dictionary with error statistics
        """
        return self.error_analytics.get_summary()

    def add_user(
        self, username: str, role: str, api_key: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        Add a user to the system with specified role.

        Args:
            username: Username to identify the user
            role: Access role (admin, operator, viewer, developer)
            api_key: Optional API key for authentication

        Returns:
            User data including generated API key if not provided
        """
        if not self.security_manager.enable_access_control:
            raise ValueError(
                "Access control is not enabled. Enable it in the security configuration."
            )

        return self.security_manager.add_user(username, role, api_key)

    def list_users(self) -> List[Dict[str, Any]]:
        """
        List all users in the system.

        Returns:
            List of user data dictionaries
        """
        if not self.security_manager.enable_access_control:
            raise ValueError(
                "Access control is not enabled. Enable it in the security configuration."
            )

        users = []
        for username in self.security_manager.access_control.users:
            user_data = self.security_manager.access_control.get_user(username)
            # Remove sensitive data like API key
            if "api_key" in user_data:
                user_data["api_key"] = "*" * 8  # Mask API key
            users.append(user_data)

        return users

    def store_credential(self, name: str, credential_data: Dict[str, Any]) -> bool:
        """
        Store API credentials securely.

        Args:
            name: Name to identify the credential
            credential_data: Credential data to store

        Returns:
            True if successful, False otherwise
        """
        return self.security_manager.store_credential(name, credential_data)

    def get_credential(self, name: str) -> Optional[Dict[str, Any]]:
        """
        Get stored API credentials.

        Args:
            name: Name of the credential

        Returns:
            Credential data if found, None otherwise
        """
        return self.security_manager.get_credential(name)

    def list_credentials(self) -> List[str]:
        """
        List available credential names.

        Returns:
            List of credential names
        """
        return self.security_manager.list_credentials()

    def process_dlq(
        self, operation_type: Optional[str] = None, limit: int = 10
    ) -> Dict[str, Any]:
        """
        Process items in the Dead Letter Queue for retry.

        Args:
            operation_type: Optional operation type to filter by
            limit: Maximum number of items to process

        Returns:
            Dictionary with processing results
        """
        self.logger.info(
            f"Processing Dead Letter Queue (type={operation_type}, limit={limit})"
        )

        # Get DLQ items
        items = self.dlq.get_items(limit=limit)

        class DLQResults(TypedDict):
            total_processed: int
            successful: int
            failed: int
            items: List[Dict[str, Any]]

        results: DLQResults = {
            "total_processed": 0,
            "successful": 0,
            "failed": 0,
            "items": [],
        }

        for item in items:
            # Skip if not matching the requested operation type
            if (
                operation_type
                and item.get("metadata", {}).get("operation_type") != operation_type
            ):
                continue

            item_id = item.get("id", "unknown")
            payload = item.get("payload", {})
            metadata = item.get("metadata", {})

            retry_result = {
                "id": item_id,
                "success": False,
                "message": "Operation not retried",
            }

            # Determine what type of operation this is and how to retry it
            if "endpoint" in payload and "source_" in metadata.get(
                "operation_type", ""
            ):
                # This is a source operation
                try:
                    self.source.fetch_data(
                        payload.get("endpoint"), payload.get("params")
                    )
                    retry_result["success"] = True
                    retry_result["message"] = "Successfully retried source operation"
                    results["successful"] += 1
                except Exception as e:
                    retry_result["message"] = (
                        f"Failed to retry source operation: {str(e)}"
                    )
                    results["failed"] += 1

            elif "endpoint" in payload and "target_" in metadata.get(
                "operation_type", ""
            ):
                # This is a target operation
                try:
                    self.target.send_data(payload.get("endpoint"), payload.get("data"))
                    retry_result["success"] = True
                    retry_result["message"] = "Successfully retried target operation"
                    results["successful"] += 1
                except Exception as e:
                    retry_result["message"] = (
                        f"Failed to retry target operation: {str(e)}"
                    )
                    results["failed"] += 1

            else:
                # Unknown operation type
                retry_result["message"] = "Unknown operation type - cannot retry"
                results["failed"] += 1

            results["total_processed"] += 1
            results["items"].append(retry_result)

        self.logger.info(
            f"DLQ processing complete: {results['successful']} successful, {results['failed']} failed"
        )
        return dict(results)

    def fetch(
        self,
        endpoint: str,
        params: Optional[Dict[str, Any]] = None,
    ) -> Any:
        """
        Convenience wrapper to fetch data from the configured source connector.

        Args:
            endpoint: Source endpoint name to fetch from
            params: Optional parameters for the request

        Returns:
            Parsed response payload from the source API
        """
        if not self.source:
            raise ValueError("Source connector is not configured")
        return self.source.fetch_data(endpoint, params)

    def stream(
        self,
        endpoint: str,
        params: Optional[Dict[str, Any]] = None,
        **kwargs: Any,
    ) -> Any:
        """
        Convenience wrapper to stream a response from the configured source.

        Args:
            endpoint: Source endpoint name to stream from
            params: Optional query parameters
            **kwargs: Additional arguments forwarded to ``ApiConnector.stream_response``

        Returns:
            A generator yielding byte chunks from the source response.
        """
        if not self.source:
            raise ValueError("Source connector is not configured")
        return self.source.stream_response(endpoint, params, **kwargs)

    def download(
        self,
        endpoint: str,
        destination_path: str,
        params: Optional[Dict[str, Any]] = None,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """
        Convenience wrapper to download a streamed response from the source.

        Args:
            endpoint: Source endpoint name to download from
            destination_path: Destination file path
            params: Optional query parameters
            **kwargs: Additional arguments forwarded to ``ApiConnector.download_stream``

        Returns:
            Download result metadata.
        """
        if not self.source:
            raise ValueError("Source connector is not configured")
        return self.source.download_stream(
            endpoint, destination_path, params=params, **kwargs
        )

    def send(
        self,
        endpoint: str,
        data: Union[Dict[str, Any], List[Dict[str, Any]]],
        **kwargs: Any,
    ) -> Any:
        """
        Convenience wrapper to send data to the configured target connector.

        Args:
            endpoint: Target endpoint name to send to
            data: Payload to send (single item or list)

        Returns:
            Target connector response (if any)
        """
        if not self.target:
            raise ValueError("Target connector is not configured")
        return self.target.send_data(endpoint, data, **kwargs)

    def _resolve_source_connector(self, name: str) -> ApiConnector:
        """Resolve a source connector by logical name."""
        connector = self.sources.get(name)
        if connector:
            return connector

        if name == "source" and self.source:
            return self.source

        raise ValueError(f"Source connector '{name}' is not registered")

    def aggregate_source_data(
        self,
        source_data: Dict[str, Any],
        aggregation_config: Dict[str, Any],
    ) -> List[Dict[str, Any]]:
        """
        Aggregate pre-fetched source payloads using the configured mapper rules.

        Args:
            source_data: Mapping of source name to payload
            aggregation_config: Aggregation config consumed by ``MultiSourceAggregator``

        Returns:
            Aggregated record list.
        """
        return self.multi_source_aggregator.aggregate(source_data, aggregation_config)

    def aggregate_sources(
        self,
        source_requests: Dict[str, Dict[str, Any]],
        aggregation_config: Dict[str, Any],
        parallel: bool = True,
    ) -> List[Dict[str, Any]]:
        """
        Fetch multiple sources and aggregate them into a single dataset.

        Args:
            source_requests: Mapping of source alias to request config.
                Each request supports ``connector``, ``endpoint``, and optional ``params``.
            aggregation_config: Multi-source aggregation config.
            parallel: Whether to fetch sources concurrently.

        Returns:
            Aggregated record list.
        """
        if not source_requests:
            return []

        def _fetch_source(
            alias: str, request_config: Dict[str, Any]
        ) -> Tuple[str, Any]:
            connector_name = request_config.get("connector", alias)
            endpoint = request_config["endpoint"]
            params = request_config.get("params")
            connector = self._resolve_source_connector(connector_name)
            return alias, connector.fetch_data(endpoint, params)

        source_payloads: Dict[str, Any] = {}

        if parallel and len(source_requests) > 1:
            max_workers = min(8, len(source_requests))
            with ThreadPoolExecutor(max_workers=max_workers) as executor:
                future_map = {
                    executor.submit(_fetch_source, alias, request_config): alias
                    for alias, request_config in source_requests.items()
                }
                for future in as_completed(future_map):
                    alias, payload = future.result()
                    source_payloads[alias] = payload
        else:
            for alias, request_config in source_requests.items():
                resolved_alias, payload = _fetch_source(alias, request_config)
                source_payloads[resolved_alias] = payload

        return self.aggregate_source_data(source_payloads, aggregation_config)

    def sync(
        self,
        source_endpoint: Optional[str] = None,
        target_endpoint: Optional[str] = None,
        params: Optional[Dict[str, Any]] = None,
        max_retries: int = 3,
        retry_delay: float = 1.0,
        retry_backoff_factor: float = 2.0,
        retry_status_codes: Optional[List[int]] = None,
    ) -> SyncResult:
        """
        Execute a sync operation between source and target APIs.

        Args:
            source_endpoint: Source endpoint to use (overrides mapping)
            target_endpoint: Target endpoint to use (overrides mapping)
            params: Additional parameters for the source API call
            max_retries: Maximum number of retry attempts for transient failures
            retry_delay: Initial delay between retries in seconds
            retry_backoff_factor: Multiplicative factor for retry delay
            retry_status_codes: HTTP status codes to retry (default: 429, 502, 503, 504)

        Returns:
            SyncResult: Result of the sync operation
        """
        if not self.source or not self.target:
            raise ValueError(
                "Source and target connectors must be configured before syncing"
            )

        # If no endpoints specified, use the first mapping
        if not source_endpoint or not target_endpoint:
            mapping = self.mapper.get_first_mapping()
            if not mapping:
                raise ValueError("No mapping configured and no endpoints specified")
            source_endpoint = mapping["source"]
            target_endpoint = mapping["target"]

        # Generate correlation ID for this sync operation
        correlation_id = str(uuid.uuid4())
        start_time = time.time()

        # Wrap entire sync operation in distributed tracing
        with self.telemetry.trace_sync(
            source_endpoint, target_endpoint, correlation_id
        ):
            # Start provenance
            self.provenance.start_run(
                correlation_id=correlation_id,
                config_path=(
                    config_path
                    if (config_path := getattr(self, "_last_config_path", None))
                    else None
                ),
                source_endpoint=source_endpoint,
                target_endpoint=target_endpoint,
            )

            # Default retry status codes if none provided
            if retry_status_codes is None:
                retry_status_codes = [429, 502, 503, 504]  # Common transient failures

            self.logger.info(
                f"[{correlation_id}] Starting sync from {source_endpoint} to {target_endpoint}"
            )

            # Initialize result object
            sync_result = SyncResult(correlation_id=correlation_id)

            # Get circuit breaker for source endpoint
            source_circuit_name = f"source_{source_endpoint}"
            source_cb = self.error_recovery_manager.get_circuit_breaker(
                source_circuit_name
            )

            # Check if user has permission for this operation
            if self.security_manager.enable_access_control:
                current_user = getattr(self, "current_user", None)
                if current_user and not self.security_manager.check_permission(
                    current_user, "run_sync"
                ):
                    raise PermissionError(
                        f"User {current_user} does not have permission to run sync operations"
                    )

            # Merge last_sync into params from state store if not provided
            if params is None:
                effective_params = None
            else:
                effective_params = dict(params)
            if self.state_store:
                # Ensure we have a dict if we are going to inject
                need_inject = (effective_params is None) or (
                    "updated_since" not in effective_params
                )
                if need_inject:
                    last_sync = self.state_store.get_last_sync(source_endpoint)
                    if last_sync:
                        effective_params = dict(effective_params or {})
                        effective_params["updated_since"] = last_sync

            # Always use standard non-encrypted call
            source_data, source_error = source_cb.execute(
                lambda: self.source.fetch_data(source_endpoint, effective_params)
            )

            # If circuit breaker failed, try recovery strategies
            if source_error:
                # Create payload for retry
                fetch_payload = {"endpoint": source_endpoint, "params": params}

                # Apply recovery strategies
                success, result, error = self.error_recovery_manager.handle_error(
                    error=source_error,
                    payload=fetch_payload,
                    operation=lambda p: self.source.fetch_data(
                        p["endpoint"], p["params"]
                    ),
                    operation_type=source_circuit_name,
                    max_retries=max_retries,
                    retry_delay=retry_delay,
                    retry_backoff_factor=retry_backoff_factor,
                )

                if success:
                    source_data = result
                else:
                    # Record the error for analytics
                    self.error_analytics.record_error(error)

                    # Update result with error details
                    end_time = time.time()
                    sync_result.duration_ms = int((end_time - start_time) * 1000)
                    sync_result.success = False
                    sync_result.errors.append(error.to_dict())
                    self.logger.error(f"[{correlation_id}] Sync failed: {error}")
                    return sync_result

            try:
                # Map fields according to configuration
                transformed_data = self.mapper.map_data(
                    source_endpoint, target_endpoint, source_data
                )

                # Optional strict validation against target request schema (if defined in connector)
                if (
                    self.validation_config.get("strict_mode")
                    and is_validator_available()
                ):
                    target_endpoint_cfg = (
                        self.target.endpoints.get(target_endpoint)
                        if self.target
                        else None
                    )
                    if target_endpoint_cfg and target_endpoint_cfg.request_schema:
                        if isinstance(transformed_data, list):
                            for item in transformed_data:
                                valid, diffs = validate_payload_against_schema(
                                    item, target_endpoint_cfg.request_schema
                                )
                                if not valid:
                                    raise ApiLinkerError(
                                        message="Strict mode: target payload failed schema validation",
                                        error_category=ErrorCategory.VALIDATION,
                                        status_code=0,
                                        additional_context={"diffs": diffs},
                                    )
                        else:
                            valid, diffs = validate_payload_against_schema(
                                transformed_data, target_endpoint_cfg.request_schema
                            )
                            if not valid:
                                raise ApiLinkerError(
                                    message="Strict mode: target payload failed schema validation",
                                    error_category=ErrorCategory.VALIDATION,
                                    status_code=0,
                                    additional_context={"diffs": diffs},
                                )

                # Record source data metrics
                source_count = len(source_data) if isinstance(source_data, list) else 1
                sync_result.details["source_count"] = source_count

                # Get circuit breaker for target endpoint
                target_circuit_name = f"target_{target_endpoint}"
                target_cb = self.error_recovery_manager.get_circuit_breaker(
                    target_circuit_name
                )

                # Idempotency: skip payloads we've already sent during replays
                def _send():
                    # If idempotency enabled, de-duplicate per item
                    if self.idempotency_config.get("enabled") and isinstance(
                        transformed_data, list
                    ):
                        salt = self.idempotency_config.get("salt", "")
                        filtered = []
                        for item in transformed_data:
                            key = generate_idempotency_key(item, salt=salt)
                            if not self.deduplicator.has_seen(target_endpoint, key):
                                self.deduplicator.mark_seen(target_endpoint, key)
                                filtered.append(item)
                        payload: Union[Dict[str, Any], List[Dict[str, Any]]] = filtered
                    else:
                        payload = transformed_data
                    return self.target.send_data(target_endpoint, payload)

                # Always use standard non-encrypted call
                target_result, target_error = target_cb.execute(_send)

                # If circuit breaker failed, try recovery strategies
                if target_error:
                    # Create payload for retry
                    send_payload = {
                        "endpoint": target_endpoint,
                        "data": transformed_data,
                    }

                    # Apply recovery strategies
                    success, result, error = self.error_recovery_manager.handle_error(
                        error=target_error,
                        payload=send_payload,
                        operation=lambda p: self.target.send_data(
                            p["endpoint"], p["data"]
                        ),
                        operation_type=target_circuit_name,
                        max_retries=max_retries,
                        retry_delay=retry_delay,
                        retry_backoff_factor=retry_backoff_factor,
                    )

                    if success:
                        target_result = result
                    else:
                        # Record the error for analytics
                        self.error_analytics.record_error(error)

                        # Update result with error details
                        end_time = time.time()
                        sync_result.duration_ms = int((end_time - start_time) * 1000)
                        sync_result.success = False
                        sync_result.errors.append(error.to_dict())
                        self.logger.error(f"[{correlation_id}] Sync failed: {error}")
                        return sync_result

                # Update result with success information
                sync_result.count = (
                    len(transformed_data) if isinstance(transformed_data, list) else 1
                )
                sync_result.success = True

                # Set target response directly
                if isinstance(target_result, dict):
                    sync_result.target_response = target_result
                else:
                    sync_result.target_response = {}

                # Calculate duration
                end_time = time.time()
                sync_result.duration_ms = int((end_time - start_time) * 1000)

                self.logger.info(
                    f"[{correlation_id}] Sync completed successfully: {sync_result.count} items transferred in {sync_result.duration_ms}ms"
                )
                # Update last_sync checkpoint
                if self.state_store:
                    self.state_store.set_last_sync(source_endpoint, now_iso())
                # Complete provenance
                self.provenance.complete_run(
                    True, sync_result.count, sync_result.details
                )

                # Record telemetry metrics
                self.telemetry.record_sync_completion(
                    source_endpoint, target_endpoint, True, sync_result.count
                )

                return sync_result

            except Exception as e:
                # Convert to ApiLinkerError
                error = ApiLinkerError.from_exception(
                    e,
                    error_category=ErrorCategory.MAPPING,
                    correlation_id=correlation_id,
                    operation_id=f"mapping_{source_endpoint}_to_{target_endpoint}",
                )

                # Record the error for analytics
                self.error_analytics.record_error(error)

                # Update result
                end_time = time.time()
                sync_result.duration_ms = int((end_time - start_time) * 1000)
                sync_result.success = False
                sync_result.errors.append(error.to_dict())

                self.logger.error(
                    f"[{correlation_id}] Sync failed during mapping: {error}"
                )
                # Record error in provenance
                self.provenance.record_error(
                    error.message,
                    category=error.error_category.value,
                    status_code=error.status_code,
                    endpoint=target_endpoint,
                )
                self.provenance.complete_run(False, 0, {})

                # Record telemetry metrics
                self.telemetry.record_sync_completion(
                    source_endpoint, target_endpoint, False, 0
                )
                self.telemetry.record_error(
                    error.error_category.value, "sync", error.message
                )

            return sync_result

    def start_scheduled_sync(self) -> None:
        """Start scheduled sync operations."""
        self.logger.info("Starting scheduled sync")
        self.scheduler.start(self.sync)

    def stop_scheduled_sync(self) -> None:
        """Stop scheduled sync operations."""
        self.logger.info("Stopping scheduled sync")
        self.scheduler.stop()

    def _with_retries(
        self,
        operation: Callable[[], Any],
        operation_name: str,
        max_retries: int,
        retry_delay: float,
        retry_backoff_factor: float,
        retry_status_codes: List[int],
        correlation_id: str,
    ) -> Tuple[Any, Optional[ErrorDetail]]:
        """
        Execute an operation with configurable retry logic for transient failures.

        Args:
            operation: Callable function to execute
            operation_name: Name of operation for logging
            max_retries: Maximum number of retry attempts
            retry_delay: Initial delay between retries in seconds
            retry_backoff_factor: Multiplicative factor for retry delay
            retry_status_codes: HTTP status codes that should trigger a retry
            correlation_id: Correlation ID for tracing

        Returns:
            Tuple of (result, error_detail) - If successful, error_detail will be None
        """
        current_delay = retry_delay

        for attempt in range(max_retries + 1):
            try:
                if attempt > 0:
                    self.logger.info(
                        f"[{correlation_id}] Retry attempt {attempt}/{max_retries} for {operation_name} after {current_delay:.2f}s delay"
                    )
                    time.sleep(current_delay)
                    current_delay *= retry_backoff_factor

                result = operation()

                if attempt > 0:
                    self.logger.info(
                        f"[{correlation_id}] Retry succeeded for {operation_name}"
                    )

                return result, None

            except Exception as e:
                status_code = getattr(e, "status_code", None)
                response_body = getattr(e, "response", None)
                request_url = getattr(e, "url", None)
                request_method = getattr(e, "method", None)

                # Convert response to string if it's not already
                if response_body and not isinstance(response_body, str):
                    try:
                        response_body = str(response_body)[:1000]  # Limit size
                    except:
                        response_body = "<Unable to convert response to string>"

                error_detail = ErrorDetail(
                    message=str(e),
                    status_code=status_code,
                    response_body=response_body,
                    request_url=request_url,
                    request_method=request_method,
                    timestamp=datetime.now().isoformat(),
                    error_type=(
                        "transient_error"
                        if status_code in retry_status_codes
                        else "api_error"
                    ),
                )

                # Check if this is a retryable error
                is_retryable = (
                    status_code in retry_status_codes if status_code else False
                )

                if is_retryable and attempt < max_retries:
                    self.logger.warning(
                        f"[{correlation_id}] {operation_name} failed with retryable error (status: {status_code}): {str(e)}"
                    )
                else:
                    # Either not retryable or out of retries
                    log_level = logging.WARNING if is_retryable else logging.ERROR
                    retry_msg = (
                        "out of retry attempts"
                        if is_retryable
                        else "non-retryable error"
                    )

                    self.logger.log(
                        log_level,
                        f"[{correlation_id}] {operation_name} failed with {retry_msg}: {str(e)}",
                    )
                    return None, error_detail

        # We should never reach here, but just in case
        fallback_error = ErrorDetail(
            message=f"Unknown error during {operation_name}",
            timestamp=datetime.now().isoformat(),
            error_type="unknown_error",
        )
        return None, fallback_error

__init__(config_path=None, source_config=None, target_config=None, mapping_config=None, schedule_config=None, error_handling_config=None, security_config=None, validation_config=None, observability_config=None, secret_manager_config=None, log_level='INFO', log_file=None)

Source code in apilinker/api_linker.py
def __init__(
    self,
    config_path: Optional[str] = None,
    source_config: Optional[Dict[str, Any]] = None,
    target_config: Optional[Dict[str, Any]] = None,
    mapping_config: Optional[Dict[str, Any]] = None,
    schedule_config: Optional[Dict[str, Any]] = None,
    error_handling_config: Optional[Dict[str, Any]] = None,
    security_config: Optional[Dict[str, Any]] = None,
    validation_config: Optional[Dict[str, Any]] = None,
    observability_config: Optional[Dict[str, Any]] = None,
    secret_manager_config: Optional[Dict[str, Any]] = None,
    log_level: str = "INFO",
    log_file: Optional[str] = None,
) -> None:
    # Initialize logger
    self.logger = setup_logger(log_level, log_file)
    self.logger.info("Initializing ApiLinker")

    # Initialize components
    self.source: Optional[ApiConnector] = None
    self.target: Optional[ApiConnector] = None
    self.sources: Dict[str, ApiConnector] = {}
    self.mapper = FieldMapper()
    self.multi_source_aggregator = MultiSourceAggregator(self.mapper)
    self.scheduler = Scheduler()
    self.validation_config = validation_config or {"strict_mode": False}
    self.provenance = ProvenanceRecorder()
    self.deduplicator = InMemoryDeduplicator()
    self.state_store: Optional[StateStore] = None

    # Initialize observability
    self.telemetry = self._initialize_observability(observability_config)

    # Initialize secret management
    self.secret_manager = self._initialize_secret_manager(secret_manager_config)

    # Initialize security system
    self.security_manager = self._initialize_security(security_config)

    # Initialize auth manager and integrate with security
    self.auth_manager = AuthManager()
    integrate_security_with_auth_manager(self.security_manager, self.auth_manager)

    # Initialize error handling system
    self.dlq, self.error_recovery_manager, self.error_analytics = (
        create_error_handler()
    )

    # Load configuration if provided
    if config_path:
        self.load_config(config_path)
    else:
        # Set up direct configurations if provided
        if source_config:
            self.add_source(**source_config)
        if target_config:
            self.add_target(**target_config)
        if mapping_config:
            self.add_mapping(**mapping_config)
        if schedule_config:
            self.add_schedule(**schedule_config)
        if error_handling_config:
            self._configure_error_handling(error_handling_config)
        if security_config:
            self._configure_security(security_config)

add_source(type, base_url, auth=None, endpoints=None, **kwargs)

Add a source API connector.

Parameters:

Name Type Description Default
type str

Type of API connector (rest, graphql, etc.)

required
base_url str

Base URL of the API

required
auth Optional[Dict[str, Any]]

Authentication configuration

None
endpoints Optional[Dict[str, Any]]

Configured endpoints

None
**kwargs Any

Additional configuration parameters

{}
Source code in apilinker/api_linker.py
def add_source(
    self,
    type: str,
    base_url: str,
    auth: Optional[Dict[str, Any]] = None,
    endpoints: Optional[Dict[str, Any]] = None,
    **kwargs: Any,
) -> None:
    """
    Add a source API connector.

    Args:
        type: Type of API connector (rest, graphql, etc.)
        base_url: Base URL of the API
        auth: Authentication configuration
        endpoints: Configured endpoints
        **kwargs: Additional configuration parameters
    """
    self.logger.info(f"Adding source connector: {type} for {base_url}")
    self.source = self._create_connector(type, base_url, auth, endpoints, **kwargs)
    self.sources["source"] = self.source

add_target(type, base_url, auth=None, endpoints=None, **kwargs)

Add a target API connector.

Parameters:

Name Type Description Default
type str

Type of API connector (rest, graphql, etc.)

required
base_url str

Base URL of the API

required
auth Optional[Dict[str, Any]]

Authentication configuration

None
endpoints Optional[Dict[str, Any]]

Configured endpoints

None
**kwargs Any

Additional configuration parameters

{}
Source code in apilinker/api_linker.py
def add_target(
    self,
    type: str,
    base_url: str,
    auth: Optional[Dict[str, Any]] = None,
    endpoints: Optional[Dict[str, Any]] = None,
    **kwargs: Any,
) -> None:
    """
    Add a target API connector.

    Args:
        type: Type of API connector (rest, graphql, etc.)
        base_url: Base URL of the API
        auth: Authentication configuration
        endpoints: Configured endpoints
        **kwargs: Additional configuration parameters
    """
    self.logger.info(f"Adding target connector: {type} for {base_url}")
    self.target = self._create_connector(type, base_url, auth, endpoints, **kwargs)

add_mapping(source, target, fields)

Add a field mapping between source and target endpoints.

Parameters:

Name Type Description Default
source str

Source endpoint name

required
target str

Target endpoint name

required
fields List[Dict[str, Any]]

List of field mappings

required
Source code in apilinker/api_linker.py
def add_mapping(
    self, source: str, target: str, fields: List[Dict[str, Any]]
) -> None:
    """
    Add a field mapping between source and target endpoints.

    Args:
        source: Source endpoint name
        target: Target endpoint name
        fields: List of field mappings
    """
    self.logger.info(
        f"Adding mapping from {source} to {target} with {len(fields)} fields"
    )
    self.mapper.add_mapping(source, target, fields)

sync(source_endpoint=None, target_endpoint=None, params=None, max_retries=3, retry_delay=1.0, retry_backoff_factor=2.0, retry_status_codes=None)

Execute a sync operation between source and target APIs.

Parameters:

Name Type Description Default
source_endpoint Optional[str]

Source endpoint to use (overrides mapping)

None
target_endpoint Optional[str]

Target endpoint to use (overrides mapping)

None
params Optional[Dict[str, Any]]

Additional parameters for the source API call

None
max_retries int

Maximum number of retry attempts for transient failures

3
retry_delay float

Initial delay between retries in seconds

1.0
retry_backoff_factor float

Multiplicative factor for retry delay

2.0
retry_status_codes Optional[List[int]]

HTTP status codes to retry (default: 429, 502, 503, 504)

None

Returns:

Name Type Description
SyncResult SyncResult

Result of the sync operation

Source code in apilinker/api_linker.py
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
def sync(
    self,
    source_endpoint: Optional[str] = None,
    target_endpoint: Optional[str] = None,
    params: Optional[Dict[str, Any]] = None,
    max_retries: int = 3,
    retry_delay: float = 1.0,
    retry_backoff_factor: float = 2.0,
    retry_status_codes: Optional[List[int]] = None,
) -> SyncResult:
    """
    Execute a sync operation between source and target APIs.

    Args:
        source_endpoint: Source endpoint to use (overrides mapping)
        target_endpoint: Target endpoint to use (overrides mapping)
        params: Additional parameters for the source API call
        max_retries: Maximum number of retry attempts for transient failures
        retry_delay: Initial delay between retries in seconds
        retry_backoff_factor: Multiplicative factor for retry delay
        retry_status_codes: HTTP status codes to retry (default: 429, 502, 503, 504)

    Returns:
        SyncResult: Result of the sync operation
    """
    if not self.source or not self.target:
        raise ValueError(
            "Source and target connectors must be configured before syncing"
        )

    # If no endpoints specified, use the first mapping
    if not source_endpoint or not target_endpoint:
        mapping = self.mapper.get_first_mapping()
        if not mapping:
            raise ValueError("No mapping configured and no endpoints specified")
        source_endpoint = mapping["source"]
        target_endpoint = mapping["target"]

    # Generate correlation ID for this sync operation
    correlation_id = str(uuid.uuid4())
    start_time = time.time()

    # Wrap entire sync operation in distributed tracing
    with self.telemetry.trace_sync(
        source_endpoint, target_endpoint, correlation_id
    ):
        # Start provenance
        self.provenance.start_run(
            correlation_id=correlation_id,
            config_path=(
                config_path
                if (config_path := getattr(self, "_last_config_path", None))
                else None
            ),
            source_endpoint=source_endpoint,
            target_endpoint=target_endpoint,
        )

        # Default retry status codes if none provided
        if retry_status_codes is None:
            retry_status_codes = [429, 502, 503, 504]  # Common transient failures

        self.logger.info(
            f"[{correlation_id}] Starting sync from {source_endpoint} to {target_endpoint}"
        )

        # Initialize result object
        sync_result = SyncResult(correlation_id=correlation_id)

        # Get circuit breaker for source endpoint
        source_circuit_name = f"source_{source_endpoint}"
        source_cb = self.error_recovery_manager.get_circuit_breaker(
            source_circuit_name
        )

        # Check if user has permission for this operation
        if self.security_manager.enable_access_control:
            current_user = getattr(self, "current_user", None)
            if current_user and not self.security_manager.check_permission(
                current_user, "run_sync"
            ):
                raise PermissionError(
                    f"User {current_user} does not have permission to run sync operations"
                )

        # Merge last_sync into params from state store if not provided
        if params is None:
            effective_params = None
        else:
            effective_params = dict(params)
        if self.state_store:
            # Ensure we have a dict if we are going to inject
            need_inject = (effective_params is None) or (
                "updated_since" not in effective_params
            )
            if need_inject:
                last_sync = self.state_store.get_last_sync(source_endpoint)
                if last_sync:
                    effective_params = dict(effective_params or {})
                    effective_params["updated_since"] = last_sync

        # Always use standard non-encrypted call
        source_data, source_error = source_cb.execute(
            lambda: self.source.fetch_data(source_endpoint, effective_params)
        )

        # If circuit breaker failed, try recovery strategies
        if source_error:
            # Create payload for retry
            fetch_payload = {"endpoint": source_endpoint, "params": params}

            # Apply recovery strategies
            success, result, error = self.error_recovery_manager.handle_error(
                error=source_error,
                payload=fetch_payload,
                operation=lambda p: self.source.fetch_data(
                    p["endpoint"], p["params"]
                ),
                operation_type=source_circuit_name,
                max_retries=max_retries,
                retry_delay=retry_delay,
                retry_backoff_factor=retry_backoff_factor,
            )

            if success:
                source_data = result
            else:
                # Record the error for analytics
                self.error_analytics.record_error(error)

                # Update result with error details
                end_time = time.time()
                sync_result.duration_ms = int((end_time - start_time) * 1000)
                sync_result.success = False
                sync_result.errors.append(error.to_dict())
                self.logger.error(f"[{correlation_id}] Sync failed: {error}")
                return sync_result

        try:
            # Map fields according to configuration
            transformed_data = self.mapper.map_data(
                source_endpoint, target_endpoint, source_data
            )

            # Optional strict validation against target request schema (if defined in connector)
            if (
                self.validation_config.get("strict_mode")
                and is_validator_available()
            ):
                target_endpoint_cfg = (
                    self.target.endpoints.get(target_endpoint)
                    if self.target
                    else None
                )
                if target_endpoint_cfg and target_endpoint_cfg.request_schema:
                    if isinstance(transformed_data, list):
                        for item in transformed_data:
                            valid, diffs = validate_payload_against_schema(
                                item, target_endpoint_cfg.request_schema
                            )
                            if not valid:
                                raise ApiLinkerError(
                                    message="Strict mode: target payload failed schema validation",
                                    error_category=ErrorCategory.VALIDATION,
                                    status_code=0,
                                    additional_context={"diffs": diffs},
                                )
                    else:
                        valid, diffs = validate_payload_against_schema(
                            transformed_data, target_endpoint_cfg.request_schema
                        )
                        if not valid:
                            raise ApiLinkerError(
                                message="Strict mode: target payload failed schema validation",
                                error_category=ErrorCategory.VALIDATION,
                                status_code=0,
                                additional_context={"diffs": diffs},
                            )

            # Record source data metrics
            source_count = len(source_data) if isinstance(source_data, list) else 1
            sync_result.details["source_count"] = source_count

            # Get circuit breaker for target endpoint
            target_circuit_name = f"target_{target_endpoint}"
            target_cb = self.error_recovery_manager.get_circuit_breaker(
                target_circuit_name
            )

            # Idempotency: skip payloads we've already sent during replays
            def _send():
                # If idempotency enabled, de-duplicate per item
                if self.idempotency_config.get("enabled") and isinstance(
                    transformed_data, list
                ):
                    salt = self.idempotency_config.get("salt", "")
                    filtered = []
                    for item in transformed_data:
                        key = generate_idempotency_key(item, salt=salt)
                        if not self.deduplicator.has_seen(target_endpoint, key):
                            self.deduplicator.mark_seen(target_endpoint, key)
                            filtered.append(item)
                    payload: Union[Dict[str, Any], List[Dict[str, Any]]] = filtered
                else:
                    payload = transformed_data
                return self.target.send_data(target_endpoint, payload)

            # Always use standard non-encrypted call
            target_result, target_error = target_cb.execute(_send)

            # If circuit breaker failed, try recovery strategies
            if target_error:
                # Create payload for retry
                send_payload = {
                    "endpoint": target_endpoint,
                    "data": transformed_data,
                }

                # Apply recovery strategies
                success, result, error = self.error_recovery_manager.handle_error(
                    error=target_error,
                    payload=send_payload,
                    operation=lambda p: self.target.send_data(
                        p["endpoint"], p["data"]
                    ),
                    operation_type=target_circuit_name,
                    max_retries=max_retries,
                    retry_delay=retry_delay,
                    retry_backoff_factor=retry_backoff_factor,
                )

                if success:
                    target_result = result
                else:
                    # Record the error for analytics
                    self.error_analytics.record_error(error)

                    # Update result with error details
                    end_time = time.time()
                    sync_result.duration_ms = int((end_time - start_time) * 1000)
                    sync_result.success = False
                    sync_result.errors.append(error.to_dict())
                    self.logger.error(f"[{correlation_id}] Sync failed: {error}")
                    return sync_result

            # Update result with success information
            sync_result.count = (
                len(transformed_data) if isinstance(transformed_data, list) else 1
            )
            sync_result.success = True

            # Set target response directly
            if isinstance(target_result, dict):
                sync_result.target_response = target_result
            else:
                sync_result.target_response = {}

            # Calculate duration
            end_time = time.time()
            sync_result.duration_ms = int((end_time - start_time) * 1000)

            self.logger.info(
                f"[{correlation_id}] Sync completed successfully: {sync_result.count} items transferred in {sync_result.duration_ms}ms"
            )
            # Update last_sync checkpoint
            if self.state_store:
                self.state_store.set_last_sync(source_endpoint, now_iso())
            # Complete provenance
            self.provenance.complete_run(
                True, sync_result.count, sync_result.details
            )

            # Record telemetry metrics
            self.telemetry.record_sync_completion(
                source_endpoint, target_endpoint, True, sync_result.count
            )

            return sync_result

        except Exception as e:
            # Convert to ApiLinkerError
            error = ApiLinkerError.from_exception(
                e,
                error_category=ErrorCategory.MAPPING,
                correlation_id=correlation_id,
                operation_id=f"mapping_{source_endpoint}_to_{target_endpoint}",
            )

            # Record the error for analytics
            self.error_analytics.record_error(error)

            # Update result
            end_time = time.time()
            sync_result.duration_ms = int((end_time - start_time) * 1000)
            sync_result.success = False
            sync_result.errors.append(error.to_dict())

            self.logger.error(
                f"[{correlation_id}] Sync failed during mapping: {error}"
            )
            # Record error in provenance
            self.provenance.record_error(
                error.message,
                category=error.error_category.value,
                status_code=error.status_code,
                endpoint=target_endpoint,
            )
            self.provenance.complete_run(False, 0, {})

            # Record telemetry metrics
            self.telemetry.record_sync_completion(
                source_endpoint, target_endpoint, False, 0
            )
            self.telemetry.record_error(
                error.error_category.value, "sync", error.message
            )

        return sync_result

fetch(endpoint, params=None)

Convenience wrapper to fetch data from the configured source connector.

Parameters:

Name Type Description Default
endpoint str

Source endpoint name to fetch from

required
params Optional[Dict[str, Any]]

Optional parameters for the request

None

Returns:

Type Description
Any

Parsed response payload from the source API

Source code in apilinker/api_linker.py
def fetch(
    self,
    endpoint: str,
    params: Optional[Dict[str, Any]] = None,
) -> Any:
    """
    Convenience wrapper to fetch data from the configured source connector.

    Args:
        endpoint: Source endpoint name to fetch from
        params: Optional parameters for the request

    Returns:
        Parsed response payload from the source API
    """
    if not self.source:
        raise ValueError("Source connector is not configured")
    return self.source.fetch_data(endpoint, params)

send(endpoint, data, **kwargs)

Convenience wrapper to send data to the configured target connector.

Parameters:

Name Type Description Default
endpoint str

Target endpoint name to send to

required
data Union[Dict[str, Any], List[Dict[str, Any]]]

Payload to send (single item or list)

required

Returns:

Type Description
Any

Target connector response (if any)

Source code in apilinker/api_linker.py
def send(
    self,
    endpoint: str,
    data: Union[Dict[str, Any], List[Dict[str, Any]]],
    **kwargs: Any,
) -> Any:
    """
    Convenience wrapper to send data to the configured target connector.

    Args:
        endpoint: Target endpoint name to send to
        data: Payload to send (single item or list)

    Returns:
        Target connector response (if any)
    """
    if not self.target:
        raise ValueError("Target connector is not configured")
    return self.target.send_data(endpoint, data, **kwargs)

ApiConnector

Base class for all API connectors.

apilinker.core.connector.ApiConnector

API Connector for interacting with REST APIs.

This class handles the connection to APIs, making requests, and processing responses.

Parameters:

Name Type Description Default
connector_type str

Type of connector (rest, graphql, etc.)

required
base_url str

Base URL for the API

required
auth_config Optional[AuthConfig]

Authentication configuration

None
endpoints Optional[Dict[str, Dict[str, Any]]]

Dictionary of endpoint configurations

None
timeout int

Request timeout in seconds

30
retry_count int

Number of retries on failure

3
retry_delay int

Delay between retries in seconds

1
Source code in apilinker/core/connector.py
  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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
class ApiConnector:
    """
    API Connector for interacting with REST APIs.

    This class handles the connection to APIs, making requests, and
    processing responses.

    Args:
        connector_type: Type of connector (rest, graphql, etc.)
        base_url: Base URL for the API
        auth_config: Authentication configuration
        endpoints: Dictionary of endpoint configurations
        timeout: Request timeout in seconds
        retry_count: Number of retries on failure
        retry_delay: Delay between retries in seconds
    """

    def __init__(
        self,
        connector_type: str,
        base_url: str,
        auth_config: Optional[AuthConfig] = None,
        endpoints: Optional[Dict[str, Dict[str, Any]]] = None,
        timeout: int = 30,
        retry_count: int = 3,
        retry_delay: int = 1,
        default_headers: Optional[Dict[str, str]] = None,
        **kwargs: Any,
    ) -> None:
        self.connector_type = connector_type
        self.base_url = base_url
        self.auth_config = auth_config
        self.timeout = timeout
        self.retry_count = retry_count
        self.retry_delay = retry_delay

        # Default headers (may be provided via explicit parameter or legacy 'headers' kwarg)
        if default_headers is None and "headers" in kwargs:
            try:
                default_headers = dict(kwargs.pop("headers"))
            except Exception:
                default_headers = None
        self.default_headers: Dict[str, str] = default_headers or {}
        # Provide a backwards-compatible attribute name used by some connectors
        self.headers: Dict[str, str] = self.default_headers

        # Parse and store endpoint configurations
        self.endpoints: Dict[str, EndpointConfig] = {}
        if endpoints:
            for name, config in endpoints.items():
                self.endpoints[name] = EndpointConfig(**config)

        # Store additional settings
        self.settings: Dict[str, Any] = kwargs

        # Create HTTP client with default settings
        self.client = self._create_client()

        # Initialize Rate Limit Manager
        self.rate_limit_manager = RateLimitManager()

        # Configure rate limiters for endpoints
        for name, config in self.endpoints.items():
            if config.rate_limit:
                self.rate_limit_manager.create_limiter(name, config.rate_limit)

        logger.debug(f"Initialized {connector_type} connector for {base_url}")

    def _create_client(self) -> httpx.Client:
        """Create an HTTP client with appropriate settings."""
        # Initialize with default parameters
        auth = None
        if (
            self.auth_config
            and self.auth_config.type == "basic"
            and hasattr(self.auth_config, "username")
            and hasattr(self.auth_config, "password")
        ):
            auth = httpx.BasicAuth(
                username=getattr(self.auth_config, "username", ""),
                password=getattr(self.auth_config, "password", ""),
            )

        # Create client with properly structured parameters
        return httpx.Client(base_url=self.base_url, timeout=self.timeout, auth=auth)

    def _prepare_request(
        self, endpoint_name: str, params: Optional[Dict[str, Any]] = None
    ) -> Dict[str, Any]:
        """
        Prepare a request for the given endpoint.

        Args:
            endpoint_name: Name of the endpoint to use
            params: Additional parameters to include in the request

        Returns:
            Dict containing request details (url, method, headers, params, json)
        """
        if endpoint_name not in self.endpoints:
            raise ValueError(f"Endpoint '{endpoint_name}' not found in configuration")

        endpoint = self.endpoints[endpoint_name]

        # Combine endpoint path with base URL
        url = endpoint.path

        # Combine params from endpoint config and provided params
        request_params = endpoint.params.copy()
        if params:
            request_params.update(params)

        # Prepare headers (merge default headers and endpoint-specific headers)
        headers = {**(self.default_headers or {}), **endpoint.headers}

        # Add auth headers if needed
        if self.auth_config:
            if (
                self.auth_config.type == "api_key"
                and hasattr(self.auth_config, "in_header")
                and getattr(self.auth_config, "in_header", False)
            ):
                header_name = getattr(self.auth_config, "header_name", "X-API-Key")
                key = getattr(self.auth_config, "key", "")
                headers[header_name] = key
            elif self.auth_config.type == "bearer" and hasattr(
                self.auth_config, "token"
            ):
                headers["Authorization"] = (
                    f"Bearer {getattr(self.auth_config, 'token', '')}"
                )

        # Prepare request object
        request = {
            "url": url,
            "method": endpoint.method,
            "headers": headers,
            "params": request_params,
        }

        # Add body if endpoint has a body template
        if endpoint.body_template:
            request["json"] = endpoint.body_template

        return request

    def _process_response(
        self, response: httpx.Response, endpoint_name: str
    ) -> Union[Dict[str, Any], List[Dict[str, Any]]]:
        """
        Process the API response.

        Args:
            response: The HTTP response
            endpoint_name: Name of the endpoint

        Returns:
            Parsed response data
        """
        # Update rate limiter from response headers
        self.rate_limit_manager.update_from_response(endpoint_name, response)

        # Raise for HTTP errors
        response.raise_for_status()

        # Parse JSON response
        data: Any = response.json()

        # Extract data from response path if configured
        endpoint = self.endpoints[endpoint_name]
        if endpoint.response_path and isinstance(data, dict):
            path_parts = endpoint.response_path.split(".")
            current_data: Any = data
            for part in path_parts:
                if isinstance(current_data, dict) and part in current_data:
                    current_data = current_data[part]
                else:
                    logger.warning(
                        f"Response path '{endpoint.response_path}' not found in response"
                    )
                    break
            # Only update data if we successfully navigated through the path
            if current_data is not data:
                data = current_data

        # Validate against response schema if provided
        endpoint = self.endpoints[endpoint_name]
        if endpoint.response_schema and is_validator_available():
            valid, diffs = validate_payload_against_schema(
                data, endpoint.response_schema
            )
            if not valid:
                logger.warning(
                    "Response schema validation failed for %s\n%s",
                    endpoint_name,
                    pretty_print_diffs(diffs),
                )
                # Record as a rate-limit or validation event via logger context (provenance layer may hook logs)

        # Ensure we return a valid type
        if isinstance(data, (dict, list)):
            return data
        else:
            # If response isn't a dict or list, wrap it in a dict
            return {"value": data}

    def _handle_pagination(
        self,
        initial_data: Union[Dict[str, Any], List[Dict[str, Any]]],
        endpoint_name: str,
        params: Optional[Dict[str, Any]] = None,
    ) -> List[Dict[str, Any]]:
        """
        Handle paginated responses if pagination is configured.

        Args:
            initial_data: Data from the first request
            endpoint_name: Name of the endpoint
            params: Request parameters

        Returns:
            Combined data from all pages
        """
        endpoint = self.endpoints[endpoint_name]

        # If no pagination config or initial data is not a dict, return as is
        if not endpoint.pagination or not isinstance(initial_data, dict):
            if isinstance(initial_data, list):
                return initial_data
            # Convert non-list data to a single-item list
            return (
                [initial_data]
                if isinstance(initial_data, dict)
                else [{"value": initial_data}]
            )

        # Extract the pagination configuration
        pagination = endpoint.pagination
        data_path = pagination.get("data_path", "")
        next_page_path = pagination.get("next_page_path", "")
        page_param = pagination.get("page_param", "page")

        # Extract the items from the first response
        if data_path:
            path_parts = data_path.split(".")
            items: Any = initial_data
            for part in path_parts:
                if isinstance(items, dict) and part in items:
                    items = items[part]
                else:
                    logger.warning(f"Data path '{data_path}' not found in response")
                    return [initial_data]
        else:
            # If no data path is specified, the entire response is the data
            items = initial_data

        # Normalize items to a list of dicts
        if not isinstance(items, list):
            items_list: List[Dict[str, Any]] = (
                [items] if isinstance(items, dict) else [{"value": items}]
            )
        else:
            items_list = []
            for elem in items:
                if isinstance(elem, dict):
                    items_list.append(elem)
                else:
                    items_list.append({"value": elem})

        # Extract next page token/URL if available
        next_page: Optional[Union[str, int]] = None
        if next_page_path:
            path_parts = next_page_path.split(".")
            temp_next_page: Any = initial_data
            for part in path_parts:
                if isinstance(temp_next_page, dict) and part in temp_next_page:
                    temp_next_page = temp_next_page[part]
                else:
                    temp_next_page = None
                    break
            # Only assign if it's a valid type for pagination
            if isinstance(temp_next_page, (str, int)):
                next_page = temp_next_page

        # Return the items if there's no next page
        if not next_page:
            return items_list

        # Fetch all pages
        all_items: List[Dict[str, Any]] = list(items_list)
        page = 2

        while next_page:
            # Update params for next page
            next_params: Dict[str, Any] = params.copy() if params else {}

            # Use either page number or next page token (refined to str|int in this loop)
            next_params[page_param] = next_page

            # Make the next request
            try:
                request = self._prepare_request(endpoint_name, next_params)
                response = self.client.request(
                    request["method"],
                    request["url"],
                    headers=request["headers"],
                    params=request["params"],
                    json=request.get("json"),
                )
                response.raise_for_status()
                page_data = response.json()

                # Extract items from this page
                page_items: Any
                if data_path:
                    path_parts = data_path.split(".")
                    page_items = page_data
                    for part in path_parts:
                        if isinstance(page_items, dict) and part in page_items:
                            page_items = page_items[part]
                        else:
                            page_items = []
                            break
                else:
                    page_items = page_data

                # Add items to the result, normalizing to list[dict]
                if isinstance(page_items, list):
                    for elem in page_items:
                        if isinstance(elem, dict):
                            all_items.append(elem)
                        else:
                            all_items.append({"value": elem})
                else:
                    all_items.append(
                        page_items
                        if isinstance(page_items, dict)
                        else {"value": page_items}
                    )

                # Extract next page token
                if next_page_path:
                    path_parts = next_page_path.split(".")
                    temp_next_page = page_data
                    for part in path_parts:
                        if isinstance(temp_next_page, dict) and part in temp_next_page:
                            temp_next_page = temp_next_page[part]
                        else:
                            temp_next_page = None
                            break
                    # Only assign if it's a valid type for pagination
                    if isinstance(temp_next_page, (str, int)):
                        next_page = temp_next_page
                    else:
                        next_page = None
                else:
                    # If no next page path, just increment the page number
                    page += 1
                    next_page = (
                        page if page <= pagination.get("max_pages", 10) else None
                    )

            except Exception as e:
                logger.error(f"Error fetching page {page}: {str(e)}")
                break

        return all_items

    def _categorize_error(self, exc: Exception) -> Tuple[ErrorCategory, int]:
        """
        Categorize an exception to determine its error category and status code.

        Args:
            exc: The exception to categorize

        Returns:
            Tuple of (ErrorCategory, status_code)
        """
        # Default values
        category = ErrorCategory.UNKNOWN
        status_code = None

        # Check for HTTP-specific errors
        if isinstance(exc, httpx.TimeoutException):
            category = ErrorCategory.TIMEOUT
            status_code = 0  # Custom code for timeout
        elif isinstance(exc, httpx.TransportError) or isinstance(
            exc, httpx.RequestError
        ):
            category = ErrorCategory.NETWORK
            status_code = 0  # Custom code for network/transport errors
        elif isinstance(exc, httpx.HTTPStatusError):
            status_code = exc.response.status_code

            # Categorize based on HTTP status code
            if status_code == 401 or status_code == 403:
                category = ErrorCategory.AUTHENTICATION
            elif status_code == 422 or status_code == 400:
                category = ErrorCategory.VALIDATION
            elif status_code == 429:
                category = ErrorCategory.RATE_LIMIT
            elif status_code >= 500:
                category = ErrorCategory.SERVER
            elif status_code >= 400:
                category = ErrorCategory.CLIENT

        return category, status_code

    def _decode_sse_data(self, raw_data: str, decode_json: bool = True) -> Any:
        """
        Decode an SSE data field.

        Args:
            raw_data: Raw SSE data payload after line-join
            decode_json: Whether to attempt JSON decoding

        Returns:
            Decoded object or raw string payload
        """
        if not decode_json:
            return raw_data

        if raw_data.strip() == "":
            return raw_data

        try:
            return json.loads(raw_data)
        except Exception:
            return raw_data

    def _parse_sse_event(
        self, raw_lines: List[str], decode_json: bool = True
    ) -> Optional[Dict[str, Any]]:
        """
        Parse a single SSE event block (lines between blank separators).

        Args:
            raw_lines: Raw lines from the SSE stream
            decode_json: Whether to decode JSON payloads automatically

        Returns:
            Parsed event dictionary, or None if event is ignorable.
            Returned event includes a transient ``has_data`` flag used internally.
        """
        if not raw_lines:
            return None

        event_id: Optional[str] = None
        event_name = "message"
        data_lines: List[str] = []
        retry_ms: Optional[int] = None

        for line in raw_lines:
            if line.startswith(":"):
                # SSE comment/keepalive line
                continue

            if ":" in line:
                field, value = line.split(":", 1)
                if value.startswith(" "):
                    value = value[1:]
            else:
                field, value = line, ""

            if field == "event":
                event_name = value or "message"
            elif field == "data":
                data_lines.append(value)
            elif field == "id":
                # Ignore invalid ids per SSE spec guidance
                if "\x00" not in value:
                    event_id = value
            elif field == "retry":
                try:
                    parsed_retry = int(value)
                    if parsed_retry >= 0:
                        retry_ms = parsed_retry
                except (TypeError, ValueError):
                    logger.debug("Ignoring invalid SSE retry value: %s", value)

        has_data = len(data_lines) > 0
        if not has_data and retry_ms is None and event_id is None:
            return None

        raw_data = "\n".join(data_lines)
        return {
            "id": event_id,
            "event": event_name,
            "data": self._decode_sse_data(raw_data, decode_json) if has_data else None,
            "retry": retry_ms,
            "raw_data": raw_data,
            "has_data": has_data,
        }

    def _build_sse_request(
        self,
        endpoint_name: str,
        params: Optional[Dict[str, Any]] = None,
        last_event_id: Optional[str] = None,
    ) -> Dict[str, Any]:
        """
        Build a request dictionary for an SSE endpoint.

        Adds SSE-friendly headers while preserving endpoint/default headers.
        """
        request = self._prepare_request(endpoint_name, params)
        headers = dict(request.get("headers", {}))
        headers.setdefault("Accept", "text/event-stream")
        headers.setdefault("Cache-Control", "no-cache")
        if last_event_id:
            headers["Last-Event-ID"] = last_event_id
        request["headers"] = headers
        return request

    def _build_stream_request(
        self,
        endpoint_name: str,
        params: Optional[Dict[str, Any]] = None,
        resume_from: int = 0,
        extra_headers: Optional[Dict[str, str]] = None,
    ) -> Dict[str, Any]:
        """
        Build a request dictionary for streamed HTTP responses.

        Adds optional resume and caller-provided headers while preserving
        endpoint/default headers.
        """
        request = self._prepare_request(endpoint_name, params)
        headers = dict(request.get("headers", {}))
        if resume_from > 0:
            headers["Range"] = f"bytes={resume_from}-"
        if extra_headers:
            headers.update(extra_headers)
        request["headers"] = headers
        return request

    def _extract_stream_total_bytes(
        self, response: httpx.Response, resume_from: int = 0
    ) -> Optional[int]:
        """Infer the total payload size for a streamed response."""
        content_range = response.headers.get("Content-Range")
        if content_range and "/" in content_range:
            total_part = content_range.rsplit("/", 1)[1].strip()
            if total_part.isdigit():
                return int(total_part)

        content_length = response.headers.get("Content-Length")
        if content_length and content_length.isdigit():
            total = int(content_length)
            if resume_from > 0 and response.status_code == 206:
                return resume_from + total
            return total

        return None

    def _build_stream_progress(
        self,
        endpoint_name: str,
        bytes_processed: int,
        bytes_streamed: int,
        total_bytes: Optional[int],
        chunk_index: int,
        resumed: bool,
        done: bool,
    ) -> Dict[str, Any]:
        """Create a normalized progress payload for streaming callbacks."""
        percent_complete = None
        if total_bytes and total_bytes > 0:
            percent_complete = min(100.0, (bytes_processed / total_bytes) * 100.0)

        return {
            "endpoint": endpoint_name,
            "bytes_processed": bytes_processed,
            "bytes_streamed": bytes_streamed,
            "total_bytes": total_bytes,
            "percent_complete": percent_complete,
            "chunk_index": chunk_index,
            "resumed": resumed,
            "done": done,
        }

    def _raise_stream_error(
        self,
        exc: Exception,
        endpoint_name: str,
        request: Dict[str, Any],
        operation: str,
    ) -> None:
        """Raise an ``ApiLinkerError`` for generic streaming failures."""
        error_category, status_code = self._categorize_error(exc)
        response_body = None
        if hasattr(exc, "response"):
            try:
                response_body = exc.response.text[:1000]
            except Exception:
                response_body = "<Unable to read response body>"

        raise ApiLinkerError(
            message=f"Failed to {operation} from {endpoint_name}: {str(exc)}",
            error_category=error_category,
            status_code=status_code,
            response_body=response_body,
            request_url=str(request.get("url")),
            request_method=request.get("method", "GET"),
            additional_context={"endpoint": endpoint_name, "operation": operation},
        )

    def _raise_sse_error(
        self, exc: Exception, endpoint_name: str, request: Dict[str, Any]
    ) -> None:
        """Raise an ``ApiLinkerError`` for SSE failures with rich context."""
        error_category, status_code = self._categorize_error(exc)
        response_body = None
        if hasattr(exc, "response"):
            try:
                response_body = exc.response.text[:1000]
            except Exception:
                response_body = "<Unable to read response body>"

        raise ApiLinkerError(
            message=f"Failed to stream SSE from {endpoint_name}: {str(exc)}",
            error_category=error_category,
            status_code=status_code,
            response_body=response_body,
            request_url=str(request.get("url")),
            request_method=request.get("method", "GET"),
            additional_context={"endpoint": endpoint_name},
        )

    def stream_sse(
        self,
        endpoint_name: str,
        params: Optional[Dict[str, Any]] = None,
        max_events: Optional[int] = None,
        reconnect: bool = True,
        reconnect_delay: float = 1.0,
        max_reconnect_attempts: Optional[int] = None,
        read_timeout: Optional[float] = None,
        decode_json: bool = True,
    ) -> Generator[Dict[str, Any], None, None]:
        """
        Stream events from an SSE endpoint.

        Supports automatic reconnection, Last-Event-ID resume, and optional
        JSON decoding of event payloads.

        Args:
            endpoint_name: Endpoint key configured in ``self.endpoints``.
            params: Query parameters.
            max_events: Stop after this many dispatched events.
            reconnect: Whether to reconnect on disconnect/error.
            reconnect_delay: Base reconnect delay in seconds.
            max_reconnect_attempts: Maximum reconnect attempts (None = unlimited).
            read_timeout: Per-stream read timeout. Defaults to connector timeout.
            decode_json: Whether to decode JSON payloads automatically.

        Yields:
            Parsed SSE events with keys: ``id``, ``event``, ``data``, ``retry``, ``raw_data``.
        """
        if endpoint_name not in self.endpoints:
            raise ValueError(f"Endpoint '{endpoint_name}' not found in configuration")

        endpoint = self.endpoints[endpoint_name]
        sse_config = endpoint.sse or {}

        if max_events is None and sse_config.get("max_events") is not None:
            max_events = int(sse_config["max_events"])

        reconnect = bool(sse_config.get("reconnect", reconnect))
        reconnect_delay = float(sse_config.get("reconnect_delay", reconnect_delay))

        if (
            max_reconnect_attempts is None
            and sse_config.get("max_reconnect_attempts") is not None
        ):
            max_reconnect_attempts = int(sse_config["max_reconnect_attempts"])

        if read_timeout is None:
            read_timeout = sse_config.get("read_timeout")
        if read_timeout is None:
            read_timeout = self.timeout

        decode_json = bool(sse_config.get("decode_json", decode_json))

        reconnect_attempts = 0
        received_events = 0
        last_event_id: Optional[str] = None
        effective_reconnect_delay = max(0.0, reconnect_delay)

        while True:
            request = self._build_sse_request(endpoint_name, params, last_event_id)
            try:
                # Apply endpoint-level rate limiting before opening/renewing stream
                self.rate_limit_manager.acquire(endpoint_name)

                with self.client.stream(
                    request["method"],
                    request["url"],
                    headers=request["headers"],
                    params=request["params"],
                    json=request.get("json"),
                    timeout=read_timeout,
                ) as response:
                    self.rate_limit_manager.update_from_response(
                        endpoint_name, response
                    )
                    response.raise_for_status()
                    logger.info(
                        "Connected to SSE endpoint: %s (%s %s)",
                        endpoint_name,
                        request["method"],
                        request["url"],
                    )

                    pending_lines: List[str] = []

                    def _dispatch_event(
                        event: Dict[str, Any],
                    ) -> Optional[Dict[str, Any]]:
                        nonlocal effective_reconnect_delay, last_event_id, received_events

                        retry_hint = event.get("retry")
                        if isinstance(retry_hint, int):
                            effective_reconnect_delay = max(
                                0.0, float(retry_hint) / 1000.0
                            )

                        event_id = event.get("id")
                        if event_id:
                            last_event_id = str(event_id)

                        if not event.get("has_data"):
                            # Retry/id-only control blocks are not dispatched
                            return None

                        event.pop("has_data", None)
                        received_events += 1
                        return event

                    for raw_line in response.iter_lines():
                        if raw_line is None:
                            continue

                        line = raw_line.rstrip("\r")

                        if line == "":
                            parsed = self._parse_sse_event(
                                pending_lines, decode_json=decode_json
                            )
                            pending_lines = []

                            if parsed is None:
                                continue

                            event = _dispatch_event(parsed)
                            if event is None:
                                continue

                            yield event
                            if max_events is not None and received_events >= max_events:
                                return
                        else:
                            pending_lines.append(line)

                    # Flush trailing buffered event block on connection close
                    if pending_lines:
                        parsed = self._parse_sse_event(
                            pending_lines, decode_json=decode_json
                        )
                        if parsed is not None:
                            event = _dispatch_event(parsed)
                            if event is not None:
                                yield event
                                if (
                                    max_events is not None
                                    and received_events >= max_events
                                ):
                                    return

            except Exception as exc:
                if not reconnect:
                    self._raise_sse_error(exc, endpoint_name, request)

                reconnect_attempts += 1
                if (
                    max_reconnect_attempts is not None
                    and reconnect_attempts > max_reconnect_attempts
                ):
                    self._raise_sse_error(exc, endpoint_name, request)

                logger.warning(
                    "SSE stream error on endpoint '%s': %s. Reconnecting in %.2fs (attempt %d)",
                    endpoint_name,
                    str(exc),
                    effective_reconnect_delay,
                    reconnect_attempts,
                )
                time.sleep(effective_reconnect_delay)
                continue

            # Reconnect when stream closes naturally, unless disabled.
            if not reconnect:
                return

            reconnect_attempts += 1
            if (
                max_reconnect_attempts is not None
                and reconnect_attempts > max_reconnect_attempts
            ):
                return

            logger.info(
                "SSE stream closed for endpoint '%s'. Reconnecting in %.2fs (attempt %d)",
                endpoint_name,
                effective_reconnect_delay,
                reconnect_attempts,
            )
            time.sleep(effective_reconnect_delay)

    def consume_sse(
        self,
        endpoint_name: str,
        params: Optional[Dict[str, Any]] = None,
        processor: Optional[Callable[[List[Dict[str, Any]]], Any]] = None,
        chunk_size: int = 50,
        max_events: Optional[int] = None,
        backpressure_buffer_size: int = 500,
        drop_policy: str = "block",
        **stream_kwargs: Any,
    ) -> Dict[str, Any]:
        """
        Consume SSE events in chunks with bounded in-memory buffering.

        This method adds chunked processing and explicit backpressure handling:
        - ``drop_policy='block'``: flushes buffer chunks before accepting more data.
        - ``drop_policy='drop_oldest'``: drops oldest buffered events when full.

        Args:
            endpoint_name: Endpoint key configured in ``self.endpoints``.
            params: Query parameters.
            processor: Optional callback invoked with each chunk.
            chunk_size: Number of events per processing chunk.
            max_events: Maximum number of events to consume.
            backpressure_buffer_size: Max in-memory event buffer.
            drop_policy: ``block`` or ``drop_oldest``.
            **stream_kwargs: Extra kwargs forwarded to ``stream_sse``.

        Returns:
            Summary dictionary with processing metrics and chunk results.
        """
        if endpoint_name not in self.endpoints:
            raise ValueError(f"Endpoint '{endpoint_name}' not found in configuration")

        endpoint = self.endpoints[endpoint_name]
        sse_config = endpoint.sse or {}

        if max_events is None and sse_config.get("max_events") is not None:
            max_events = int(sse_config["max_events"])

        chunk_size = int(sse_config.get("chunk_size", chunk_size))
        backpressure_buffer_size = int(
            sse_config.get("backpressure_buffer_size", backpressure_buffer_size)
        )
        drop_policy = str(sse_config.get("drop_policy", drop_policy)).lower()

        if chunk_size <= 0:
            raise ValueError("chunk_size must be > 0")
        if backpressure_buffer_size <= 0:
            raise ValueError("backpressure_buffer_size must be > 0")
        if drop_policy not in {"block", "drop_oldest"}:
            raise ValueError("drop_policy must be either 'block' or 'drop_oldest'")

        buffer: Deque[Dict[str, Any]] = deque(maxlen=backpressure_buffer_size)
        dropped_events = 0
        processed_events = 0
        chunks_processed = 0
        chunk_results: List[Any] = []

        def _flush(force: bool = False) -> bool:
            nonlocal processed_events, chunks_processed
            flushed = False

            while buffer and (force or len(buffer) >= chunk_size):
                current_chunk_size = (
                    chunk_size if len(buffer) >= chunk_size else len(buffer)
                )
                chunk = [buffer.popleft() for _ in range(current_chunk_size)]
                chunks_processed += 1
                processed_events += len(chunk)
                flushed = True

                if processor:
                    chunk_results.append(processor(chunk))
                else:
                    chunk_results.append(chunk)

                # In non-force mode we flush at most one chunk each step.
                if not force:
                    break

            return flushed

        for event in self.stream_sse(
            endpoint_name=endpoint_name,
            params=params,
            max_events=max_events,
            **stream_kwargs,
        ):
            while len(buffer) >= backpressure_buffer_size:
                if drop_policy == "drop_oldest":
                    buffer.popleft()
                    dropped_events += 1
                    break

                # Block strategy: process buffered data before accepting more.
                if not _flush(force=False):
                    _flush(force=True)
                    break

            buffer.append(event)
            _flush(force=False)

        # Process any trailing events.
        _flush(force=True)

        return {
            "success": True,
            "processed_events": processed_events,
            "chunks_processed": chunks_processed,
            "dropped_events": dropped_events,
            "chunk_size": chunk_size,
            "buffer_max_size": backpressure_buffer_size,
            "results": chunk_results,
        }

    def stream_response(
        self,
        endpoint_name: str,
        params: Optional[Dict[str, Any]] = None,
        chunk_size: int = 65536,
        read_timeout: Optional[float] = None,
        progress_callback: Optional[Callable[[Dict[str, Any]], None]] = None,
        resume_from: int = 0,
        extra_headers: Optional[Dict[str, str]] = None,
    ) -> Generator[bytes, None, None]:
        """
        Stream a generic HTTP response in bounded-size chunks.

        This method supports memory-efficient chunk processing, optional
        progress callbacks, and byte-range resume when the upstream API
        supports ``Range`` requests.

        Args:
            endpoint_name: Endpoint key configured in ``self.endpoints``.
            params: Optional query parameters.
            chunk_size: Byte size for each yielded chunk.
            read_timeout: Per-stream read timeout. Defaults to connector timeout.
            progress_callback: Optional callback invoked with progress metadata.
            resume_from: Byte offset to resume from using a ``Range`` request.
            extra_headers: Extra request headers merged into the stream request.

        Yields:
            Raw byte chunks from the response body.
        """
        if endpoint_name not in self.endpoints:
            raise ValueError(f"Endpoint '{endpoint_name}' not found in configuration")

        endpoint = self.endpoints[endpoint_name]
        streaming_config = endpoint.streaming or {}

        chunk_size = int(streaming_config.get("chunk_size", chunk_size))
        if chunk_size <= 0:
            raise ValueError("chunk_size must be > 0")

        resume_from = int(streaming_config.get("resume_from", resume_from))
        if resume_from < 0:
            raise ValueError("resume_from must be >= 0")

        if read_timeout is None:
            read_timeout = streaming_config.get("read_timeout")
        if read_timeout is None:
            read_timeout = self.timeout

        configured_headers = streaming_config.get("headers", {})
        merged_headers = {**configured_headers, **(extra_headers or {})}
        request = self._build_stream_request(
            endpoint_name=endpoint_name,
            params=params,
            resume_from=resume_from,
            extra_headers=merged_headers,
        )

        try:
            self.rate_limit_manager.acquire(endpoint_name)

            with self.client.stream(
                request["method"],
                request["url"],
                headers=request["headers"],
                params=request["params"],
                json=request.get("json"),
                timeout=read_timeout,
            ) as response:
                self.rate_limit_manager.update_from_response(endpoint_name, response)
                response.raise_for_status()

                resumed = resume_from > 0 and response.status_code == 206
                effective_resume_from = resume_from if resumed else 0
                total_bytes = self._extract_stream_total_bytes(
                    response, resume_from=effective_resume_from
                )
                bytes_streamed = 0
                chunk_index = 0

                if progress_callback:
                    progress_callback(
                        self._build_stream_progress(
                            endpoint_name=endpoint_name,
                            bytes_processed=effective_resume_from,
                            bytes_streamed=0,
                            total_bytes=total_bytes,
                            chunk_index=0,
                            resumed=resumed,
                            done=False,
                        )
                    )

                for chunk in response.iter_bytes(chunk_size=chunk_size):
                    if not chunk:
                        continue

                    chunk_index += 1
                    bytes_streamed += len(chunk)

                    if progress_callback:
                        progress_callback(
                            self._build_stream_progress(
                                endpoint_name=endpoint_name,
                                bytes_processed=effective_resume_from + bytes_streamed,
                                bytes_streamed=bytes_streamed,
                                total_bytes=total_bytes,
                                chunk_index=chunk_index,
                                resumed=resumed,
                                done=False,
                            )
                        )

                    yield chunk

                if progress_callback:
                    progress_callback(
                        self._build_stream_progress(
                            endpoint_name=endpoint_name,
                            bytes_processed=effective_resume_from + bytes_streamed,
                            bytes_streamed=bytes_streamed,
                            total_bytes=total_bytes,
                            chunk_index=chunk_index,
                            resumed=resumed,
                            done=True,
                        )
                    )

        except Exception as exc:
            self._raise_stream_error(exc, endpoint_name, request, "stream response")

    def download_stream(
        self,
        endpoint_name: str,
        destination_path: str,
        params: Optional[Dict[str, Any]] = None,
        chunk_size: int = 65536,
        resume: bool = True,
        read_timeout: Optional[float] = None,
        progress_callback: Optional[Callable[[Dict[str, Any]], None]] = None,
        extra_headers: Optional[Dict[str, str]] = None,
    ) -> Dict[str, Any]:
        """
        Download a streamed HTTP response directly to disk.

        Downloads are written incrementally to keep memory usage bounded.
        When ``resume`` is enabled and the destination file already exists,
        ApiLinker will attempt a byte-range request and append only the
        remaining bytes when the upstream API returns ``206 Partial Content``.
        """
        if endpoint_name not in self.endpoints:
            raise ValueError(f"Endpoint '{endpoint_name}' not found in configuration")

        endpoint = self.endpoints[endpoint_name]
        streaming_config = endpoint.streaming or {}

        chunk_size = int(streaming_config.get("chunk_size", chunk_size))
        if chunk_size <= 0:
            raise ValueError("chunk_size must be > 0")

        resume = bool(streaming_config.get("resume", resume))

        if read_timeout is None:
            read_timeout = streaming_config.get("read_timeout")
        if read_timeout is None:
            read_timeout = self.timeout

        configured_headers = streaming_config.get("headers", {})
        merged_headers = {**configured_headers, **(extra_headers or {})}

        destination_dir = os.path.dirname(os.path.abspath(destination_path))
        if destination_dir:
            os.makedirs(destination_dir, exist_ok=True)

        requested_resume_from = (
            os.path.getsize(destination_path)
            if resume and os.path.exists(destination_path)
            else 0
        )

        request = self._build_stream_request(
            endpoint_name=endpoint_name,
            params=params,
            resume_from=requested_resume_from,
            extra_headers=merged_headers,
        )

        try:
            self.rate_limit_manager.acquire(endpoint_name)

            with self.client.stream(
                request["method"],
                request["url"],
                headers=request["headers"],
                params=request["params"],
                json=request.get("json"),
                timeout=read_timeout,
            ) as response:
                self.rate_limit_manager.update_from_response(endpoint_name, response)
                response.raise_for_status()

                resumed = requested_resume_from > 0 and response.status_code == 206
                effective_resume_from = requested_resume_from if resumed else 0
                total_bytes = self._extract_stream_total_bytes(
                    response, resume_from=effective_resume_from
                )
                file_mode = "ab" if resumed else "wb"
                bytes_written = 0
                chunk_index = 0

                if progress_callback:
                    progress_callback(
                        self._build_stream_progress(
                            endpoint_name=endpoint_name,
                            bytes_processed=effective_resume_from,
                            bytes_streamed=0,
                            total_bytes=total_bytes,
                            chunk_index=0,
                            resumed=resumed,
                            done=False,
                        )
                    )

                with open(destination_path, file_mode) as output_file:
                    for chunk in response.iter_bytes(chunk_size=chunk_size):
                        if not chunk:
                            continue

                        output_file.write(chunk)
                        bytes_written += len(chunk)
                        chunk_index += 1

                        if progress_callback:
                            progress_callback(
                                self._build_stream_progress(
                                    endpoint_name=endpoint_name,
                                    bytes_processed=effective_resume_from
                                    + bytes_written,
                                    bytes_streamed=bytes_written,
                                    total_bytes=total_bytes,
                                    chunk_index=chunk_index,
                                    resumed=resumed,
                                    done=False,
                                )
                            )

                if progress_callback:
                    progress_callback(
                        self._build_stream_progress(
                            endpoint_name=endpoint_name,
                            bytes_processed=effective_resume_from + bytes_written,
                            bytes_streamed=bytes_written,
                            total_bytes=total_bytes,
                            chunk_index=chunk_index,
                            resumed=resumed,
                            done=True,
                        )
                    )

                return {
                    "success": True,
                    "path": destination_path,
                    "bytes_written": bytes_written,
                    "total_bytes": total_bytes,
                    "resumed": resumed,
                    "resume_from": effective_resume_from,
                    "chunks_written": chunk_index,
                }

        except Exception as exc:
            self._raise_stream_error(exc, endpoint_name, request, "download stream")

    def fetch_data(
        self, endpoint_name: str, params: Optional[Dict[str, Any]] = None
    ) -> Union[Dict[str, Any], List[Dict[str, Any]]]:
        """
        Fetch data from the specified endpoint.

        Args:
            endpoint_name: Name of the endpoint to use
            params: Additional parameters for the request

        Returns:
            The parsed response data

        Raises:
            ApiLinkerError: On API request failure with enhanced error context
        """
        if endpoint_name not in self.endpoints:
            raise ValueError(f"Endpoint '{endpoint_name}' not found in configuration")

        endpoint = self.endpoints[endpoint_name]
        logger.info(
            f"Fetching data from endpoint: {endpoint_name} ({endpoint.method} {endpoint.path})"
        )

        # Prepare the request
        request = self._prepare_request(endpoint_name, params)

        # Make the request with retries (note: main retries are now handled by the error recovery manager)
        last_exception = None
        for attempt in range(1, self.retry_count + 1):
            try:
                # Apply rate limiting
                self.rate_limit_manager.acquire(endpoint_name)

                response = self.client.request(
                    request["method"],
                    request["url"],
                    headers=request["headers"],
                    params=request["params"],
                    json=request.get("json"),
                )
                response.raise_for_status()

                # Process the response
                result = self._process_response(response, endpoint_name)

                # Handle pagination if configured
                if endpoint.pagination:
                    result = self._handle_pagination(result, endpoint_name, params)

                logger.info(f"Data fetched successfully from {endpoint_name}")
                return result

            except Exception as e:
                last_exception = e
                error_category, status_code = self._categorize_error(e)

                # Log the error at an appropriate level
                if attempt < self.retry_count:
                    wait_time = self.retry_delay * attempt
                    logger.warning(
                        f"Error fetching data (attempt {attempt}/{self.retry_count}): {str(e)}"
                    )
                    logger.info(f"Retrying in {wait_time} seconds...")
                    time.sleep(wait_time)
                else:
                    logger.error(f"All retry attempts failed: {str(e)}")

        # If we get here, all retry attempts failed
        if last_exception:
            error_category, status_code = self._categorize_error(last_exception)

            # Extract response data if available
            response_body = None
            if hasattr(last_exception, "response"):
                try:
                    response_body = last_exception.response.text[:1000]  # Limit size
                except:
                    response_body = "<Unable to read response body>"

            # Create an ApiLinkerError with enhanced context
            raise ApiLinkerError(
                message=f"Failed to fetch data from {endpoint_name}: {str(last_exception)}",
                error_category=error_category,
                status_code=status_code,
                response_body=response_body,
                request_url=str(request["url"]),
                request_method=request["method"],
                additional_context={"endpoint": endpoint_name, "params": params},
            )

        # Should not reach here
        raise ApiLinkerError(
            message=f"Unexpected state fetching data from {endpoint_name}",
            error_category=ErrorCategory.UNKNOWN,
            status_code=0,
        )

    def send_data(
        self, endpoint_name: str, data: Union[Dict[str, Any], List[Dict[str, Any]]]
    ) -> Dict[str, Any]:
        """
        Send data to the specified endpoint.

        Args:
            endpoint_name: Name of the endpoint to use
            data: Data to send

        Returns:
            The parsed response

        Raises:
            ApiLinkerError: On API request failure with enhanced error context
        """
        if endpoint_name not in self.endpoints:
            raise ValueError(f"Endpoint '{endpoint_name}' not found in configuration")

        endpoint = self.endpoints[endpoint_name]
        logger.info(
            f"Sending data to endpoint: {endpoint_name} ({endpoint.method} {endpoint.path})"
        )

        # Prepare the request
        request = self._prepare_request(endpoint_name)

        # Validate single item(s) against request schema if provided
        endpoint = self.endpoints[endpoint_name]
        if endpoint.request_schema and is_validator_available():

            def _validate_item(item: Any) -> None:
                valid, diffs = validate_payload_against_schema(
                    item, endpoint.request_schema
                )
                if not valid:
                    logger.error(
                        "Request schema validation failed for %s\n%s",
                        endpoint_name,
                        pretty_print_diffs(diffs),
                    )
                    raise ApiLinkerError(
                        message="Request failed schema validation",
                        error_category=ErrorCategory.VALIDATION,
                        status_code=0,
                        additional_context={"endpoint": endpoint_name, "diffs": diffs},
                    )

            if isinstance(data, list):
                for item in data:
                    _validate_item(item)
            else:
                _validate_item(data)

        # If data is a list, send each item individually
        if isinstance(data, list):
            results = []
            successful = 0
            failed = 0
            failures = []

            for item_index, item in enumerate(data):
                try:
                    # Apply rate limiting
                    self.rate_limit_manager.acquire(endpoint_name)

                    response = self.client.request(
                        request["method"],
                        request["url"],
                        headers=request["headers"],
                        params=request["params"],
                        json=item,
                    )
                    response.raise_for_status()
                    result = response.json() if response.content else {}
                    results.append(result)
                    successful += 1

                except Exception as e:
                    error_category, status_code = self._categorize_error(e)

                    # Extract response data if available
                    response_body = None
                    if hasattr(e, "response"):
                        try:
                            response_body = e.response.text[:1000]  # Limit size
                        except:
                            response_body = "<Unable to read response body>"

                    error = ApiLinkerError(
                        message=f"Failed to send data item {item_index} to {endpoint_name}: {str(e)}",
                        error_category=error_category,
                        status_code=status_code,
                        response_body=response_body,
                        request_url=str(request["url"]),
                        request_method=request["method"],
                        additional_context={
                            "endpoint": endpoint_name,
                            "item_index": item_index,
                        },
                    )
                    failures.append(error.to_dict())
                    logger.error(f"Error sending data item {item_index}: {error}")
                    failed += 1

            logger.info(f"Sent {successful} items successfully, {failed} failed")
            return {
                "success": successful > 0 and failed == 0,
                "sent_count": successful,
                "failed_count": failed,
                "results": results,
                "failures": failures,
            }

        # If data is a single item, send it
        else:
            # Make the request with retries (note: main retries now handled by error recovery manager)
            last_exception = None

            for attempt in range(1, self.retry_count + 1):
                try:
                    # Apply rate limiting
                    self.rate_limit_manager.acquire(endpoint_name)

                    response = self.client.request(
                        request["method"],
                        request["url"],
                        headers=request["headers"],
                        params=request["params"],
                        json=data,
                    )
                    response.raise_for_status()
                    result = response.json() if response.content else {}

                    logger.info(f"Data sent successfully to {endpoint_name}")
                    return {
                        "success": True,
                        "result": result,
                    }

                except Exception as e:
                    last_exception = e

                    # Log the error at an appropriate level
                    if attempt < self.retry_count:
                        wait_time = self.retry_delay * attempt
                        logger.warning(
                            f"Error sending data (attempt {attempt}/{self.retry_count}): {str(e)}"
                        )
                        logger.info(f"Retrying in {wait_time} seconds...")
                        time.sleep(wait_time)
                    else:
                        logger.error(f"All retry attempts failed: {str(e)}")

            # If we get here, all retry attempts failed
            if last_exception:
                error_category, status_code = self._categorize_error(last_exception)

                # Extract response data if available
                response_body = None
                if hasattr(last_exception, "response"):
                    try:
                        response_body = last_exception.response.text[
                            :1000
                        ]  # Limit size
                    except:
                        response_body = "<Unable to read response body>"

                # Create an ApiLinkerError with enhanced context
                raise ApiLinkerError(
                    message=f"Failed to send data to {endpoint_name}: {str(last_exception)}",
                    error_category=error_category,
                    status_code=status_code,
                    response_body=response_body,
                    request_url=str(request["url"]),
                    request_method=request["method"],
                    additional_context={"endpoint": endpoint_name},
                )

            # This should not be reached
            return {"success": False, "error": "Unknown error"}

    def check_health(self) -> HealthCheckResult:
        """
        Check the health of the API connection.

        Returns:
            HealthCheckResult indicating the status.
        """
        start_time = time.time()
        try:
            # Try to hit the base URL or a specific health endpoint if we had one configured
            # For now, just check if we can connect to the base URL
            response = self.client.get("/", timeout=5.0)

            latency = (time.time() - start_time) * 1000

            status = HealthStatus.HEALTHY
            message = f"Connected to {self.base_url}"

            # If we get a 5xx error, the server is definitely having issues
            if response.status_code >= 500:
                status = HealthStatus.UNHEALTHY
                message = f"Server returned {response.status_code}"

            return HealthCheckResult(
                status=status,
                component=f"connector:{self.base_url}",
                message=message,
                latency_ms=latency,
                details={"status_code": response.status_code},
            )

        except Exception as e:
            latency = (time.time() - start_time) * 1000
            return HealthCheckResult(
                status=HealthStatus.UNHEALTHY,
                component=f"connector:{self.base_url}",
                message=str(e),
                latency_ms=latency,
            )

__init__(connector_type, base_url, auth_config=None, endpoints=None, timeout=30, retry_count=3, retry_delay=1, default_headers=None, **kwargs)

Source code in apilinker/core/connector.py
def __init__(
    self,
    connector_type: str,
    base_url: str,
    auth_config: Optional[AuthConfig] = None,
    endpoints: Optional[Dict[str, Dict[str, Any]]] = None,
    timeout: int = 30,
    retry_count: int = 3,
    retry_delay: int = 1,
    default_headers: Optional[Dict[str, str]] = None,
    **kwargs: Any,
) -> None:
    self.connector_type = connector_type
    self.base_url = base_url
    self.auth_config = auth_config
    self.timeout = timeout
    self.retry_count = retry_count
    self.retry_delay = retry_delay

    # Default headers (may be provided via explicit parameter or legacy 'headers' kwarg)
    if default_headers is None and "headers" in kwargs:
        try:
            default_headers = dict(kwargs.pop("headers"))
        except Exception:
            default_headers = None
    self.default_headers: Dict[str, str] = default_headers or {}
    # Provide a backwards-compatible attribute name used by some connectors
    self.headers: Dict[str, str] = self.default_headers

    # Parse and store endpoint configurations
    self.endpoints: Dict[str, EndpointConfig] = {}
    if endpoints:
        for name, config in endpoints.items():
            self.endpoints[name] = EndpointConfig(**config)

    # Store additional settings
    self.settings: Dict[str, Any] = kwargs

    # Create HTTP client with default settings
    self.client = self._create_client()

    # Initialize Rate Limit Manager
    self.rate_limit_manager = RateLimitManager()

    # Configure rate limiters for endpoints
    for name, config in self.endpoints.items():
        if config.rate_limit:
            self.rate_limit_manager.create_limiter(name, config.rate_limit)

    logger.debug(f"Initialized {connector_type} connector for {base_url}")

fetch_data(endpoint_name, params=None)

Fetch data from the specified endpoint.

Parameters:

Name Type Description Default
endpoint_name str

Name of the endpoint to use

required
params Optional[Dict[str, Any]]

Additional parameters for the request

None

Returns:

Type Description
Union[Dict[str, Any], List[Dict[str, Any]]]

The parsed response data

Raises:

Type Description
ApiLinkerError

On API request failure with enhanced error context

Source code in apilinker/core/connector.py
def fetch_data(
    self, endpoint_name: str, params: Optional[Dict[str, Any]] = None
) -> Union[Dict[str, Any], List[Dict[str, Any]]]:
    """
    Fetch data from the specified endpoint.

    Args:
        endpoint_name: Name of the endpoint to use
        params: Additional parameters for the request

    Returns:
        The parsed response data

    Raises:
        ApiLinkerError: On API request failure with enhanced error context
    """
    if endpoint_name not in self.endpoints:
        raise ValueError(f"Endpoint '{endpoint_name}' not found in configuration")

    endpoint = self.endpoints[endpoint_name]
    logger.info(
        f"Fetching data from endpoint: {endpoint_name} ({endpoint.method} {endpoint.path})"
    )

    # Prepare the request
    request = self._prepare_request(endpoint_name, params)

    # Make the request with retries (note: main retries are now handled by the error recovery manager)
    last_exception = None
    for attempt in range(1, self.retry_count + 1):
        try:
            # Apply rate limiting
            self.rate_limit_manager.acquire(endpoint_name)

            response = self.client.request(
                request["method"],
                request["url"],
                headers=request["headers"],
                params=request["params"],
                json=request.get("json"),
            )
            response.raise_for_status()

            # Process the response
            result = self._process_response(response, endpoint_name)

            # Handle pagination if configured
            if endpoint.pagination:
                result = self._handle_pagination(result, endpoint_name, params)

            logger.info(f"Data fetched successfully from {endpoint_name}")
            return result

        except Exception as e:
            last_exception = e
            error_category, status_code = self._categorize_error(e)

            # Log the error at an appropriate level
            if attempt < self.retry_count:
                wait_time = self.retry_delay * attempt
                logger.warning(
                    f"Error fetching data (attempt {attempt}/{self.retry_count}): {str(e)}"
                )
                logger.info(f"Retrying in {wait_time} seconds...")
                time.sleep(wait_time)
            else:
                logger.error(f"All retry attempts failed: {str(e)}")

    # If we get here, all retry attempts failed
    if last_exception:
        error_category, status_code = self._categorize_error(last_exception)

        # Extract response data if available
        response_body = None
        if hasattr(last_exception, "response"):
            try:
                response_body = last_exception.response.text[:1000]  # Limit size
            except:
                response_body = "<Unable to read response body>"

        # Create an ApiLinkerError with enhanced context
        raise ApiLinkerError(
            message=f"Failed to fetch data from {endpoint_name}: {str(last_exception)}",
            error_category=error_category,
            status_code=status_code,
            response_body=response_body,
            request_url=str(request["url"]),
            request_method=request["method"],
            additional_context={"endpoint": endpoint_name, "params": params},
        )

    # Should not reach here
    raise ApiLinkerError(
        message=f"Unexpected state fetching data from {endpoint_name}",
        error_category=ErrorCategory.UNKNOWN,
        status_code=0,
    )

send_data(endpoint_name, data)

Send data to the specified endpoint.

Parameters:

Name Type Description Default
endpoint_name str

Name of the endpoint to use

required
data Union[Dict[str, Any], List[Dict[str, Any]]]

Data to send

required

Returns:

Type Description
Dict[str, Any]

The parsed response

Raises:

Type Description
ApiLinkerError

On API request failure with enhanced error context

Source code in apilinker/core/connector.py
def send_data(
    self, endpoint_name: str, data: Union[Dict[str, Any], List[Dict[str, Any]]]
) -> Dict[str, Any]:
    """
    Send data to the specified endpoint.

    Args:
        endpoint_name: Name of the endpoint to use
        data: Data to send

    Returns:
        The parsed response

    Raises:
        ApiLinkerError: On API request failure with enhanced error context
    """
    if endpoint_name not in self.endpoints:
        raise ValueError(f"Endpoint '{endpoint_name}' not found in configuration")

    endpoint = self.endpoints[endpoint_name]
    logger.info(
        f"Sending data to endpoint: {endpoint_name} ({endpoint.method} {endpoint.path})"
    )

    # Prepare the request
    request = self._prepare_request(endpoint_name)

    # Validate single item(s) against request schema if provided
    endpoint = self.endpoints[endpoint_name]
    if endpoint.request_schema and is_validator_available():

        def _validate_item(item: Any) -> None:
            valid, diffs = validate_payload_against_schema(
                item, endpoint.request_schema
            )
            if not valid:
                logger.error(
                    "Request schema validation failed for %s\n%s",
                    endpoint_name,
                    pretty_print_diffs(diffs),
                )
                raise ApiLinkerError(
                    message="Request failed schema validation",
                    error_category=ErrorCategory.VALIDATION,
                    status_code=0,
                    additional_context={"endpoint": endpoint_name, "diffs": diffs},
                )

        if isinstance(data, list):
            for item in data:
                _validate_item(item)
        else:
            _validate_item(data)

    # If data is a list, send each item individually
    if isinstance(data, list):
        results = []
        successful = 0
        failed = 0
        failures = []

        for item_index, item in enumerate(data):
            try:
                # Apply rate limiting
                self.rate_limit_manager.acquire(endpoint_name)

                response = self.client.request(
                    request["method"],
                    request["url"],
                    headers=request["headers"],
                    params=request["params"],
                    json=item,
                )
                response.raise_for_status()
                result = response.json() if response.content else {}
                results.append(result)
                successful += 1

            except Exception as e:
                error_category, status_code = self._categorize_error(e)

                # Extract response data if available
                response_body = None
                if hasattr(e, "response"):
                    try:
                        response_body = e.response.text[:1000]  # Limit size
                    except:
                        response_body = "<Unable to read response body>"

                error = ApiLinkerError(
                    message=f"Failed to send data item {item_index} to {endpoint_name}: {str(e)}",
                    error_category=error_category,
                    status_code=status_code,
                    response_body=response_body,
                    request_url=str(request["url"]),
                    request_method=request["method"],
                    additional_context={
                        "endpoint": endpoint_name,
                        "item_index": item_index,
                    },
                )
                failures.append(error.to_dict())
                logger.error(f"Error sending data item {item_index}: {error}")
                failed += 1

        logger.info(f"Sent {successful} items successfully, {failed} failed")
        return {
            "success": successful > 0 and failed == 0,
            "sent_count": successful,
            "failed_count": failed,
            "results": results,
            "failures": failures,
        }

    # If data is a single item, send it
    else:
        # Make the request with retries (note: main retries now handled by error recovery manager)
        last_exception = None

        for attempt in range(1, self.retry_count + 1):
            try:
                # Apply rate limiting
                self.rate_limit_manager.acquire(endpoint_name)

                response = self.client.request(
                    request["method"],
                    request["url"],
                    headers=request["headers"],
                    params=request["params"],
                    json=data,
                )
                response.raise_for_status()
                result = response.json() if response.content else {}

                logger.info(f"Data sent successfully to {endpoint_name}")
                return {
                    "success": True,
                    "result": result,
                }

            except Exception as e:
                last_exception = e

                # Log the error at an appropriate level
                if attempt < self.retry_count:
                    wait_time = self.retry_delay * attempt
                    logger.warning(
                        f"Error sending data (attempt {attempt}/{self.retry_count}): {str(e)}"
                    )
                    logger.info(f"Retrying in {wait_time} seconds...")
                    time.sleep(wait_time)
                else:
                    logger.error(f"All retry attempts failed: {str(e)}")

        # If we get here, all retry attempts failed
        if last_exception:
            error_category, status_code = self._categorize_error(last_exception)

            # Extract response data if available
            response_body = None
            if hasattr(last_exception, "response"):
                try:
                    response_body = last_exception.response.text[
                        :1000
                    ]  # Limit size
                except:
                    response_body = "<Unable to read response body>"

            # Create an ApiLinkerError with enhanced context
            raise ApiLinkerError(
                message=f"Failed to send data to {endpoint_name}: {str(last_exception)}",
                error_category=error_category,
                status_code=status_code,
                response_body=response_body,
                request_url=str(request["url"]),
                request_method=request["method"],
                additional_context={"endpoint": endpoint_name},
            )

        # This should not be reached
        return {"success": False, "error": "Unknown error"}

stream_sse(endpoint_name, params=None, max_events=None, reconnect=True, reconnect_delay=1.0, max_reconnect_attempts=None, read_timeout=None, decode_json=True)

Stream events from an SSE endpoint.

Supports automatic reconnection, Last-Event-ID resume, and optional JSON decoding of event payloads.

Parameters:

Name Type Description Default
endpoint_name str

Endpoint key configured in self.endpoints.

required
params Optional[Dict[str, Any]]

Query parameters.

None
max_events Optional[int]

Stop after this many dispatched events.

None
reconnect bool

Whether to reconnect on disconnect/error.

True
reconnect_delay float

Base reconnect delay in seconds.

1.0
max_reconnect_attempts Optional[int]

Maximum reconnect attempts (None = unlimited).

None
read_timeout Optional[float]

Per-stream read timeout. Defaults to connector timeout.

None
decode_json bool

Whether to decode JSON payloads automatically.

True

Yields:

Type Description
Dict[str, Any]

Parsed SSE events with keys: id, event, data, retry, raw_data.

Source code in apilinker/core/connector.py
def stream_sse(
    self,
    endpoint_name: str,
    params: Optional[Dict[str, Any]] = None,
    max_events: Optional[int] = None,
    reconnect: bool = True,
    reconnect_delay: float = 1.0,
    max_reconnect_attempts: Optional[int] = None,
    read_timeout: Optional[float] = None,
    decode_json: bool = True,
) -> Generator[Dict[str, Any], None, None]:
    """
    Stream events from an SSE endpoint.

    Supports automatic reconnection, Last-Event-ID resume, and optional
    JSON decoding of event payloads.

    Args:
        endpoint_name: Endpoint key configured in ``self.endpoints``.
        params: Query parameters.
        max_events: Stop after this many dispatched events.
        reconnect: Whether to reconnect on disconnect/error.
        reconnect_delay: Base reconnect delay in seconds.
        max_reconnect_attempts: Maximum reconnect attempts (None = unlimited).
        read_timeout: Per-stream read timeout. Defaults to connector timeout.
        decode_json: Whether to decode JSON payloads automatically.

    Yields:
        Parsed SSE events with keys: ``id``, ``event``, ``data``, ``retry``, ``raw_data``.
    """
    if endpoint_name not in self.endpoints:
        raise ValueError(f"Endpoint '{endpoint_name}' not found in configuration")

    endpoint = self.endpoints[endpoint_name]
    sse_config = endpoint.sse or {}

    if max_events is None and sse_config.get("max_events") is not None:
        max_events = int(sse_config["max_events"])

    reconnect = bool(sse_config.get("reconnect", reconnect))
    reconnect_delay = float(sse_config.get("reconnect_delay", reconnect_delay))

    if (
        max_reconnect_attempts is None
        and sse_config.get("max_reconnect_attempts") is not None
    ):
        max_reconnect_attempts = int(sse_config["max_reconnect_attempts"])

    if read_timeout is None:
        read_timeout = sse_config.get("read_timeout")
    if read_timeout is None:
        read_timeout = self.timeout

    decode_json = bool(sse_config.get("decode_json", decode_json))

    reconnect_attempts = 0
    received_events = 0
    last_event_id: Optional[str] = None
    effective_reconnect_delay = max(0.0, reconnect_delay)

    while True:
        request = self._build_sse_request(endpoint_name, params, last_event_id)
        try:
            # Apply endpoint-level rate limiting before opening/renewing stream
            self.rate_limit_manager.acquire(endpoint_name)

            with self.client.stream(
                request["method"],
                request["url"],
                headers=request["headers"],
                params=request["params"],
                json=request.get("json"),
                timeout=read_timeout,
            ) as response:
                self.rate_limit_manager.update_from_response(
                    endpoint_name, response
                )
                response.raise_for_status()
                logger.info(
                    "Connected to SSE endpoint: %s (%s %s)",
                    endpoint_name,
                    request["method"],
                    request["url"],
                )

                pending_lines: List[str] = []

                def _dispatch_event(
                    event: Dict[str, Any],
                ) -> Optional[Dict[str, Any]]:
                    nonlocal effective_reconnect_delay, last_event_id, received_events

                    retry_hint = event.get("retry")
                    if isinstance(retry_hint, int):
                        effective_reconnect_delay = max(
                            0.0, float(retry_hint) / 1000.0
                        )

                    event_id = event.get("id")
                    if event_id:
                        last_event_id = str(event_id)

                    if not event.get("has_data"):
                        # Retry/id-only control blocks are not dispatched
                        return None

                    event.pop("has_data", None)
                    received_events += 1
                    return event

                for raw_line in response.iter_lines():
                    if raw_line is None:
                        continue

                    line = raw_line.rstrip("\r")

                    if line == "":
                        parsed = self._parse_sse_event(
                            pending_lines, decode_json=decode_json
                        )
                        pending_lines = []

                        if parsed is None:
                            continue

                        event = _dispatch_event(parsed)
                        if event is None:
                            continue

                        yield event
                        if max_events is not None and received_events >= max_events:
                            return
                    else:
                        pending_lines.append(line)

                # Flush trailing buffered event block on connection close
                if pending_lines:
                    parsed = self._parse_sse_event(
                        pending_lines, decode_json=decode_json
                    )
                    if parsed is not None:
                        event = _dispatch_event(parsed)
                        if event is not None:
                            yield event
                            if (
                                max_events is not None
                                and received_events >= max_events
                            ):
                                return

        except Exception as exc:
            if not reconnect:
                self._raise_sse_error(exc, endpoint_name, request)

            reconnect_attempts += 1
            if (
                max_reconnect_attempts is not None
                and reconnect_attempts > max_reconnect_attempts
            ):
                self._raise_sse_error(exc, endpoint_name, request)

            logger.warning(
                "SSE stream error on endpoint '%s': %s. Reconnecting in %.2fs (attempt %d)",
                endpoint_name,
                str(exc),
                effective_reconnect_delay,
                reconnect_attempts,
            )
            time.sleep(effective_reconnect_delay)
            continue

        # Reconnect when stream closes naturally, unless disabled.
        if not reconnect:
            return

        reconnect_attempts += 1
        if (
            max_reconnect_attempts is not None
            and reconnect_attempts > max_reconnect_attempts
        ):
            return

        logger.info(
            "SSE stream closed for endpoint '%s'. Reconnecting in %.2fs (attempt %d)",
            endpoint_name,
            effective_reconnect_delay,
            reconnect_attempts,
        )
        time.sleep(effective_reconnect_delay)

consume_sse(endpoint_name, params=None, processor=None, chunk_size=50, max_events=None, backpressure_buffer_size=500, drop_policy='block', **stream_kwargs)

Consume SSE events in chunks with bounded in-memory buffering.

This method adds chunked processing and explicit backpressure handling: - drop_policy='block': flushes buffer chunks before accepting more data. - drop_policy='drop_oldest': drops oldest buffered events when full.

Parameters:

Name Type Description Default
endpoint_name str

Endpoint key configured in self.endpoints.

required
params Optional[Dict[str, Any]]

Query parameters.

None
processor Optional[Callable[[List[Dict[str, Any]]], Any]]

Optional callback invoked with each chunk.

None
chunk_size int

Number of events per processing chunk.

50
max_events Optional[int]

Maximum number of events to consume.

None
backpressure_buffer_size int

Max in-memory event buffer.

500
drop_policy str

block or drop_oldest.

'block'
**stream_kwargs Any

Extra kwargs forwarded to stream_sse.

{}

Returns:

Type Description
Dict[str, Any]

Summary dictionary with processing metrics and chunk results.

Source code in apilinker/core/connector.py
def consume_sse(
    self,
    endpoint_name: str,
    params: Optional[Dict[str, Any]] = None,
    processor: Optional[Callable[[List[Dict[str, Any]]], Any]] = None,
    chunk_size: int = 50,
    max_events: Optional[int] = None,
    backpressure_buffer_size: int = 500,
    drop_policy: str = "block",
    **stream_kwargs: Any,
) -> Dict[str, Any]:
    """
    Consume SSE events in chunks with bounded in-memory buffering.

    This method adds chunked processing and explicit backpressure handling:
    - ``drop_policy='block'``: flushes buffer chunks before accepting more data.
    - ``drop_policy='drop_oldest'``: drops oldest buffered events when full.

    Args:
        endpoint_name: Endpoint key configured in ``self.endpoints``.
        params: Query parameters.
        processor: Optional callback invoked with each chunk.
        chunk_size: Number of events per processing chunk.
        max_events: Maximum number of events to consume.
        backpressure_buffer_size: Max in-memory event buffer.
        drop_policy: ``block`` or ``drop_oldest``.
        **stream_kwargs: Extra kwargs forwarded to ``stream_sse``.

    Returns:
        Summary dictionary with processing metrics and chunk results.
    """
    if endpoint_name not in self.endpoints:
        raise ValueError(f"Endpoint '{endpoint_name}' not found in configuration")

    endpoint = self.endpoints[endpoint_name]
    sse_config = endpoint.sse or {}

    if max_events is None and sse_config.get("max_events") is not None:
        max_events = int(sse_config["max_events"])

    chunk_size = int(sse_config.get("chunk_size", chunk_size))
    backpressure_buffer_size = int(
        sse_config.get("backpressure_buffer_size", backpressure_buffer_size)
    )
    drop_policy = str(sse_config.get("drop_policy", drop_policy)).lower()

    if chunk_size <= 0:
        raise ValueError("chunk_size must be > 0")
    if backpressure_buffer_size <= 0:
        raise ValueError("backpressure_buffer_size must be > 0")
    if drop_policy not in {"block", "drop_oldest"}:
        raise ValueError("drop_policy must be either 'block' or 'drop_oldest'")

    buffer: Deque[Dict[str, Any]] = deque(maxlen=backpressure_buffer_size)
    dropped_events = 0
    processed_events = 0
    chunks_processed = 0
    chunk_results: List[Any] = []

    def _flush(force: bool = False) -> bool:
        nonlocal processed_events, chunks_processed
        flushed = False

        while buffer and (force or len(buffer) >= chunk_size):
            current_chunk_size = (
                chunk_size if len(buffer) >= chunk_size else len(buffer)
            )
            chunk = [buffer.popleft() for _ in range(current_chunk_size)]
            chunks_processed += 1
            processed_events += len(chunk)
            flushed = True

            if processor:
                chunk_results.append(processor(chunk))
            else:
                chunk_results.append(chunk)

            # In non-force mode we flush at most one chunk each step.
            if not force:
                break

        return flushed

    for event in self.stream_sse(
        endpoint_name=endpoint_name,
        params=params,
        max_events=max_events,
        **stream_kwargs,
    ):
        while len(buffer) >= backpressure_buffer_size:
            if drop_policy == "drop_oldest":
                buffer.popleft()
                dropped_events += 1
                break

            # Block strategy: process buffered data before accepting more.
            if not _flush(force=False):
                _flush(force=True)
                break

        buffer.append(event)
        _flush(force=False)

    # Process any trailing events.
    _flush(force=True)

    return {
        "success": True,
        "processed_events": processed_events,
        "chunks_processed": chunks_processed,
        "dropped_events": dropped_events,
        "chunk_size": chunk_size,
        "buffer_max_size": backpressure_buffer_size,
        "results": chunk_results,
    }

check_health()

Check the health of the API connection.

Returns:

Type Description
HealthCheckResult

HealthCheckResult indicating the status.

Source code in apilinker/core/connector.py
def check_health(self) -> HealthCheckResult:
    """
    Check the health of the API connection.

    Returns:
        HealthCheckResult indicating the status.
    """
    start_time = time.time()
    try:
        # Try to hit the base URL or a specific health endpoint if we had one configured
        # For now, just check if we can connect to the base URL
        response = self.client.get("/", timeout=5.0)

        latency = (time.time() - start_time) * 1000

        status = HealthStatus.HEALTHY
        message = f"Connected to {self.base_url}"

        # If we get a 5xx error, the server is definitely having issues
        if response.status_code >= 500:
            status = HealthStatus.UNHEALTHY
            message = f"Server returned {response.status_code}"

        return HealthCheckResult(
            status=status,
            component=f"connector:{self.base_url}",
            message=message,
            latency_ms=latency,
            details={"status_code": response.status_code},
        )

    except Exception as e:
        latency = (time.time() - start_time) * 1000
        return HealthCheckResult(
            status=HealthStatus.UNHEALTHY,
            component=f"connector:{self.base_url}",
            message=str(e),
            latency_ms=latency,
        )

FieldMapper

Data transformation and field mapping engine.

apilinker.core.mapper.FieldMapper

Maps fields between source and target APIs, including transformations.

This class handles the mapping of fields from source to target format, including nested fields, transformations, and filtering.

Source code in apilinker/core/mapper.py
 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
class FieldMapper:
    """
    Maps fields between source and target APIs, including transformations.

    This class handles the mapping of fields from source to target format,
    including nested fields, transformations, and filtering.
    """

    def __init__(self) -> None:
        self.mappings: List[Dict[str, Any]] = []
        self.transformers: Dict[str, Callable] = self._register_built_in_transformers()
        logger.debug("Initialized FieldMapper")

    def _register_built_in_transformers(self) -> Dict[str, Callable]:
        """Register built-in transformation functions."""
        return {
            # Date/time transformations
            "iso_to_timestamp": lambda v: (
                int(datetime.fromisoformat(v.replace("Z", "+00:00")).timestamp())
                if v
                else None
            ),
            "timestamp_to_iso": lambda v: (
                datetime.fromtimestamp(int(v)).isoformat() if v else None
            ),
            # String transformations
            "lowercase": lambda v: v.lower() if v else None,
            "uppercase": lambda v: v.upper() if v else None,
            "strip": lambda v: v.strip() if v else None,
            # Type conversions
            "to_string": lambda v: str(v) if v is not None else "",
            "to_int": lambda v: int(float(v)) if v else 0,
            "to_float": lambda v: float(v) if v else 0.0,
            "to_bool": lambda v: bool(v) if v is not None else False,
            # Null handling
            "default_empty_string": lambda v: v if v is not None else "",
            "default_zero": lambda v: v if v is not None else 0,
            "none_if_empty": lambda v: v if v else None,
        }

    def register_transformer(self, name: str, func: Callable) -> None:
        """
        Register a custom transformation function.

        Args:
            name: Name of the transformer
            func: Function that performs the transformation
        """
        if name in self.transformers:
            logger.warning(f"Overwriting existing transformer: {name}")
        self.transformers[name] = func
        logger.debug(f"Registered transformer: {name}")

    def transform(self, value: Any, transformer: Union[str, Dict[str, Any]]) -> Any:
        """
        Convenience wrapper to apply a single transformer to a value.

        Args:
            value: Input value
            transformer: Transformer name or transformer dict {name, params}

        Returns:
            Transformed value
        """
        return self.apply_transform(value, transformer)

    def load_custom_transformer(
        self, module_path: str, function_name: str, alias: Optional[str] = None
    ) -> None:
        """
        Load a custom transformer function from a Python module.

        Args:
            module_path: Import path for the module
            function_name: Name of the function in the module
            alias: Optional alternative name to register the transformer under
        """
        try:
            module = importlib.import_module(module_path)
            func = getattr(module, function_name)

            # Register with the provided alias or the original function name
            name = alias or function_name
            self.register_transformer(name, func)
            logger.info(
                f"Loaded custom transformer from {module_path}.{function_name} as {name}"
            )

        except (ImportError, AttributeError) as e:
            logger.error(f"Error loading custom transformer: {str(e)}")
            raise ValueError(
                f"Failed to load transformer from {module_path}.{function_name}: {str(e)}"
            )

    def add_mapping(
        self, source: str, target: str, fields: List[Dict[str, Any]]
    ) -> None:
        """
        Add a field mapping between source and target endpoints.

        Args:
            source: Source endpoint name
            target: Target endpoint name
            fields: List of field mappings (dicts with source, target, and optional transform)
        """
        # Validate that required fields are present
        for field in fields:
            if "source" not in field or "target" not in field:
                raise ValueError(
                    "Field mapping must contain 'source' and 'target' keys"
                )

        self.mappings.append({"source": source, "target": target, "fields": fields})
        logger.debug(
            f"Added mapping from {source} to {target} with {len(fields)} fields"
        )

    def get_mappings(self) -> List[Dict[str, Any]]:
        """Get all defined mappings."""
        return self.mappings

    def get_first_mapping(self) -> Optional[Dict[str, Any]]:
        """Get the first mapping if any exists."""
        return self.mappings[0] if self.mappings else None

    def get_value_from_path(self, data: Dict[str, Any], path: str) -> Any:
        """
        Extract a value from nested dictionary using dot notation.

        Args:
            data: Source data dictionary
            path: Path to the value using dot notation (e.g., "user.address.city")

        Returns:
            The value at the specified path or None if not found
        """
        if not path:
            return data

        # Handle array indexing in path (e.g., "items[0].name")
        parts: List[Union[str, int]] = []
        current_part = ""
        i = 0
        while i < len(path):
            if path[i] == "[":
                if current_part:
                    parts.append(current_part)
                    current_part = ""

                # Extract the array index
                i += 1
                index_str = ""
                while i < len(path) and path[i] != "]":
                    index_str += path[i]
                    i += 1

                # Add the index as a separate part
                if index_str.isdigit():
                    parts.append(int(index_str))
                i += 1  # Skip the closing bracket
            elif path[i] == ".":
                if current_part:
                    parts.append(current_part)
                    current_part = ""
                i += 1
            else:
                current_part += path[i]
                i += 1

        if current_part:
            parts.append(current_part)

        # Navigate through the path
        current: Any = data
        for part in parts:
            if isinstance(current, dict) and isinstance(part, str):
                if part in current:
                    current = current[part]
                else:
                    return None
            elif isinstance(current, list) and isinstance(part, int):
                if 0 <= part < len(current):
                    current = current[part]
                else:
                    return None
            else:
                return None

        return current

    def set_value_at_path(self, data: Dict[str, Any], path: str, value: Any) -> None:
        """
        Set a value in a nested dictionary using dot notation.

        Args:
            data: Target data dictionary
            path: Path where to set the value using dot notation
            value: Value to set
        """
        if not path:
            return

        parts = path.split(".")

        # Navigate to the parent of the leaf node
        current = data
        for i, part in enumerate(parts[:-1]):
            if part not in current:
                current[part] = {}
            current = current[part]

        # Set the value at the leaf node
        current[parts[-1]] = value

    def apply_transform(
        self,
        value: Any,
        transform: Union[str, List[str], Dict[str, Any]],
        params: Dict[str, Any] = None,
    ) -> Any:
        """
        Apply a transformation to a value.

        Args:
            value: The value to transform
            transform: The transformation to apply (string name or list of transforms)
            params: Optional parameters for the transformer

        Returns:
            Transformed value
        """
        # Handle None values
        if value is None:
            # Special case transformers that handle None
            if transform == "default_empty_string":
                return ""
            elif transform == "default_zero":
                return 0
            else:
                return None

        # Handle empty params
        if params is None:
            params = {}

        # Handle list of transformations
        if isinstance(transform, list):
            result = value
            for t in transform:
                result = self.apply_transform(result, t)
            return result

        # Handle transformation with parameters
        if isinstance(transform, dict):
            name = transform.get("name")
            transform_params = transform.get("params", {})

            if not name or name not in self.transformers:
                logger.warning(f"Unknown transformer: {name}")
                return value

            return self.transformers[name](value, **transform_params)

        # Simple string transformer name
        if transform not in self.transformers:
            logger.warning(f"Unknown transformer: {transform}")
            return value

        # Special handling for list inputs with certain transforms
        if isinstance(value, list) and transform in ["lowercase", "uppercase", "strip"]:
            return [
                self.transformers[transform](item) if isinstance(item, str) else item
                for item in value
            ]

        # Apply the transformation with parameters if provided
        if params:
            return self.transformers[transform](value, **params)
        else:
            return self.transformers[transform](value)

    def map_data(
        self,
        source_endpoint: str,
        target_endpoint: str,
        data: Union[Dict[str, Any], List[Dict[str, Any]]],
    ) -> Union[Dict[str, Any], List[Dict[str, Any]]]:
        """
        Map data from source format to target format.

        Args:
            source_endpoint: Source endpoint name
            target_endpoint: Target endpoint name
            data: Data to map

        Returns:
            Mapped data in target format
        """
        # Find the appropriate mapping
        mapping = None
        for m in self.mappings:
            if m["source"] == source_endpoint and m["target"] == target_endpoint:
                mapping = m
                break

        if not mapping:
            logger.warning(
                f"No mapping found for {source_endpoint} to {target_endpoint}"
            )
            return data

        logger.debug(f"Mapping data using {len(mapping['fields'])} field mappings")

        # Handle list of items
        if isinstance(data, list):
            return [self._map_item(item, mapping["fields"]) for item in data]

        # Handle single item
        return self._map_item(data, mapping["fields"])

    def _map_item(
        self, item: Dict[str, Any], fields: List[Dict[str, Any]]
    ) -> Dict[str, Any]:
        """
        Map a single data item according to field mappings.

        Args:
            item: Source data item
            fields: Field mapping configurations

        Returns:
            Mapped data item
        """
        return self.map_fields(item, fields)

    def map_fields(
        self, item: Dict[str, Any], fields: List[Dict[str, Any]]
    ) -> Dict[str, Any]:
        """
        Apply a list of field mappings to a single item.

        This is the item-level counterpart to ``map_data`` and reuses the
        same field mapping semantics for callers that need projection without
        registering a source/target mapping pair first.
        """
        result: Dict[str, Any] = {}

        for field in fields:
            source_path = field["source"]
            target_path = field["target"]

            # Get source value
            source_value = self.get_value_from_path(item, source_path)

            # Apply transformation if specified
            if "transform" in field and field["transform"]:
                transform = field["transform"]
                if isinstance(transform, str):
                    # Single transformation
                    source_value = self.apply_transform(source_value, transform)
                elif isinstance(transform, list):
                    # Multiple transformations in sequence
                    for t in transform:
                        source_value = self.apply_transform(source_value, t)
                else:
                    logger.warning(f"Unknown transform format: {transform}")

            # Check conditions if specified
            if "condition" in field:
                condition = field["condition"]
                if condition.get("field"):
                    condition_value = self.get_value_from_path(item, condition["field"])
                    operator = condition.get("operator", "eq")
                    compare_value = condition.get("value")

                    skip = False
                    if operator == "eq" and condition_value != compare_value:
                        skip = True
                    elif operator == "ne" and condition_value == compare_value:
                        skip = True
                    elif operator == "gt" and not (condition_value > compare_value):
                        skip = True
                    elif operator == "lt" and not (condition_value < compare_value):
                        skip = True
                    elif operator == "exists" and condition_value is None:
                        skip = True
                    elif operator == "not_exists" and condition_value is not None:
                        skip = True

                    if skip:
                        continue

            # Set value in result
            if source_value is not None or field.get("include_nulls", False):
                self.set_value_at_path(result, target_path, source_value)

        return result

add_mapping(source, target, fields)

Add a field mapping between source and target endpoints.

Parameters:

Name Type Description Default
source str

Source endpoint name

required
target str

Target endpoint name

required
fields List[Dict[str, Any]]

List of field mappings (dicts with source, target, and optional transform)

required
Source code in apilinker/core/mapper.py
def add_mapping(
    self, source: str, target: str, fields: List[Dict[str, Any]]
) -> None:
    """
    Add a field mapping between source and target endpoints.

    Args:
        source: Source endpoint name
        target: Target endpoint name
        fields: List of field mappings (dicts with source, target, and optional transform)
    """
    # Validate that required fields are present
    for field in fields:
        if "source" not in field or "target" not in field:
            raise ValueError(
                "Field mapping must contain 'source' and 'target' keys"
            )

    self.mappings.append({"source": source, "target": target, "fields": fields})
    logger.debug(
        f"Added mapping from {source} to {target} with {len(fields)} fields"
    )

transform(value, transformer)

Convenience wrapper to apply a single transformer to a value.

Parameters:

Name Type Description Default
value Any

Input value

required
transformer Union[str, Dict[str, Any]]

Transformer name or transformer dict {name, params}

required

Returns:

Type Description
Any

Transformed value

Source code in apilinker/core/mapper.py
def transform(self, value: Any, transformer: Union[str, Dict[str, Any]]) -> Any:
    """
    Convenience wrapper to apply a single transformer to a value.

    Args:
        value: Input value
        transformer: Transformer name or transformer dict {name, params}

    Returns:
        Transformed value
    """
    return self.apply_transform(value, transformer)

register_transformer(name, func)

Register a custom transformation function.

Parameters:

Name Type Description Default
name str

Name of the transformer

required
func Callable

Function that performs the transformation

required
Source code in apilinker/core/mapper.py
def register_transformer(self, name: str, func: Callable) -> None:
    """
    Register a custom transformation function.

    Args:
        name: Name of the transformer
        func: Function that performs the transformation
    """
    if name in self.transformers:
        logger.warning(f"Overwriting existing transformer: {name}")
    self.transformers[name] = func
    logger.debug(f"Registered transformer: {name}")

Monitoring & Alerting

System monitoring and health checks.

apilinker.core.monitoring.MonitoringManager

Manages health checks and alerts.

Source code in apilinker/core/monitoring.py
class MonitoringManager:
    """
    Manages health checks and alerts.
    """

    def __init__(self):
        self.integrations: List[AlertIntegration] = []
        self.rules: List[AlertRule] = []
        self.alert_history: List[Alert] = []
        self.health_checks: Dict[str, Callable[[], Union[bool, HealthCheckResult]]] = {}

    def add_integration(self, integration: AlertIntegration):
        """Add an alert integration."""
        self.integrations.append(integration)

    def add_rule(self, rule: AlertRule):
        """Add an alert rule."""
        self.rules.append(rule)

    def register_health_check(
        self, component: str, check_func: Callable[[], Union[bool, HealthCheckResult]]
    ) -> None:
        """Register a health check function for a component."""
        self.health_checks[component] = check_func

    def run_health_checks(self) -> Dict[str, HealthCheckResult]:
        """Run all registered health checks."""
        results: Dict[str, HealthCheckResult] = {}
        context: Dict[str, Any] = {}

        for component, check_func in self.health_checks.items():
            try:
                start_time = time.time()
                result = check_func()
                latency = (time.time() - start_time) * 1000

                if isinstance(result, bool):
                    status = HealthStatus.HEALTHY if result else HealthStatus.UNHEALTHY
                    message = "OK" if result else "Check failed"
                    details: Dict[str, Any] = {}
                else:
                    # result is HealthCheckResult
                    status = result.status
                    message = result.message
                    details = result.details
                    # Use the latency from the result if provided, or the measured one
                    if result.latency_ms > 0:
                        latency = result.latency_ms

                results[component] = HealthCheckResult(
                    status=status,
                    component=component,
                    message=message,
                    latency_ms=latency,
                    details=details,
                )
                context[f"{component}_status"] = status
                context[f"{component}_latency_ms"] = latency

            except Exception as e:
                logger.error(f"Health check failed for {component}: {e}")
                results[component] = HealthCheckResult(
                    status=HealthStatus.UNHEALTHY,
                    component=component,
                    message=str(e),
                    latency_ms=0.0,
                )
                context[f"{component}_status"] = HealthStatus.UNHEALTHY

        # Evaluate alert rules
        self._evaluate_rules(context)

        return results

    def _evaluate_rules(self, context: Dict[str, Any]):
        """Evaluate all alert rules against the current context."""
        for rule in self.rules:
            if rule.should_trigger(context):
                alert = Alert(
                    id=f"{rule.name}_{int(time.time())}",
                    rule_name=rule.name,
                    severity=rule.severity,
                    message=f"Alert rule '{rule.name}' triggered",
                    details=context,
                )
                self._trigger_alert(alert)

    def _trigger_alert(self, alert: Alert):
        """Trigger an alert across all integrations."""
        logger.warning(f"Triggering alert: {alert.rule_name} - {alert.message}")
        self.alert_history.append(alert)

        # Deduplication check (simple version: check if same rule triggered recently)
        # Note: Real deduplication is complex, this is a basic implementation

        for integration in self.integrations:
            integration.send_alert(alert)

    def get_alert_history(self, limit: int = 100) -> List[Alert]:
        """Get the history of triggered alerts."""
        return sorted(self.alert_history, key=lambda x: x.timestamp, reverse=True)[
            :limit
        ]

__init__()

Source code in apilinker/core/monitoring.py
def __init__(self):
    self.integrations: List[AlertIntegration] = []
    self.rules: List[AlertRule] = []
    self.alert_history: List[Alert] = []
    self.health_checks: Dict[str, Callable[[], Union[bool, HealthCheckResult]]] = {}

register_health_check(component, check_func)

Register a health check function for a component.

Source code in apilinker/core/monitoring.py
def register_health_check(
    self, component: str, check_func: Callable[[], Union[bool, HealthCheckResult]]
) -> None:
    """Register a health check function for a component."""
    self.health_checks[component] = check_func

add_rule(rule)

Add an alert rule.

Source code in apilinker/core/monitoring.py
def add_rule(self, rule: AlertRule):
    """Add an alert rule."""
    self.rules.append(rule)

add_integration(integration)

Add an alert integration.

Source code in apilinker/core/monitoring.py
def add_integration(self, integration: AlertIntegration):
    """Add an alert integration."""
    self.integrations.append(integration)

run_health_checks()

Run all registered health checks.

Source code in apilinker/core/monitoring.py
def run_health_checks(self) -> Dict[str, HealthCheckResult]:
    """Run all registered health checks."""
    results: Dict[str, HealthCheckResult] = {}
    context: Dict[str, Any] = {}

    for component, check_func in self.health_checks.items():
        try:
            start_time = time.time()
            result = check_func()
            latency = (time.time() - start_time) * 1000

            if isinstance(result, bool):
                status = HealthStatus.HEALTHY if result else HealthStatus.UNHEALTHY
                message = "OK" if result else "Check failed"
                details: Dict[str, Any] = {}
            else:
                # result is HealthCheckResult
                status = result.status
                message = result.message
                details = result.details
                # Use the latency from the result if provided, or the measured one
                if result.latency_ms > 0:
                    latency = result.latency_ms

            results[component] = HealthCheckResult(
                status=status,
                component=component,
                message=message,
                latency_ms=latency,
                details=details,
            )
            context[f"{component}_status"] = status
            context[f"{component}_latency_ms"] = latency

        except Exception as e:
            logger.error(f"Health check failed for {component}: {e}")
            results[component] = HealthCheckResult(
                status=HealthStatus.UNHEALTHY,
                component=component,
                message=str(e),
                latency_ms=0.0,
            )
            context[f"{component}_status"] = HealthStatus.UNHEALTHY

    # Evaluate alert rules
    self._evaluate_rules(context)

    return results

get_alert_history(limit=100)

Get the history of triggered alerts.

Source code in apilinker/core/monitoring.py
def get_alert_history(self, limit: int = 100) -> List[Alert]:
    """Get the history of triggered alerts."""
    return sorted(self.alert_history, key=lambda x: x.timestamp, reverse=True)[
        :limit
    ]

Research Connectors

For research connector documentation, see Research Connectors Guide.

Available Connectors

  • NCBIConnector: PubMed and GenBank
  • ArXivConnector: arXiv preprints
  • CrossRefConnector: Citation data
  • SemanticScholarConnector: AI-powered search
  • PubChemConnector: Chemical compounds
  • ORCIDConnector: Researcher profiles
  • GitHubConnector: Code repositories
  • NASAConnector: Earth/space data
  • SSEConnector: Real-time Server-Sent Events streams