atlan-application-sdk-api 3.55.2__tar.gz → 3.56.0__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 (86) hide show
  1. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/PKG-INFO +2 -2
  2. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/_build_info.py +1 -1
  3. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/_runtime/__init__.py +1 -1
  4. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/_runtime/cgroup.py +4 -3
  5. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/_runtime/offload.py +24 -4
  6. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/clients/sql.py +215 -1
  7. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/common/aws_utils.py +6 -0
  8. atlan_application_sdk_api-3.56.0/application_sdk/common/utils.py +147 -0
  9. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/constants.py +297 -41
  10. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/contracts/base.py +7 -0
  11. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/credentials/ref.py +36 -27
  12. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/server/fastapi/models.py +95 -3
  13. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/version.py +1 -1
  14. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/pyproject.toml +2 -2
  15. atlan_application_sdk_api-3.55.2/application_sdk/common/utils.py +0 -87
  16. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/.gitignore +0 -0
  17. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/README.md +0 -0
  18. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/api-files.txt +0 -0
  19. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/__init__.py +0 -0
  20. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/_context_errors.py +0 -0
  21. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/_install.py +0 -0
  22. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/_logging.py +0 -0
  23. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/_runtime/progress.py +0 -0
  24. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/clients/__init__.py +0 -0
  25. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/clients/_interface.py +0 -0
  26. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/clients/_sql_failure_classifier.py +0 -0
  27. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/clients/base.py +0 -0
  28. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/clients/http_errors.py +0 -0
  29. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/clients/models.py +0 -0
  30. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/clients/sql_errors.py +0 -0
  31. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/clients/sql_typecasters.py +0 -0
  32. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/clients/ssl_utils.py +0 -0
  33. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/common/__init__.py +0 -0
  34. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/common/_generated_tree.py +0 -0
  35. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/common/_listing.py +0 -0
  36. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/common/aws_utils_errors.py +0 -0
  37. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/common/backoff.py +0 -0
  38. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/common/build_identity.py +0 -0
  39. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/common/concurrency.py +0 -0
  40. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/common/errors.py +0 -0
  41. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/common/filter_matching.py +0 -0
  42. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/common/logger.py +0 -0
  43. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/common/models.py +0 -0
  44. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/common/sql_filters.py +0 -0
  45. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/common/sql_filters_errors.py +0 -0
  46. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/common/task_queue.py +0 -0
  47. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/common/types.py +0 -0
  48. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/contracts/__init__.py +0 -0
  49. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/contracts/events.py +0 -0
  50. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/contracts/types.py +0 -0
  51. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/contracts/types_errors.py +0 -0
  52. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/credentials/__init__.py +0 -0
  53. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/credentials/errors.py +0 -0
  54. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/credentials/extra.py +0 -0
  55. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/credentials/ingress.py +0 -0
  56. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/credentials/requirements.py +0 -0
  57. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/credentials/spec.py +0 -0
  58. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/credentials/types.py +0 -0
  59. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/credentials/utils.py +0 -0
  60. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/errors/__init__.py +0 -0
  61. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/errors/base.py +0 -0
  62. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/errors/categories.py +0 -0
  63. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/errors/http.py +0 -0
  64. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/errors/leaves.py +0 -0
  65. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/errors/wire.py +0 -0
  66. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/handler/__init__.py +0 -0
  67. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/handler/_dispatch.py +0 -0
  68. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/handler/_warmup.py +0 -0
  69. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/handler/asgi.py +0 -0
  70. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/handler/base.py +0 -0
  71. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/handler/context.py +0 -0
  72. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/handler/contracts.py +0 -0
  73. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/handler/manifest.py +0 -0
  74. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/handler/metadata_routes.py +0 -0
  75. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/handler/object_routes.py +0 -0
  76. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/handler/request_contract.py +0 -0
  77. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/handler/routes.py +0 -0
  78. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/handler/service_errors.py +0 -0
  79. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/server/__init__.py +0 -0
  80. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/templates/__init__.py +0 -0
  81. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/templates/contracts/__init__.py +0 -0
  82. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/templates/contracts/base_metadata_extraction.py +0 -0
  83. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/templates/contracts/incremental_sql.py +0 -0
  84. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/templates/contracts/sql_metadata.py +0 -0
  85. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/application_sdk/templates/contracts/sql_query.py +0 -0
  86. {atlan_application_sdk_api-3.55.2 → atlan_application_sdk_api-3.56.0}/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.2
