atlan-application-sdk-api 3.55.1__tar.gz → 3.55.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/PKG-INFO +1 -1
  2. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/clients/sql.py +215 -1
  3. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/common/aws_utils.py +6 -0
  4. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/constants.py +220 -27
  5. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/contracts/base.py +7 -0
  6. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/version.py +1 -1
  7. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/pyproject.toml +1 -1
  8. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/.gitignore +0 -0
  9. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/README.md +0 -0
  10. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/api-files.txt +0 -0
  11. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/__init__.py +0 -0
  12. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/_build_info.py +0 -0
  13. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/_context_errors.py +0 -0
  14. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/_install.py +0 -0
  15. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/_logging.py +0 -0
  16. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/_runtime/__init__.py +0 -0
  17. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/_runtime/cgroup.py +0 -0
  18. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/_runtime/offload.py +0 -0
  19. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/_runtime/progress.py +0 -0
  20. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/clients/__init__.py +0 -0
  21. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/clients/_interface.py +0 -0
  22. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/clients/_sql_failure_classifier.py +0 -0
  23. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/clients/base.py +0 -0
  24. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/clients/http_errors.py +0 -0
  25. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/clients/models.py +0 -0
  26. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/clients/sql_errors.py +0 -0
  27. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/clients/sql_typecasters.py +0 -0
  28. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/clients/ssl_utils.py +0 -0
  29. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/common/__init__.py +0 -0
  30. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/common/_generated_tree.py +0 -0
  31. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/common/_listing.py +0 -0
  32. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/common/aws_utils_errors.py +0 -0
  33. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/common/backoff.py +0 -0
  34. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/common/build_identity.py +0 -0
  35. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/common/concurrency.py +0 -0
  36. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/common/errors.py +0 -0
  37. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/common/filter_matching.py +0 -0
  38. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/common/logger.py +0 -0
  39. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/common/models.py +0 -0
  40. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/common/sql_filters.py +0 -0
  41. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/common/sql_filters_errors.py +0 -0
  42. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/common/task_queue.py +0 -0
  43. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/common/types.py +0 -0
  44. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/common/utils.py +0 -0
  45. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/contracts/__init__.py +0 -0
  46. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/contracts/events.py +0 -0
  47. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/contracts/types.py +0 -0
  48. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/contracts/types_errors.py +0 -0
  49. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/credentials/__init__.py +0 -0
  50. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/credentials/errors.py +0 -0
  51. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/credentials/extra.py +0 -0
  52. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/credentials/ingress.py +0 -0
  53. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/credentials/ref.py +0 -0
  54. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/credentials/requirements.py +0 -0
  55. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/credentials/spec.py +0 -0
  56. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/credentials/types.py +0 -0
  57. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/credentials/utils.py +0 -0
  58. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/errors/__init__.py +0 -0
  59. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/errors/base.py +0 -0
  60. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/errors/categories.py +0 -0
  61. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/errors/http.py +0 -0
  62. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/errors/leaves.py +0 -0
  63. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/errors/wire.py +0 -0
  64. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/handler/__init__.py +0 -0
  65. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/handler/_dispatch.py +0 -0
  66. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/handler/_warmup.py +0 -0
  67. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/handler/asgi.py +0 -0
  68. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/handler/base.py +0 -0
  69. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/handler/context.py +0 -0
  70. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/handler/contracts.py +0 -0
  71. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/handler/manifest.py +0 -0
  72. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/handler/metadata_routes.py +0 -0
  73. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/handler/object_routes.py +0 -0
  74. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/handler/request_contract.py +0 -0
  75. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/handler/routes.py +0 -0
  76. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/handler/service_errors.py +0 -0
  77. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/server/__init__.py +0 -0
  78. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/server/fastapi/models.py +0 -0
  79. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/templates/__init__.py +0 -0
  80. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/templates/contracts/__init__.py +0 -0
  81. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/templates/contracts/base_metadata_extraction.py +0 -0
  82. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/templates/contracts/incremental_sql.py +0 -0
  83. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/templates/contracts/sql_metadata.py +0 -0
  84. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/application_sdk/templates/contracts/sql_query.py +0 -0
  85. {atlan_application_sdk_api-3.55.1 → atlan_application_sdk_api-3.55.3}/hatch_build.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: atlan-application-sdk-api
3
- Version: 3.55.1
3
+ Version: 3.55.3
4
4
  Summary: Experimental: the handler surface of the Atlan Application SDK, for the consolidated API host
5
5
  Project-URL: Homepage, https://github.com/atlanhq/application-sdk
6
6
  Project-URL: Source, https://github.com/atlanhq/application-sdk/tree/main/packages/api
@@ -15,6 +15,7 @@ import hashlib
15
15
  import math
16
16
  import re
17
17
  import threading
18
+ import time
18
19
  from collections.abc import AsyncIterator, Callable, Iterator, Mapping
19
20
  from dataclasses import dataclass