3
+ Version: 3.56.0
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
@@ -32,7 +32,7 @@ Requires-Dist: python-dotenv<2.0.0,>=1.2.2; extra == 'aws'
32
32
  Provides-Extra: pandas
33
33
  Requires-Dist: pandas<4.0.0,>=2.2.3; extra == 'pandas'
34
34
  Provides-Extra: pyatlan
35
- Requires-Dist: authlib<2,>=1.9.4; extra == 'pyatlan'
35
+ Requires-Dist: authlib<2,>=1.9.5; extra == 'pyatlan'
36
36
  Requires-Dist: pyatlan<12,>=11.7.0; extra == 'pyatlan'
37
37
  Provides-Extra: sql
38
38
  Requires-Dist: httpx<0.29.0,>=0.27.0; extra == 'sql'
@@ -27,7 +27,7 @@ def load_build_info(path: str | None = None) -> dict[str, str]:
27
27
  Missing or malformed file → ``{}``; callers fall back to the env vars.
28
28
  ``ATLAN_BUILD_INFO_PATH`` overrides the lookup for non-template layouts.
29
29
 
30
- Public because :mod:`application_sdk.app.build_identity` reads the same file
30
+ Public because :mod:`application_sdk.common.build_identity` reads the same file
31
31
  through it. A second parser there would be a second place for the key names
32
32
  to drift from what CI writes.
33
33
  """
@@ -14,7 +14,7 @@ auto-holds work). Nothing else in ``application_sdk``: never
14
14
  ``application_sdk.storage``, ``application_sdk.execution`` or
15
15
  ``application_sdk.app`` — each of those pulls in ``storage.ops`` transitively,
16
16
  which is exactly the cycle this package exists to remove.
17
- ``tests/unit/runtime/test_layering.py`` enforces this in a subprocess, so
17
+ ``tests/unit/_runtime/test_layering.py`` enforces this in a subprocess, so
18
18
  breaking the rule fails CI rather than surfacing as an ``ImportError`` at some
19
19
  unrelated call site months later.
20
20
 
@@ -1,9 +1,10 @@
1
1
  """The container's CPU limit, readable from the bottom layer (ADR-0019).
2
2
 
3
3
  ``os.cpu_count()`` reports the node's cores, not the pod's: a worker limited to
4
- one CPU on a 16-core node sees 16. Anything the substrate sizes by CPU — the
5
- fault-isolation process pool in :mod:`application_sdk._runtime.offload` — reads
6
- the limit here instead. :mod:`application_sdk.observability.cgroup` reports the
4
+ one CPU on a 16-core node sees 16. Anything sized by CPU — the ``sdk-blocking-``
5
+ thread pool and the fault-isolation process pool in
6
+ :mod:`application_sdk._runtime.offload`, and the worker's default activity slots
7
+ — reads the limit here instead. :mod:`application_sdk.observability.cgroup` reports the
7
8
  same number for sizing telemetry and delegates to this module, so the two can
8
9
  never disagree about what the limit is.
9
10
 
@@ -63,8 +63,28 @@ P = ParamSpec("P")
63
63
  # This single instance is created once at module import and intentionally
64
64
  # outlives individual calls. Named threads ("sdk-blocking-N") make it
65
65
  # distinguishable from Temporal's "activity-pool-N" threads in stack traces.
66
+ #
67
+ # Width is the stdlib's own default formula, ``min(32, cpus + 4)``, with the
68
+ # CPU count taken from the container's limit (``available_cpus``) rather than
69
+ # ``os.cpu_count()``, and never below 16. Without the floor a 1-CPU pod would
70
+ # drop from 32 threads to 5. These threads mostly wait on a database or the
71
+ # network rather than use CPU, so a wide fan-out of blocking calls would queue
72
+ # where it ran in parallel before. The floor still halves what a small pod on
73
+ # a big node got.
74
+ _MAX_BLOCKING_POOL_WIDTH = 32
75
+ _MIN_BLOCKING_POOL_WIDTH = 16
76
+
77
+
78
+ def _blocking_pool_width() -> int:
79
+ """Threads in ``_BLOCKING_EXECUTOR``: ``min(32, max(16, available_cpus() + 4))``."""
80
+ return min(
81
+ _MAX_BLOCKING_POOL_WIDTH,
82
+ max(_MIN_BLOCKING_POOL_WIDTH, available_cpus() + 4),
83
+ )
84
+
85
+
66
86
  _BLOCKING_EXECUTOR = concurrent.futures.ThreadPoolExecutor(
67
- max_workers=min(32, (os.cpu_count() or 1) + 4),
87
+ max_workers=_blocking_pool_width(),
68
88
  thread_name_prefix="sdk-blocking-",
69
89
  )
70
90
 
@@ -526,9 +546,9 @@ def _auto_hold(label: str, timeout: float | None) -> Iterator[None]:
526
546
  # the app's next calls queue behind them until the cap is reached. Unset (the
527
547
  # default), nothing changes: calls queue
528
548
  # exactly as before. A default cap would turn today's queueing into failures
529
- # for any fan-out wider than the cap, and the pool width it would be derived
530
- # from is not a reliable number — ``os.cpu_count()`` reports the node's
531
- # cores, not the pod's CPU limit.
549
+ # for any fan-out wider than the cap. The pool width now follows the pod's
550
+ # CPU limit, so a derived default would at least be sized right, but that
551
+ # does not change the first reason.
532
552
  # * **A per-app stranded count**: calls whose caller stopped waiting while the
533
553
  # thread kept running. Exported as the ``offload.stranded_threads`` gauge,
534
554
  # labelled by app only, and logged once per strand with the callable's name.