20
21
  from decimal import Decimal
@@ -50,6 +51,7 @@ from application_sdk.clients.sql_errors import (
50
51
  )
51
52
  from application_sdk.clients.sql_typecasters import install_tolerant_text_decoder_hook
52
53
  from application_sdk.common.aws_utils import (
54
+ _RDS_AUTH_TOKEN_REFRESH_SECONDS,
53
55
  _sts_deadline,
54
56
  generate_aws_rds_token_with_iam_role,
55
57
  generate_aws_rds_token_with_iam_user,
@@ -153,7 +155,7 @@ def _bound_params(
153
155
  if TYPE_CHECKING:
154
156
  import pandas as pd
155
157
  from sqlalchemy.engine import URL, Connection
156
- from sqlalchemy.engine.interfaces import DBAPICursor, ExecutionContext
158
+ from sqlalchemy.engine.interfaces import DBAPICursor, Dialect, ExecutionContext
157
159
  from sqlalchemy.ext.asyncio import AsyncConnection, AsyncEngine
158
160
  from sqlalchemy.orm import Session
159
161
 
@@ -453,6 +455,195 @@ def _cap_next_connect_timeout(
453
455
  event.listen(engine, "do_connect", _cap, once=True)
454
456
 
455
457
 
458
+ #: ``authType`` values whose password is a short-lived RDS IAM auth token.
459
+ _IAM_TOKEN_AUTH_TYPES = frozenset({"iam_user", "iam_role"})
460
+
461
+
462
+ class _FreshIamToken:
463
+ """``do_connect`` listener: give every new connection an unexpired RDS IAM token.
464
+
465
+ The engine's URL holds the token generated in ``load()``, and RDS accepts it
466
+ for new connections for only 15 minutes. Any connect after that — a second
467
+ pooled connection, a reconnect after pre-ping or after a cancelled read
468
+ invalidated the connection — would fail auth. Once the token is
469
+ ``_RDS_AUTH_TOKEN_REFRESH_SECONDS`` old, the connection string is built
470
+ again through ``build`` (the client's ``get_sqlalchemy_connection_string``,
471
+ so a connector's override is honoured), and every driver argument it
472
+ changes is swapped into the connect. Only arguments still as the engine's
473
+ URL set them are swapped: a ``connect_args`` value or another listener's
474
+ change is kept.
475
+
476
+ Arguments are compared through the dialect's own ``create_connect_args``,
477
+ so the token reaches the driver under whatever keyword it takes
478
+ (``password``, ``passwd``) without naming one here.
479
+
480
+ ``build`` blocks (for IAM-role auth it runs an STS ``AssumeRole``). A sync
481
+ engine connects on a worker thread, so it is called there. An async
482
+ engine's connect runs on the event loop, inside SQLAlchemy's greenlet;
483
+ with ``on_loop`` the build is offloaded through ``run_in_thread`` and
484
+ awaited from that greenlet, so the loop stays free while STS answers.
485
+
486
+ One refresh runs at a time: a connect that finds one in flight waits for
487
+ it instead of calling STS again. The lock guards only the listener's
488
+ state and is never held while waiting, so a connect on the loop cannot
489
+ block it. A failed build propagates out of the connect that ran it,
490
+ already typed; a connect that was waiting on it then tries itself.
491
+ """
492
+
493
+ def __init__(
494
+ self,
495
+ build: Callable[[], str],
496
+ connection_string: str,
497
+ issued_at: float,
498
+ *,
499
+ on_loop: bool = False,
500
+ clock: Callable[[], float] = time.monotonic,
501
+ ) -> None:
502
+ from sqlalchemy.engine import make_url # noqa: PLC0415 — optional dep: sqlalchemy
503
+
504
+ self._build = build
505
+ self._on_loop = on_loop
506
+ self._clock = clock
507
+ self._lock = threading.Lock()
508
+ self._engine_url = make_url(connection_string)
509
+ self._issued_at = issued_at
510
+ #: The refresh in flight, if any; connects that find it wait on it.
511
+ self._refreshing: concurrent.futures.Future[None] | None = None
512
+ #: Positional and keyword driver arguments to swap in, by the URL that
513
+ #: last refreshed them; empty while the engine's own token is fresh.
514
+ self._cargs: dict[int, Any] = {}
515
+ self._cparams: dict[str, Any] = {}
516
+ #: The engine URL's own driver arguments, which a swap must still find.
517
+ self._baseline: tuple[list[Any], dict[str, Any]] = ([], {})
518
+
519
+ def _built_connection_string(self) -> str:
520
+ if not self._on_loop:
521
+ return self._build()
522
+ from sqlalchemy.util import ( # noqa: PLC0415 — optional dep: sqlalchemy
523
+ await_only,
524
+ )
525
+
526
+ return await_only(run_in_thread(self._build))
527
+
528
+ def _wait(self, refreshing: "concurrent.futures.Future[None]") -> None:
529
+ if not self._on_loop:
530
+ refreshing.result()
531
+ return
532
+ from sqlalchemy.util import ( # noqa: PLC0415 — optional dep: sqlalchemy
533
+ await_only,
534
+ )
535
+
536
+ # Shielded: wrap_future passes a cancel through to the wrapped future,
537
+ # so a cancelled waiter would cancel the refresh every other connect
538
+ # shares, and the owner's set_result would then raise.
539
+ await_only(asyncio.shield(asyncio.wrap_future(refreshing)))
540
+
541
+ def _stale(self) -> bool:
542
+ with self._lock:
543
+ return self._clock() - self._issued_at >= _RDS_AUTH_TOKEN_REFRESH_SECONDS
544
+
545
+ def _refresh(self, dialect: "Dialect") -> None:
546
+ """Rebuild the token, or wait for the refresh another connect started.
547
+
548
+ A failed build raises here, out of the connect that ran it.
549
+ """
550
+ from sqlalchemy.engine import make_url # noqa: PLC0415 — optional dep: sqlalchemy
551
+
552
+ with self._lock:
553
+ refreshing = self._refreshing
554
+ if refreshing is None:
555
+ refreshing = self._refreshing = concurrent.futures.Future()
556
+ owner = True
557
+ else:
558
+ owner = False
559
+ if not owner:
560
+ self._wait(refreshing)
561
+ return
562
+ try:
563
+ # Taken before the build, so the token's age is never understated.
564
+ issued_at = self._clock()
565
+ fresh = make_url(self._built_connection_string())
566
+ old_args, old_params = dialect.create_connect_args(self._engine_url)
567
+ new_args, new_params = dialect.create_connect_args(fresh)
568
+ with self._lock:
569
+ self._cargs = {
570
+ i: new
571
+ for i, (old, new) in enumerate(zip(old_args, new_args))
572
+ if old != new
573
+ }
574
+ self._cparams = {
575
+ key: value
576
+ for key, value in new_params.items()
577
+ if old_params.get(key, _MISSING) != value
578
+ }
579
+ self._baseline = (list(old_args), dict(old_params))
580
+ self._issued_at = issued_at
581
+ logger.debug("Refreshed the RDS IAM auth token for new connections")
582
+ finally:
583
+ # Released whether or not the build succeeded: a waiter re-checks
584
+ # the token's age, and refreshes itself if this one failed or was
585
+ # cancelled, rather than inheriting another connect's error.
586
+ with self._lock:
587
+ self._refreshing = None
588
+ refreshing.set_result(None)
589
+
590
+ def __call__(
591
+ self,
592
+ dialect: "Dialect",
593
+ conn_rec: object,
594
+ cargs: list[Any],
595
+ cparams: dict[str, Any],
596
+ ) -> None:
597
+ while self._stale():
598
+ self._refresh(dialect)
599
+ with self._lock:
600
+ swap_args, swap_params = self._cargs, self._cparams
601
+ old_args, old_params = self._baseline
602
+ for i, value in swap_args.items():
603
+ if i < len(cargs) and cargs[i] == old_args[i]:
604
+ cargs[i] = value
605
+ for key, value in swap_params.items():
606
+ if cparams.get(key, _MISSING) == old_params.get(key, _MISSING):
607
+ cparams[key] = value
608
+
609
+
610
+ #: Stands in for an absent driver argument, which no real value equals.
611
+ _MISSING = object()
612
+
613
+
614
+ def _install_iam_token_refresh(
615
+ engine: object,
616
+ client: "BaseSQLClient",
617
+ connection_string: str,
618
+ issued_at: float,
619
+ *,
620
+ on_loop: bool = False,
621
+ ) -> None:
622
+ """Refresh ``engine``'s RDS IAM token on new connections, for IAM auth only.
623
+
624
+ ``engine`` is a sync Engine (an async engine's ``sync_engine``, with
625
+ ``on_loop``: its connects run on the event loop); anything else, such as
626
+ a test double, is left alone, as is every other ``authType``.
627
+ """
628
+ from sqlalchemy import event # noqa: PLC0415 — optional dep: sqlalchemy
629
+ from sqlalchemy.engine import Engine # noqa: PLC0415 — optional dep: sqlalchemy
630
+
631
+ if not isinstance(engine, Engine):
632
+ return
633
+ if client.credentials.get("authType") not in _IAM_TOKEN_AUTH_TYPES:
634
+ return
635
+ event.listen(
636
+ engine,
637
+ "do_connect",
638
+ _FreshIamToken(
639
+ client.get_sqlalchemy_connection_string,
640
+ connection_string,
641
+ issued_at,
642
+ on_loop=on_loop,
643
+ ),
644
+ )
645
+
646
+
456
647
  def _budget_left(budget: asyncio.Timeout) -> float:
457
648
  """Seconds until ``budget`` expires, measured on the running loop's clock."""
458
649
  return cast(float, budget.when()) - asyncio.get_running_loop().time()
@@ -569,6 +760,7 @@ class BaseSQLClient(ClientInterface):
569
760
  # a network round trip that would otherwise block the loop.
570
761
  # Cancelling the await does not stop the thread, so the STS
571
762
  # call is fitted into the budget too.
763
+ issued_at = time.monotonic()
572
764
  with _sts_deadline(_budget_left(budget)):
573
765
  connection_string = await run_in_thread(
574
766
  self.get_sqlalchemy_connection_string
@@ -593,6 +785,11 @@ class BaseSQLClient(ClientInterface):
593
785
  # see sql_typecasters for why. Tracking: WARE-970, CONAT-767.
594
786
  install_tolerant_text_decoder_hook(self.engine)
595
787
 
788
+ # The URL's IAM token expires; later connects need a fresh one.
789
+ _install_iam_token_refresh(
790
+ self.engine, self, connection_string, issued_at
791
+ )
792
+
596
793
  # Test connection briefly to validate credentials.
597
794
  # Wrapped in run_in_thread because SQLAlchemy's synchronous
598
795
  # engine.connect() blocks the event loop — critical for Temporal
@@ -827,6 +1024,13 @@ class BaseSQLClient(ClientInterface):
827
1024
  parameters and credentials. It handles different authentication methods
828
1025
  and includes necessary connection parameters.
829
1026
 
1027
+ For ``authType`` ``iam_user`` and ``iam_role`` this is called again
1028
+ after ``load()``, each time the RDS IAM token it put in the URL is
1029
+ about to expire and a new connection is opened. It always runs on a
1030
+ worker thread, never the event loop, but not necessarily the one
1031
+ ``load()`` used. An override must therefore be safe to call repeatedly
1032
+ and from any thread, and return a fresh token each time.
1033
+
830
1034
  Returns:
831
1035
  str: Complete SQLAlchemy connection string.
832
1036
 
@@ -1249,6 +1453,7 @@ class AsyncBaseSQLClient(BaseSQLClient):
1249
1453
  # a network round trip that would otherwise block the loop.
1250
1454
  # Cancelling the await does not stop the thread, so the STS
1251
1455
  # call is fitted into the budget too.
1456
+ issued_at = time.monotonic()
1252
1457
  with _sts_deadline(_budget_left(budget)):
1253
1458
  connection_string = await run_in_thread(
1254
1459
  self.get_sqlalchemy_connection_string
@@ -1269,6 +1474,15 @@ class AsyncBaseSQLClient(BaseSQLClient):
1269
1474
  # engines surface DBAPI events on the underlying sync_engine.
1270
1475
  install_tolerant_text_decoder_hook(self.engine.sync_engine)
1271
1476
 
1477
+ # The URL's IAM token expires; later connects need a fresh one.
1478
+ _install_iam_token_refresh(
1479
+ self.engine.sync_engine,
1480
+ self,
1481
+ connection_string,
1482
+ issued_at,
1483
+ on_loop=True,
1484
+ )
1485
+
1272
1486
  # Test connection briefly to validate credentials
1273
1487
  async with self.engine.connect() as _:
1274
1488
  pass # Connection test successful
@@ -39,6 +39,12 @@ _STS_MAX_ATTEMPTS = 2
39
39
  #: some socket layers, the opposite of what an expired deadline wants.
40
40
  _STS_MIN_TIMEOUT_SECONDS = 1.0
41
41
 
42
+ #: Age at which an RDS IAM auth token is replaced before the next new
43
+ #: connection. RDS accepts a token for new connections for 15 minutes after it
44
+ #: is generated; refreshing at 10 leaves room for the time spent building it
45
+ #: and for clock skew. An open connection is unaffected by its token expiring.
46
+ _RDS_AUTH_TOKEN_REFRESH_SECONDS = 10 * 60.0
47
+
42
48
  #: ``time.monotonic()`` by which an STS call made in this context must finish,
43
49
  #: or None for the fixed bounds above. A context variable rather than a
44
50
  #: parameter so it reaches ``AssumeRole`` through any connector's override of
@@ -54,6 +54,7 @@ Example:
54
54
  import math
55
55
  import os
56
56
  import warnings
57
+ from dataclasses import dataclass
57
58
  from enum import Enum
58
59
 
59
60
  import httpx
@@ -261,17 +262,195 @@ TEMPORAL_PROMETHEUS_BIND_ADDRESS = os.getenv(
261
262
  TEMPORAL_CORE_METRICS_PROXY_TIMEOUT_SECONDS: float = float(
262
263
  os.getenv("ATLAN_TEMPORAL_CORE_METRICS_PROXY_TIMEOUT_SECONDS", "5.0")
263
264
  )
264
- #: Upper bound on the bytes read from the loopback metrics endpoint when
265
- #: reading sdk-core's poller gauge for diagnostics. The endpoint is local and
266
- #: diagnostics-only, but a high-cardinality or misbehaving exporter could
267
- #: otherwise make the observer allocate an unbounded string every interval.
268
- #: Oversize is treated as unknown (``None``), never as zero. ~1 MiB is far
269
- #: above a healthy exposition (~460 series) and far below anything that could
270
- #: pressure the worker.
265
+ #: Upper bound on the bytes read from the loopback metrics endpoint by every
266
+ #: reader of it: the worker's poller-gauge diagnostic, the combined-mode
267
+ #: FastAPI ``/metrics`` proxy and the worker's ``TemporalCoreCollector``
268
+ #: (Pushgateway). A high-cardinality or misbehaving exporter could otherwise
269
+ #: make each reader allocate an unbounded body on every interval, scrape or
270
+ #: push. Oversize is treated as unknown — the diagnostic reports ``None``
271
+ #: (never zero), the proxy serves ``/metrics`` without core series and counts
272
+ #: ``reason="oversize"``, the collector skips the cycle. ~1 MiB is far above a
273
+ #: healthy exposition (~460 series) and far below anything that could
274
+ #: pressure the process.
271
275
  TEMPORAL_CORE_METRICS_MAX_BYTES: int = int(
272
276
  os.getenv("ATLAN_TEMPORAL_CORE_METRICS_MAX_BYTES", str(1024 * 1024))
273
277
  )
274
278
 
279
+ # Shutdown budget
280
+ #: Delay before initiating worker shutdown after receiving a termination signal.
281
+ #: This gives the event loop time to flush in-flight activity completions
282
+ #: (e.g. RespondActivityTaskFailed/Completed RPCs) that are already queued
283
+ #: but haven't been sent yet. Without this, a SIGTERM that arrives right
284
+ #: after an activity fails can preempt the _run_activity coroutine before
285
+ #: it reaches complete_activity_task(), leaving the SDK with a phantom
286
+ #: "in-use" task slot that blocks shutdown for the entire
287
+ #: graceful_shutdown_timeout.
288
+ SHUTDOWN_DRAIN_DELAY_SECONDS = int(os.getenv("ATLAN_SHUTDOWN_DRAIN_DELAY_SECONDS", 5))
289
+
290
+ #: Env var naming the pod's ``terminationGracePeriodSeconds``. The Downward API
291
+ #: cannot expose that field, so the chart sets this from the same value.
292
+ SHUTDOWN_GRACE_SECONDS_ENV = "ATLAN_SHUTDOWN_GRACE_SECONDS"
293
+
294
+ # Defaults used when no grace is declared — the bounds every deployment ran
295
+ # with before the budget existed. They are also the caps on a derived budget.
296
+ _DEFAULT_DRAIN_SECONDS = 3600
297
+ _DEFAULT_POST_DRAIN_SECONDS = 120
298
+ _DEFAULT_PUSHGATEWAY_HTTP_TIMEOUT_SECONDS = 10.0
299
+ _DEFAULT_PUSHGATEWAY_SHUTDOWN_DELETE_DELAY_SECONDS = 35.0
300
+ # Headroom kept back from the grace for what runs after the Python process
301
+ # exits: the entrypoint stops daprd for up to DAPR_STOP_TIMEOUT_SECONDS (30 s).
302
+ _SHUTDOWN_HEADROOM_CAP_SECONDS = 30
303
+ # The least the drain ever leaves for the steps after it, so the observability
304
+ # flush (10 s bound) still has a chance when the drain takes almost the whole
305
+ # grace.
306
+ _MIN_SHUTDOWN_TAIL_SECONDS = 10
307
+ # Read here as well as in ExecutionSettings because the tail after the drain is
308
+ # whatever the drain leaves; an explicit drain changes that remainder.
309
+ _DRAIN_ENV = "TEMPORAL_GRACEFUL_SHUTDOWN_TIMEOUT"
310
+
311
+
312
+ @dataclass(frozen=True)
313
+ class ShutdownBudget:
314
+ """Every shutdown bound, derived from one grace period.
315
+
316
+ A graceful stop runs, in order: the drain delay
317
+ (:data:`SHUTDOWN_DRAIN_DELAY_SECONDS`), the Temporal drain
318
+ (``drain_seconds``), then everything after the drain under one deadline
319
+ (``post_drain_seconds``) — the Pushgateway final push, pre-DELETE hold and
320
+ DELETE, closing infrastructure, the observability flush and interpreter exit
321
+ hooks. ``headroom_seconds`` is left for daprd's stop after the process exits.
322
+
323
+ The drain comes first. In-flight activities are the only step whose loss is
324
+ not best-effort, and daprd stays up for the whole drain (the entrypoint only
325
+ stops it after Python exits), so activities keep Dapr access to the end.
326
+ The steps after the drain take what is left.
327
+ """
328
+
329
+ grace_seconds: int
330
+ drain_seconds: int
331
+ post_drain_seconds: int
332
+ headroom_seconds: int
333
+ pushgateway_http_timeout_seconds: float
334
+ pushgateway_shutdown_delete_delay_seconds: float
335
+
336
+
337
+ def derive_shutdown_budget(
338
+ grace_seconds: int,
339
+ drain_delay_seconds: float = SHUTDOWN_DRAIN_DELAY_SECONDS,
340
+ preferred_drain_seconds: int = _DEFAULT_DRAIN_SECONDS,
341
+ ) -> ShutdownBudget:
342
+ """Split a pod grace period into the bounds each shutdown step gets, drain first.
343
+
344
+ The tail after the drain would ideally get a post-drain deadline of a
345
+ quarter of the grace and daprd headroom of a tenth, capped at 120 s and
346
+ 30 s. It never takes that from a drain of up to ``preferred_drain_seconds``
347
+ (the explicit or default drain): it then gets only what the grace leaves
348
+ beyond that drain, and never less than 10 s. The drain gets the rest. Inside
349
+ the tail, daprd gets up to a quarter (capped at 30 s) and the post-drain
350
+ deadline the remainder (capped at 120 s). The Pushgateway gets at most half
351
+ of the post-drain deadline: per-call HTTP timeout ≤ 1/8 of it (two calls),
352
+ the pre-DELETE hold the rest of that half.
353
+
354
+ So a 12 h grace keeps the 120/10/35 s defaults and drains for ~12 h; a
355
+ 3660 s grace keeps the full 3600 s drain and squeezes the 55 s left over; a
356
+ 30 s grace drains for 15 s.
357
+
358
+ Raises:
359
+ ValueError: The grace is shorter than the drain delay plus a 1 s
360
+ post-drain deadline, so no split can fit inside it.
361
+ """
362
+ grace = max(0, grace_seconds)
363
+ delay = math.ceil(drain_delay_seconds)
364
+ # The drain delay and a 1 s post-drain deadline are fixed costs: below
365
+ # their sum no split fits the grace, and a drain of 0 would still leave
366
+ # SIGKILL landing before the worker reached Temporal's shutdown.
367
+ minimum = delay + 1
368
+ if grace < minimum:
369
+ raise ValueError(
370
+ f"grace of {grace}s cannot fit the {drain_delay_seconds}s drain delay "
371
+ f"and a 1s post-drain deadline; it must be at least {minimum}s"
372
+ )
373
+ ideal_tail = min(_DEFAULT_POST_DRAIN_SECONDS, grace // 4) + min(
374
+ _SHUTDOWN_HEADROOM_CAP_SECONDS, grace // 10
375
+ )
376
+ beyond_preferred_drain = grace - delay - max(0, preferred_drain_seconds)
377
+ tail = min(
378
+ ideal_tail,
379
+ max(min(ideal_tail, _MIN_SHUTDOWN_TAIL_SECONDS), beyond_preferred_drain),
380
+ )
381
+ # Never 0: a non-positive post-drain timeout disables the deadline.
382
+ tail = min(max(1, tail), grace - delay)
383
+ headroom = min(_SHUTDOWN_HEADROOM_CAP_SECONDS, tail // 4)
384
+ post_drain = max(1, min(_DEFAULT_POST_DRAIN_SECONDS, tail - headroom))
385
+ drain = max(0, grace - delay - post_drain - headroom)
386
+ http_timeout = min(_DEFAULT_PUSHGATEWAY_HTTP_TIMEOUT_SECONDS, post_drain / 8)
387
+ delete_delay = max(
388
+ 0.0,
389
+ min(
390
+ _DEFAULT_PUSHGATEWAY_SHUTDOWN_DELETE_DELAY_SECONDS,
391
+ post_drain / 2 - 2 * http_timeout,
392
+ ),
393
+ )
394
+ return ShutdownBudget(
395
+ grace_seconds=grace,
396
+ drain_seconds=drain,
397
+ post_drain_seconds=post_drain,
398
+ headroom_seconds=headroom,
399
+ pushgateway_http_timeout_seconds=http_timeout,
400
+ pushgateway_shutdown_delete_delay_seconds=delete_delay,
401
+ )
402
+
403
+
404
+ def _preferred_drain_seconds() -> int:
405
+ """The explicit drain if one is set and parses, else the 3600 s default.
406
+
407
+ A value that does not parse is left for ``load_execution_settings`` to
408
+ reject, as it always has; here it only falls back to the default.
409
+ """
410
+ raw = os.environ.get(_DRAIN_ENV, "").strip()
411
+ try:
412
+ return int(raw) if raw else _DEFAULT_DRAIN_SECONDS
413
+ except ValueError:
414
+ return _DEFAULT_DRAIN_SECONDS
415
+
416
+
417
+ def load_shutdown_budget() -> ShutdownBudget | None:
418
+ """Read ``ATLAN_SHUTDOWN_GRACE_SECONDS`` and derive the budget from it.
419
+
420
+ ``None`` when unset or not a positive integer: every bound then keeps its
421
+ fixed default, so a deployment that declares nothing behaves as before.
422
+ Read on each call so settings loaders and tests see the current env.
423
+ """
424
+ raw = os.environ.get(SHUTDOWN_GRACE_SECONDS_ENV, "").strip()
425
+ if not raw:
426
+ return None
427
+ try:
428
+ grace = int(raw)
429
+ except ValueError:
430
+ warnings.warn(
431
+ f"{SHUTDOWN_GRACE_SECONDS_ENV}={raw!r} is not an integer; "
432
+ "shutdown bounds keep their fixed defaults",
433
+ stacklevel=2,
434
+ )
435
+ return None
436
+ if grace <= 0:
437
+ return None
438
+ try:
439
+ return derive_shutdown_budget(
440
+ grace, preferred_drain_seconds=_preferred_drain_seconds()
441
+ )
442
+ except ValueError as exc:
443
+ warnings.warn(
444
+ f"{SHUTDOWN_GRACE_SECONDS_ENV}={grace}: {exc}. Shutdown bounds keep "
445
+ "their fixed defaults; raise the grace or lower "
446
+ "ATLAN_SHUTDOWN_DRAIN_DELAY_SECONDS",
447
+ stacklevel=2,
448
+ )
449
+ return None
450
+
451
+
452
+ _SHUTDOWN_BUDGET = load_shutdown_budget()
453
+
275
454
  # Prometheus Pushgateway (worker-only deployments)
276
455
  #: Pushgateway URL workers push to. Empty disables push (combined-mode
277
456
  #: server+worker deployments leave this unset; ``/metrics`` covers
@@ -308,13 +487,19 @@ PROMETHEUS_PUSHGATEWAY_SWEEP_STALENESS_SECONDS = float(
308
487
  )
309
488
  #: Per-request HTTP timeout for every Pushgateway call (push, DELETE,
310
489
  #: sweep GET, sweep per-group DELETE). The prometheus_client default of 30s
311
- #: is too generous for our shape: at shutdown, two back-to-back 30s hangs
312
- #: (final push + DELETE_ON_SHUTDOWN) would exceed Kubernetes' default 30s
313
- #: terminationGracePeriodSeconds and SIGKILL the pod before cleanup runs.
314
- #: 10s leaves 2/3 of the push interval for actual work and ~10s of slack
315
- #: inside the grace period for the rest of worker shutdown.
490
+ #: is too generous: the final push and DELETE_ON_SHUTDOWN run back to back
491
+ #: under the post-drain deadline, which they share with the rest of shutdown.
492
+ #: Default 10s; when ``ATLAN_SHUTDOWN_GRACE_SECONDS`` is set and this is not,
493
+ #: derived from the grace (see :class:`ShutdownBudget`).
316
494
  PROMETHEUS_PUSHGATEWAY_HTTP_TIMEOUT_SECONDS = float(
317
- os.getenv("ATLAN_PROMETHEUS_PUSHGATEWAY_HTTP_TIMEOUT_SECONDS", "10")
495
+ os.getenv(
496
+ "ATLAN_PROMETHEUS_PUSHGATEWAY_HTTP_TIMEOUT_SECONDS",
497
+ str(
498
+ _SHUTDOWN_BUDGET.pushgateway_http_timeout_seconds
499
+ if _SHUTDOWN_BUDGET is not None
500
+ else _DEFAULT_PUSHGATEWAY_HTTP_TIMEOUT_SECONDS
501
+ ),
502
+ )
318
503
  )
319
504
  #: Sleep interval between the final push and the DELETE_ON_SHUTDOWN call
320
505
  #: so Prometheus has at least one scrape opportunity to read the final
@@ -323,11 +508,19 @@ PROMETHEUS_PUSHGATEWAY_HTTP_TIMEOUT_SECONDS = float(
323
508
  #: particular, the activity-failure increments that often trigger the
324
509
  #: scale-down — never reaches Prometheus. Default 35s = one full 30s
325
510
  #: scrape interval (the cluster default for the Pushgateway scrape, see
326
- #: vmagent's rendered config) plus a 5s jitter buffer. Worker pods have a
327
- #: 12h terminationGracePeriodSeconds, so the extra wait doesn't approach
328
- #: the kill timeout. Set to 0 to disable.
511
+ #: vmagent's rendered config) plus a 5s jitter buffer. It runs under the
512
+ #: post-drain deadline, so when ``ATLAN_SHUTDOWN_GRACE_SECONDS`` is set and
513
+ #: this is not, it is derived from the grace and shrinks with a short one
514
+ #: (see :class:`ShutdownBudget`). Set to 0 to disable.
329
515
  PROMETHEUS_PUSHGATEWAY_SHUTDOWN_DELETE_DELAY_SECONDS = float(
330
- os.getenv("ATLAN_PROMETHEUS_PUSHGATEWAY_SHUTDOWN_DELETE_DELAY_SECONDS", "35")
516
+ os.getenv(
517
+ "ATLAN_PROMETHEUS_PUSHGATEWAY_SHUTDOWN_DELETE_DELAY_SECONDS",
518
+ str(
519
+ _SHUTDOWN_BUDGET.pushgateway_shutdown_delete_delay_seconds
520
+ if _SHUTDOWN_BUDGET is not None
521
+ else _DEFAULT_PUSHGATEWAY_SHUTDOWN_DELETE_DELAY_SECONDS
522
+ ),
523
+ )
331
524
  )
332
525
 
333
526
  # REMOVED: ENABLE_TEMPORAL_ACTIVITY_FAILURE_LOGGING, WORKFLOW_UI_HOST,
@@ -535,16 +728,8 @@ WORKFLOW_AUTH_CLIENT_SECRET_KEY = os.getenv(
535
728
  # ATLAN_RUN_LENGTH_SLA_SECONDS → RUN_LENGTH_SLA_SECONDS (default 86400, 0 disables)
536
729
  # ExecutionSettings owns the graceful shutdown timeout:
537
730
  # - ExecutionSettings.graceful_shutdown_timeout_seconds (TEMPORAL_GRACEFUL_SHUTDOWN_TIMEOUT)
538
-
539
- #: Delay before initiating worker shutdown after receiving a termination signal.
540
- #: This gives the event loop time to flush in-flight activity completions
541
- #: (e.g. RespondActivityTaskFailed/Completed RPCs) that are already queued
542
- #: but haven't been sent yet. Without this, a SIGTERM that arrives right
543
- #: after an activity fails can preempt the _run_activity coroutine before
544
- #: it reaches complete_activity_task(), leaving the SDK with a phantom
545
- #: "in-use" task slot that blocks shutdown for the entire
546
- #: graceful_shutdown_timeout.
547
- SHUTDOWN_DRAIN_DELAY_SECONDS = int(os.getenv("ATLAN_SHUTDOWN_DRAIN_DELAY_SECONDS", 5))
731
+ # — derived from ATLAN_SHUTDOWN_GRACE_SECONDS when that is set; see
732
+ # ShutdownBudget above.
548
733
 
549
734
 
550
735
  #: Maximum re-dispatches per activity caused by worker pod eviction (SIGTERM
@@ -988,6 +1173,14 @@ SIZING_CLEANUP_ENABLED = (
988
1173
  SIZING_FILE_NAME = os.environ.get("ATLAN_SIZING_FILE_NAME", "sizing.parquet")
989
1174
  TRACES_FILE_NAME = os.environ.get("ATLAN_TRACES_FILE_NAME", "traces.parquet")
990
1175
 
1176
+ #: Upper bound, in seconds, on stopping the shared observability background
1177
+ #: loop at process exit: the final flush of every periodic sink (logs,
1178
+ #: metrics, traces, sizing) and the Segment worker's last batch, together.
1179
+ #: See ``application_sdk.observability.background_loop``.
1180
+ OBSERVABILITY_SHUTDOWN_TIMEOUT_SECONDS = float(
1181
+ os.environ.get("ATLAN_OBSERVABILITY_SHUTDOWN_TIMEOUT_SECONDS", "10")
1182
+ )
1183
+
991
1184
  # Segment Configuration
992
1185
  #: Segment API URL for sending events. Defaults to https://api.segment.io/v1/batch
993
1186
  SEGMENT_API_URL = os.getenv("ATLAN_SEGMENT_API_URL", "https://api.segment.io/v1/batch")
@@ -482,6 +482,13 @@ class Output(BaseModel):
482
482
  ``artifacts`` from any ``get_outputs().add_metric()`` /
483
483
  ``add_artifact()`` calls made during the workflow or its activities.
484
484
  Connector code never needs to set these fields directly.
485
+
486
+ On a task's output the two fields carry that task's own outputs back
487
+ to the workflow through Temporal history, so they arrive even when
488
+ the task runs in a different worker process. The interceptor
489
+ overwrites them with exactly what the task collected (``None`` when
490
+ it collected nothing): a task that returns an upstream output
491
+ unchanged does not report the upstream metrics a second time.
485
492
  """
486
493
 
487
494
  model_config = ConfigDict()
@@ -35,5 +35,5 @@ only to reconcile ahead of a release — and deliberately, since older Dapr
35
35
  releases drop off the CDN.
36
36
  """
37
37
 
38
- __version__ = "3.55.1"
38
+ __version__ = "3.55.3"
39
39
  __dapr_version: str = "1.19.1"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "atlan-application-sdk-api"
3
- version = "3.55.1"
3
+ version = "3.55.3"
4
4
  description = "Experimental: the handler surface of the Atlan Application SDK, for the consolidated API host"
5
5
  license = "Apache-2.0"
6
6
  authors = [