@@ -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
@@ -0,0 +1,147 @@
1
+ """Common utilities.
2
+
3
+ Most functions previously in this module have been moved to more logical homes:
4
+
5
+ - SQL filter pipeline → ``common.sql_filters``
6
+ - Credential parsing → ``credentials.utils``
7
+ - CPU/threading → ``common.concurrency``
8
+ """
9
+
10
+ import os
11
+ import warnings
12
+
13
+ import orjson
14
+ from pydantic import BaseModel
15
+
16
+ from application_sdk._context_errors import ObjectStoreNotConfiguredError
17
+ from application_sdk._install import worker_only_missing
18
+ from application_sdk._logging import get_logger
19
+ from application_sdk.constants import TEMPORARY_PATH
20
+
21
+ logger = get_logger(__name__)
22
+
23
+
24
+ async def download_file_from_upload_response(
25
+ response: dict | str | BaseModel,
26
+ ) -> str:
27
+ """Download a file that was uploaded via the /file endpoint.
28
+
29
+ Takes the upload response returned by the file upload endpoint (or its
30
+ dict/JSON representation) and downloads the file to a local temporary path
31
+ for processing in workflows or activities.
32
+
33
+ Args:
34
+ response: The upload response containing the object store key. Can be
35
+ a dict, a JSON string, or any pydantic model with a ``key`` field —
36
+ :class:`application_sdk.handler.contracts.FileUploadResponse` (what
37
+ the handler's ``POST /workflows/v1/file`` returns) or the deprecated
38
+ ``application_sdk.server.fastapi.models.FileUploadResponse``.
39
+
40
+ Returns:
41
+ The local file path where the file was downloaded.
42
+
43
+ Raises:
44
+ ValueError: If the input is a string that isn't valid JSON, or if
45
+ the ``key`` field is missing from the response.
46
+ """
47
+ if isinstance(response, str):
48
+ try:
49
+ response = orjson.loads(response)
50
+ except orjson.JSONDecodeError as e:
51
+ from application_sdk.common.errors import JsonParseError # noqa: PLC0415
52
+
53
+ raise JsonParseError(cause=e) from e
54
+
55
+ if isinstance(response, BaseModel):
56
+ # Read the declared field, not getattr: a model without one is a type
57
+ # error, not a model whose key happens to be missing.
58
+ if "key" not in type(response).model_fields:
59
+ from application_sdk.common.errors import ResponseTypeError # noqa: PLC0415
60
+
61
+ raise ResponseTypeError(
62
+ message=f"Unsupported response type: {type(response).__name__}"
63
+ )
64
+ key = getattr(response, "key") # noqa: B009 — BaseModel declares no ``key``; checked above
65
+ # handler.contracts.FileUploadResponse defaults ``key`` to "": an unset
66
+ # key is a missing key, not a request to download the temp directory.
67
+ if not key:
68
+ from application_sdk.common.errors import ( # noqa: PLC0415
69
+ ResponseKeyMissingError,
70
+ )
71
+
72
+ raise ResponseKeyMissingError()
73
+ elif isinstance(response, dict):
74
+ # Same rule as the model branch: the dict/JSON form of a handler
75
+ # response with no key carries ``"key": ""``.
76
+ if not response.get("key"):
77
+ from application_sdk.common.errors import ( # noqa: PLC0415
78
+ ResponseKeyMissingError,
79
+ )
80
+
81
+ raise ResponseKeyMissingError()
82
+ key = response["key"]
83
+ else:
84
+ from application_sdk.common.errors import ResponseTypeError # noqa: PLC0415
85
+
86
+ raise ResponseTypeError(
87
+ message=f"Unsupported response type: {type(response).__name__}"
88
+ )
89
+
90
+ local_path = os.path.join(TEMPORARY_PATH, key)
91
+
92
+ try:
93
+ from application_sdk.storage.ops import ( # noqa: PLC0415 — lazy: storage.ops imports obstore (heavy Rust ext) at module load, and this module sits on the workflow-sandbox import chain (credentials → here); pinned by the preflight gate's import-hygiene test
94
+ download_file_chunked,
95
+ )
96
+ except ModuleNotFoundError as exc:
97
+ if not worker_only_missing(exc):
98
+ raise
99
+ # api-only install (the API host): there is no object store to read from.
100
+ raise ObjectStoreNotConfiguredError() from exc
101
+
102
+ # Chunk large uploads (user-supplied files are uncapped) so a big artifact
103
+ # survives slow egress; small files still stream in a single GET. (BLDX-1513)
104
+ await download_file_chunked(
105
+ key=key,
106
+ local_path=local_path,
107
+ )
108
+
109
+ return local_path
110
+
111
+
112
+ #: name -> (replacement, why). Served by __getattr__ below (PEP 562).
113
+ _DEPRECATED_CONSTANTS: dict[str, tuple[str, str]] = {
114
+ "FileUploadResponse": (
115
+ "application_sdk.handler.contracts.FileUploadResponse",
116
+ "this module only ever re-exported the v2 "
117
+ "application_sdk.server.fastapi.models.FileUploadResponse, which is "
118
+ "itself deprecated",
119
+ ),
120
+ }
121
+
122
+
123
+ def _deprecated_constant_value(name: str) -> object:
124
+ if name == "FileUploadResponse":
125
+ # Lazy: this module sits on the workflow-sandbox import chain
126
+ # (credentials → here) and must not pull the v2 server models in.
127
+ from application_sdk.server.fastapi.models import ( # noqa: PLC0415
128
+ FileUploadResponse,
129
+ )
130
+
131
+ return FileUploadResponse
132
+ raise AssertionError(name)
133
+
134
+
135
+ def __getattr__(name: str) -> object:
136
+ """Serve the removed re-export once more, with a deprecation warning (PEP 562)."""
137
+ entry = _DEPRECATED_CONSTANTS.get(name)
138
+ if entry is None:
139
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
140
+ replacement, note = entry
141
+ warnings.warn(
142
+ f"{name} is deprecated; use {replacement} instead — {note}. "
143
+ "Will be removed in v4.0.",
144
+ DeprecationWarning,
145
+ stacklevel=2,
146
+ )
147
+ return _deprecated_constant_value(name)