multicloud-py-common 0.1.6__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.
@@ -0,0 +1,206 @@
1
+ Apache License Version 2.0
2
+
3
+ Copyright (c) 2026 Salesforce, Inc.
4
+ All rights reserved.
5
+
6
+ Apache License
7
+ Version 2.0, January 2004
8
+ http://www.apache.org/licenses/
9
+
10
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
11
+
12
+ 1. Definitions.
13
+
14
+ "License" shall mean the terms and conditions for use, reproduction,
15
+ and distribution as defined by Sections 1 through 9 of this document.
16
+
17
+ "Licensor" shall mean the copyright owner or entity authorized by
18
+ the copyright owner that is granting the License.
19
+
20
+ "Legal Entity" shall mean the union of the acting entity and all
21
+ other entities that control, are controlled by, or are under common
22
+ control with that entity. For the purposes of this definition,
23
+ "control" means (i) the power, direct or indirect, to cause the
24
+ direction or management of such entity, whether by contract or
25
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
26
+ outstanding shares, or (iii) beneficial ownership of such entity.
27
+
28
+ "You" (or "Your") shall mean an individual or Legal Entity
29
+ exercising permissions granted by this License.
30
+
31
+ "Source" form shall mean the preferred form for making modifications,
32
+ including but not limited to software source code, documentation
33
+ source, and configuration files.
34
+
35
+ "Object" form shall mean any form resulting from mechanical
36
+ transformation or translation of a Source form, including but
37
+ not limited to compiled object code, generated documentation,
38
+ and conversions to other media types.
39
+
40
+ "Work" shall mean the work of authorship, whether in Source or
41
+ Object form, made available under the License, as indicated by a
42
+ copyright notice that is included in or attached to the work
43
+ (an example is provided in the Appendix below).
44
+
45
+ "Derivative Works" shall mean any work, whether in Source or Object
46
+ form, that is based on (or derived from) the Work and for which the
47
+ editorial revisions, annotations, elaborations, or other modifications
48
+ represent, as a whole, an original work of authorship. For the purposes
49
+ of this License, Derivative Works shall not include works that remain
50
+ separable from, or merely link (or bind by name) to the interfaces of,
51
+ the Work and Derivative Works thereof.
52
+
53
+ "Contribution" shall mean any work of authorship, including
54
+ the original version of the Work and any modifications or additions
55
+ to that Work or Derivative Works thereof, that is intentionally
56
+ submitted to Licensor for inclusion in the Work by the copyright owner
57
+ or by an individual or Legal Entity authorized to submit on behalf of
58
+ the copyright owner. For the purposes of this definition, "submitted"
59
+ means any form of electronic, verbal, or written communication sent
60
+ to the Licensor or its representatives, including but not limited to
61
+ communication on electronic mailing lists, source code control systems,
62
+ and issue tracking systems that are managed by, or on behalf of, the
63
+ Licensor for the purpose of discussing and improving the Work, but
64
+ excluding communication that is conspicuously marked or otherwise
65
+ designated in writing by the copyright owner as "Not a Contribution."
66
+
67
+ "Contributor" shall mean Licensor and any individual or Legal Entity
68
+ on behalf of whom a Contribution has been received by Licensor and
69
+ subsequently incorporated within the Work.
70
+
71
+ 2. Grant of Copyright License. Subject to the terms and conditions of
72
+ this License, each Contributor hereby grants to You a perpetual,
73
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
74
+ copyright license to reproduce, prepare Derivative Works of,
75
+ publicly display, publicly perform, sublicense, and distribute the
76
+ Work and such Derivative Works in Source or Object form.
77
+
78
+ 3. Grant of Patent License. Subject to the terms and conditions of
79
+ this License, each Contributor hereby grants to You a perpetual,
80
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
81
+ (except as stated in this section) patent license to make, have made,
82
+ use, offer to sell, sell, import, and otherwise transfer the Work,
83
+ where such license applies only to those patent claims licensable
84
+ by such Contributor that are necessarily infringed by their
85
+ Contribution(s) alone or by combination of their Contribution(s)
86
+ with the Work to which such Contribution(s) was submitted. If You
87
+ institute patent litigation against any entity (including a
88
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
89
+ or a Contribution incorporated within the Work constitutes direct
90
+ or contributory patent infringement, then any patent licenses
91
+ granted to You under this License for that Work shall terminate
92
+ as of the date such litigation is filed.
93
+
94
+ 4. Redistribution. You may reproduce and distribute copies of the
95
+ Work or Derivative Works thereof in any medium, with or without
96
+ modifications, and in Source or Object form, provided that You
97
+ meet the following conditions:
98
+
99
+ (a) You must give any other recipients of the Work or
100
+ Derivative Works a copy of this License; and
101
+
102
+ (b) You must cause any modified files to carry prominent notices
103
+ stating that You changed the files; and
104
+
105
+ (c) You must retain, in the Source form of any Derivative Works
106
+ that You distribute, all copyright, patent, trademark, and
107
+ attribution notices from the Source form of the Work,
108
+ excluding those notices that do not pertain to any part of
109
+ the Derivative Works; and
110
+
111
+ (d) If the Work includes a "NOTICE" text file as part of its
112
+ distribution, then any Derivative Works that You distribute must
113
+ include a readable copy of the attribution notices contained
114
+ within such NOTICE file, excluding those notices that do not
115
+ pertain to any part of the Derivative Works, in at least one
116
+ of the following places: within a NOTICE text file distributed
117
+ as part of the Derivative Works; within the Source form or
118
+ documentation, if provided along with the Derivative Works; or,
119
+ within a display generated by the Derivative Works, if and
120
+ wherever such third-party notices normally appear. The contents
121
+ of the NOTICE file are for informational purposes only and
122
+ do not modify the License. You may add Your own attribution
123
+ notices within Derivative Works that You distribute, alongside
124
+ or as an addendum to the NOTICE text from the Work, provided
125
+ that such additional attribution notices cannot be construed
126
+ as modifying the License.
127
+
128
+ You may add Your own copyright statement to Your modifications and
129
+ may provide additional or different license terms and conditions
130
+ for use, reproduction, or distribution of Your modifications, or
131
+ for any such Derivative Works as a whole, provided Your use,
132
+ reproduction, and distribution of the Work otherwise complies with
133
+ the conditions stated in this License.
134
+
135
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
136
+ any Contribution intentionally submitted for inclusion in the Work
137
+ by You to the Licensor shall be under the terms and conditions of
138
+ this License, without any additional terms or conditions.
139
+ Notwithstanding the above, nothing herein shall supersede or modify
140
+ the terms of any separate license agreement you may have executed
141
+ with Licensor regarding such Contributions.
142
+
143
+ 6. Trademarks. This License does not grant permission to use the trade
144
+ names, trademarks, service marks, or product names of the Licensor,
145
+ except as required for reasonable and customary use in describing the
146
+ origin of the Work and reproducing the content of the NOTICE file.
147
+
148
+ 7. Disclaimer of Warranty. Unless required by applicable law or
149
+ agreed to in writing, Licensor provides the Work (and each
150
+ Contributor provides its Contributions) on an "AS IS" BASIS,
151
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
152
+ implied, including, without limitation, any warranties or conditions
153
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
154
+ PARTICULAR PURPOSE. You are solely responsible for determining the
155
+ appropriateness of using or redistributing the Work and assume any
156
+ risks associated with Your exercise of permissions under this License.
157
+
158
+ 8. Limitation of Liability. In no event and under no legal theory,
159
+ whether in tort (including negligence), contract, or otherwise,
160
+ unless required by applicable law (such as deliberate and grossly
161
+ negligent acts) or agreed to in writing, shall any Contributor be
162
+ liable to You for damages, including any direct, indirect, special,
163
+ incidental, or consequential damages of any character arising as a
164
+ result of this License or out of the use or inability to use the
165
+ Work (including but not limited to damages for loss of goodwill,
166
+ work stoppage, computer failure or malfunction, or any and all
167
+ other commercial damages or losses), even if such Contributor
168
+ has been advised of the possibility of such damages.
169
+
170
+ 9. Accepting Warranty or Additional Liability. While redistributing
171
+ the Work or Derivative Works thereof, You may choose to offer,
172
+ and charge a fee for, acceptance of support, warranty, indemnity,
173
+ or other liability obligations and/or rights consistent with this
174
+ License. However, in accepting such obligations, You may act only
175
+ on Your own behalf and on Your sole responsibility, not on behalf
176
+ of any other Contributor, and only if You agree to indemnify,
177
+ defend, and hold each Contributor harmless for any liability
178
+ incurred by, or claims asserted against, such Contributor by reason
179
+ of your accepting any such warranty or additional liability.
180
+
181
+ END OF TERMS AND CONDITIONS
182
+
183
+ APPENDIX: How to apply the Apache License to your work.
184
+
185
+ To apply the Apache License to your work, attach the following
186
+ boilerplate notice, with the fields enclosed by brackets "{}"
187
+ replaced with your own identifying information. (Don't include
188
+ the brackets!) The text should be enclosed in the appropriate
189
+ comment syntax for the file format. We also recommend that a
190
+ file or class name and description of purpose be included on the
191
+ same "printed page" as the copyright notice for easier
192
+ identification within third-party archives.
193
+
194
+ Copyright {yyyy} {name of copyright owner}
195
+
196
+ Licensed under the Apache License, Version 2.0 (the "License");
197
+ you may not use this file except in compliance with the License.
198
+ You may obtain a copy of the License at
199
+
200
+ http://www.apache.org/licenses/LICENSE-2.0
201
+
202
+ Unless required by applicable law or agreed to in writing, software
203
+ distributed under the License is distributed on an "AS IS" BASIS,
204
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
205
+ See the License for the specific language governing permissions and
206
+ limitations under the License.
@@ -0,0 +1,20 @@
1
+ Metadata-Version: 2.4
2
+ Name: multicloud-py-common
3
+ Version: 0.1.6
4
+ Summary: Shared base for the python-multicloud SDK: exception hierarchy, provider registry, entry-point discovery.
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/salesforce/multicloud-py
7
+ Project-URL: Repository, https://github.com/salesforce/multicloud-py
8
+ Project-URL: Issues, https://github.com/salesforce/multicloud-py/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE.txt
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
16
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
17
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
18
+ Dynamic: license-file
19
+
20
+ MultiCloud Python SDK package.
@@ -0,0 +1,43 @@
1
+ """Cross-provider common abstractions (exceptions, provider registry).
2
+
3
+ This package is the foundation all services share. It provides the
4
+ exception hierarchy and the plugin-discovery mechanism that let
5
+ downstream service packages stay cloud-agnostic.
6
+ """
7
+
8
+ from multicloud.common.credentials import (
9
+ CredentialsOverrider,
10
+ CredentialsType,
11
+ StsCredentials,
12
+ )
13
+ from multicloud.common.exceptions import (
14
+ FailedPreconditionException,
15
+ InvalidArgumentException,
16
+ ResourceExistsException,
17
+ ResourceNotFoundException,
18
+ SubstrateSdkException,
19
+ UnAuthorizedException,
20
+ UnknownException,
21
+ UnsupportedOperationException,
22
+ )
23
+ from multicloud.common.provider import Provider, ProviderRegistry
24
+ from multicloud.common.providers import get_available_providers
25
+ from multicloud.common.proxy import ProxyConfig
26
+
27
+ __all__ = [
28
+ "CredentialsOverrider",
29
+ "ProxyConfig",
30
+ "CredentialsType",
31
+ "FailedPreconditionException",
32
+ "InvalidArgumentException",
33
+ "Provider",
34
+ "ProviderRegistry",
35
+ "ResourceExistsException",
36
+ "ResourceNotFoundException",
37
+ "StsCredentials",
38
+ "SubstrateSdkException",
39
+ "UnAuthorizedException",
40
+ "UnknownException",
41
+ "UnsupportedOperationException",
42
+ "get_available_providers",
43
+ ]
@@ -0,0 +1,106 @@
1
+ """Cross-service credential models.
2
+
3
+ Defines the cloud-agnostic credential types shared across all services
4
+ (STS, Blob, PubSub, DocStore). These models describe *how* to obtain
5
+ credentials — the provider-specific resolution logic lives in the
6
+ per-cloud ``*_common`` packages.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from datetime import datetime
13
+ from enum import Enum, auto
14
+ from typing import Callable, Optional
15
+
16
+ from multicloud.common.exceptions import InvalidArgumentException
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class StsCredentials:
21
+ """Cloud-agnostic representation of temporary credentials.
22
+
23
+ All providers normalize their native credential type into this shape.
24
+
25
+ - ``access_key_id``: identity key or empty when not applicable
26
+ - ``access_key_secret``: secret key or empty when not applicable
27
+ - ``security_token``: session/bearer token (all providers)
28
+ - ``expiration``: token expiry time (all providers)
29
+ """
30
+
31
+ access_key_id: str = ""
32
+ access_key_secret: str = ""
33
+ security_token: str = ""
34
+ expiration: Optional[datetime] = None
35
+
36
+ def __repr__(self) -> str:
37
+ # Mask secret fields so accidental logging (e.g. of an exception
38
+ # whose message contains an StsCredentials) does not leak creds.
39
+ return (
40
+ f"StsCredentials(access_key_id={self.access_key_id!r}, "
41
+ f"access_key_secret=***, security_token=***, "
42
+ f"expiration={self.expiration!r})"
43
+ )
44
+
45
+
46
+ class CredentialsType(Enum):
47
+ """Type of credential override to apply."""
48
+
49
+ SESSION = auto()
50
+ ASSUME_ROLE = auto()
51
+ ASSUME_ROLE_WEB_IDENTITY = auto()
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class CredentialsOverrider:
56
+ """Override the default credentials resolution.
57
+
58
+ Modeled as a grouped configuration object because its fields are
59
+ interdependent and validated as a unit — the required subset of fields
60
+ changes based on ``credentials_type``.
61
+
62
+ Used when a service needs to:
63
+ 1. Supply explicit session credentials (SESSION)
64
+ 2. Assume a role from another account (ASSUME_ROLE)
65
+ 3. Exchange a web identity token for credentials (ASSUME_ROLE_WEB_IDENTITY)
66
+
67
+ If ``credentials_type`` is SESSION, ``session_credentials`` must be provided.
68
+ If ``credentials_type`` is ASSUME_ROLE, ``role`` is required.
69
+ If ``credentials_type`` is ASSUME_ROLE_WEB_IDENTITY, ``role`` and
70
+ ``web_identity_token_supplier`` are required.
71
+
72
+ ``role`` is provider-interpreted: each provider maps this string to its
73
+ native role identifier format (e.g. an ARN, a service-account email, or
74
+ a RAM role name).
75
+ """
76
+
77
+ credentials_type: CredentialsType
78
+ session_credentials: Optional[StsCredentials] = None
79
+ role: Optional[str] = None
80
+ duration_seconds: Optional[int] = None
81
+ session_name: Optional[str] = None
82
+ web_identity_token_supplier: Optional[Callable[[], str]] = None
83
+
84
+ def __post_init__(self) -> None:
85
+ if (
86
+ self.credentials_type == CredentialsType.SESSION
87
+ and self.session_credentials is None
88
+ ):
89
+ raise InvalidArgumentException(
90
+ "session_credentials required when credentials_type is SESSION"
91
+ )
92
+ if self.credentials_type == CredentialsType.ASSUME_ROLE and not self.role:
93
+ raise InvalidArgumentException(
94
+ "role required when credentials_type is ASSUME_ROLE"
95
+ )
96
+ if self.credentials_type == CredentialsType.ASSUME_ROLE_WEB_IDENTITY:
97
+ if not self.role:
98
+ raise InvalidArgumentException(
99
+ "role required when credentials_type is ASSUME_ROLE_WEB_IDENTITY"
100
+ )
101
+ if self.web_identity_token_supplier is None:
102
+ raise InvalidArgumentException(
103
+ "web_identity_token_supplier required when credentials_type is ASSUME_ROLE_WEB_IDENTITY"
104
+ )
105
+ if self.duration_seconds is not None and self.duration_seconds <= 0:
106
+ raise InvalidArgumentException("duration_seconds must be positive")
@@ -0,0 +1,66 @@
1
+ """Cloud-agnostic exception hierarchy.
2
+
3
+ Providers translate their native errors into one of these types so
4
+ client code can write a single ``except`` clause that works across
5
+ substrates.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+
11
+ class SubstrateSdkException(Exception):
12
+ """Root of all SDK exceptions — catch this to handle any SDK error generically."""
13
+
14
+
15
+ class InvalidArgumentException(SubstrateSdkException):
16
+ """Caller provided invalid input (empty key, bad type, failed validation)."""
17
+
18
+
19
+ class ResourceNotFoundException(SubstrateSdkException):
20
+ """Target resource (bucket, object, role) does not exist."""
21
+
22
+
23
+ class ResourceExistsException(SubstrateSdkException):
24
+ """Attempted to create a resource that already exists (e.g., duplicate bucket)."""
25
+
26
+
27
+ class ResourceConflictException(SubstrateSdkException):
28
+ """Resource state conflicts with the requested operation (e.g., delete role with attached policies).
29
+
30
+ Also raised when a concurrent write races a conditional write: the
31
+ precondition may never have been evaluated and the write may not have
32
+ happened, so this is a retry signal, distinct from the terminal
33
+ ResourceExistsException / FailedPreconditionException. Retry the write.
34
+ """
35
+
36
+
37
+ class UnAuthorizedException(SubstrateSdkException):
38
+ """Credentials missing, expired, or lack required permissions."""
39
+
40
+
41
+ class FailedPreconditionException(SubstrateSdkException):
42
+ """Operation rejected because a precondition wasn't met (e.g., non-empty bucket delete)."""
43
+
44
+
45
+ class UnsupportedOperationException(SubstrateSdkException):
46
+ """The requested operation is not supported by this provider."""
47
+
48
+
49
+ class ResourceExhaustedException(SubstrateSdkException):
50
+ """Rate limit exceeded, quota exhausted, or throttling applied."""
51
+
52
+
53
+ class DeadlineExceededException(SubstrateSdkException):
54
+ """Operation timed out or deadline exceeded."""
55
+
56
+
57
+ class TransactionFailedException(SubstrateSdkException):
58
+ """Internal service failure during transaction."""
59
+
60
+
61
+ class ResourceAlreadyExistsException(SubstrateSdkException):
62
+ """Attempted to create a resource that already exists."""
63
+
64
+
65
+ class UnknownException(SubstrateSdkException):
66
+ """Catch-all for errors that don't map to a more specific type."""
@@ -0,0 +1,166 @@
1
+ """Provider discovery registry.
2
+
3
+ A small in-process registry keyed by provider id (e.g. ``"aws"``,
4
+ ``"gcp"``). Provider classes register themselves with the
5
+ ``@registry.register("aws")`` decorator at import time; the user-facing
6
+ client (e.g. ``BucketClient``) looks up the right class by id at
7
+ construction time.
8
+
9
+ This is a service-locator pattern — it emerges when a single API must
10
+ dispatch to multiple backend implementations at runtime.
11
+
12
+ Provider modules in this SDK are loaded lazily from setuptools entry
13
+ points. Each provider distribution declares an entry point in the
14
+ ``multicloud.<svc>.providers`` group; :meth:`ProviderRegistry.discover`
15
+ imports those modules on the first :meth:`ProviderRegistry.get` call so
16
+ the ``@register`` decorators run and the providers become resolvable.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import importlib
22
+ import importlib.metadata
23
+ from abc import ABC, abstractmethod
24
+ from typing import Callable, Dict, List, Type
25
+
26
+ from multicloud.common.exceptions import SubstrateSdkException
27
+
28
+
29
+ class Provider(ABC):
30
+ """Base class for all provider implementations across all services.
31
+
32
+ Every provider (for blob, STS, or any other service) must implement
33
+ error translation to map provider-specific exceptions to the common
34
+ SubstrateSdkException hierarchy.
35
+ """
36
+
37
+ # Set by @registry.register() — identifies which cloud this provider handles.
38
+ provider_id: str = ""
39
+
40
+ def get_provider_id(self) -> str:
41
+ """Return the provider identifier (e.g., 'aws', 'gcp', 'ali').
42
+ Read from the class attribute stamped by the registry decorator.
43
+ """
44
+ return self.provider_id
45
+
46
+ @abstractmethod
47
+ def translate_error(self, exc: Exception) -> SubstrateSdkException:
48
+ """Translate provider-specific exceptions to the common hierarchy.
49
+
50
+ Each provider maps its native SDK errors into SubstrateSdkException
51
+ subtypes. This normalizes diverse error shapes into a single
52
+ hierarchy that client code can catch uniformly.
53
+
54
+ Args:
55
+ exc: The provider-specific exception to translate.
56
+
57
+ Returns:
58
+ A SubstrateSdkException subclass instance.
59
+ """
60
+
61
+
62
+ class ProviderRegistry:
63
+ """A per-service registry that maps provider_id → provider class.
64
+
65
+ Each service (blob, sts, docstore, ...) owns its own registry instance so
66
+ the namespaces don't collide. A lightweight service-locator that avoids
67
+ hard imports of optional dependencies.
68
+
69
+ Provider discovery is via setuptools entry points. The registry is
70
+ constructed with an ``entry_point_group`` (e.g. ``"multicloud.blob.providers"``)
71
+ that provider distributions advertise themselves under. The registry
72
+ imports those modules lazily on the first :meth:`get` call; each
73
+ provider module's import side-effect is to call
74
+ ``@registry.register(...)`` on its class.
75
+ """
76
+
77
+ def __init__(
78
+ self,
79
+ service_name: str,
80
+ entry_point_group: str | None = None,
81
+ ) -> None:
82
+ # entry_point_group is None for in-test registries that don't
83
+ # need plugin discovery. Real services (blob, sts, ...) pass
84
+ # something like "multicloud.blob.providers".
85
+ self._service_name = service_name
86
+ self._entry_point_group = entry_point_group
87
+ self._providers: Dict[str, Type[Provider]] = {}
88
+ self._import_errors: Dict[str, ImportError] = {}
89
+ self._discovered = False
90
+
91
+ def register(self, provider_id: str) -> Callable[[Type[Provider]], Type[Provider]]:
92
+ """Class decorator that registers a provider implementation.
93
+ Stamps provider_id on the class and adds it to the lookup table.
94
+ """
95
+
96
+ def _decorator(cls: Type[Provider]) -> Type[Provider]:
97
+ cls.provider_id = provider_id
98
+ self._providers[provider_id] = cls
99
+ # Registration wins over any previously recorded import error.
100
+ self._import_errors.pop(provider_id, None)
101
+ return cls
102
+
103
+ return _decorator
104
+
105
+ def record_import_error(self, provider_id: str, exc: ImportError) -> None:
106
+ """Stash an ImportError for deferred reporting (lazy-import pattern).
107
+
108
+ The error surfaces with a helpful "pip install" hint when the
109
+ user first tries to use that provider.
110
+ """
111
+ self._import_errors[provider_id] = exc
112
+
113
+ def discover(self) -> None:
114
+ """Import every provider module advertised in our entry-point group.
115
+
116
+ Idempotent. Safe to call multiple times. Each provider module's
117
+ import side-effect (the ``@registry.register("aws")`` decorator)
118
+ populates the registry. Missing optional dependencies surface as
119
+ ImportError and are recorded under the entry-point name so a
120
+ later ``get(...)`` call yields a clear "pip install" hint.
121
+ """
122
+ if self._discovered:
123
+ return
124
+ self._discovered = True
125
+ if self._entry_point_group is None:
126
+ return
127
+
128
+ eps = importlib.metadata.entry_points()
129
+ # Python 3.10+: select() yields entry points in the requested group.
130
+ group_eps = eps.select(group=self._entry_point_group)
131
+ for ep in group_eps:
132
+ try:
133
+ # Importing the module triggers @registry.register().
134
+ # We don't need ep.load() (which returns the attribute) —
135
+ # the side-effect is what registers the provider.
136
+ importlib.import_module(ep.value.split(":")[0])
137
+ except ImportError as exc:
138
+ # ep.name is the provider id ("aws", "gcp", "alibaba").
139
+ self.record_import_error(ep.name, exc)
140
+
141
+ def get(self, provider_id: str) -> Type[Provider]:
142
+ """Look up a provider class by id — the core dispatch mechanism.
143
+ Raises ValueError with actionable guidance if not found or import failed.
144
+ """
145
+ self.discover()
146
+
147
+ if provider_id in self._providers:
148
+ return self._providers[provider_id]
149
+ if provider_id in self._import_errors:
150
+ import_exc = self._import_errors[provider_id]
151
+ raise ValueError(
152
+ f"Provider {provider_id!r} for service={self._service_name!r} "
153
+ f"could not be loaded: {import_exc}. "
154
+ f"Try installing it (e.g. "
155
+ f"`pip install 'multicloud-{self._service_name}-{provider_id}'`)."
156
+ ) from import_exc
157
+ raise ValueError(
158
+ f"No provider registered for service={self._service_name!r} "
159
+ f"provider_id={provider_id!r}. "
160
+ f"Registered: {sorted(self._providers)}"
161
+ )
162
+
163
+ def ids(self) -> List[str]:
164
+ """Return sorted list of registered provider ids (for display/logging)."""
165
+ self.discover()
166
+ return sorted(self._providers)
@@ -0,0 +1,33 @@
1
+ """Cross-service helpers for enumerating installed providers.
2
+
3
+ Replaces the previous top-level ``multicloud.get_available_providers()``
4
+ helper. Walks setuptools entry points so the answer reflects what is
5
+ actually installed in the current environment, not what is on disk.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import importlib.metadata
11
+ from typing import List, Set
12
+
13
+ # Service entry-point groups currently shipped by the SDK. Each
14
+ # provider distribution registers itself under exactly one of these.
15
+ _SERVICE_GROUPS = (
16
+ "multicloud.blob.providers",
17
+ "multicloud.sts.providers",
18
+ )
19
+
20
+
21
+ def get_available_providers() -> List[str]:
22
+ """Return a sorted list of provider ids installed in this environment.
23
+
24
+ A provider id appears in the result if any installed distribution
25
+ advertises an entry point for it under any service group. The id
26
+ itself (``"aws"``, ``"gcp"``, ``"alibaba"``) is the entry-point name.
27
+ """
28
+ seen: Set[str] = set()
29
+ eps = importlib.metadata.entry_points()
30
+ for group in _SERVICE_GROUPS:
31
+ for ep in eps.select(group=group):
32
+ seen.add(ep.name)
33
+ return sorted(seen)
@@ -0,0 +1,48 @@
1
+ """Proxy configuration shared by every provider.
2
+
3
+ Clients otherwise inherit whatever proxy the environment advertises, which is
4
+ wrong for traffic that must stay inside the network: a same-region storage call
5
+ routed through an egress proxy fails rather than going direct.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from typing import Optional
12
+
13
+ from multicloud.common.exceptions import InvalidArgumentException
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class ProxyConfig:
18
+ """How a client should resolve its HTTP proxy.
19
+
20
+ Attributes:
21
+ endpoint: Proxy URL, such as ``http://proxy.example.net:8443``.
22
+ use_environment_variable_proxy_values: Whether to honour ``HTTP_PROXY``
23
+ and friends. True by default; set False to connect directly.
24
+
25
+ Setting ``endpoint`` also stops the environment being consulted, so
26
+ ``NO_PROXY`` no longer applies. One flag rather than the two some SDKs
27
+ expose, because Python cannot disable the environment variables and the
28
+ OS-level proxy settings separately.
29
+ """
30
+
31
+ endpoint: Optional[str] = None
32
+ use_environment_variable_proxy_values: bool = True
33
+
34
+ def __post_init__(self) -> None:
35
+ if self.endpoint is None:
36
+ return
37
+ endpoint = self.endpoint.strip()
38
+ if not endpoint:
39
+ raise InvalidArgumentException(
40
+ "proxy endpoint must not be blank; omit it to disable"
41
+ )
42
+ if "://" not in endpoint:
43
+ raise InvalidArgumentException(
44
+ f"proxy endpoint must include a scheme, got '{self.endpoint}'"
45
+ )
46
+ # Padding is not rejected, so keep the stripped form rather than one
47
+ # that passes validation and then fails to proxy.
48
+ object.__setattr__(self, "endpoint", endpoint)
@@ -0,0 +1,20 @@
1
+ Metadata-Version: 2.4
2
+ Name: multicloud-py-common
3
+ Version: 0.1.6
4
+ Summary: Shared base for the python-multicloud SDK: exception hierarchy, provider registry, entry-point discovery.
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/salesforce/multicloud-py
7
+ Project-URL: Repository, https://github.com/salesforce/multicloud-py
8
+ Project-URL: Issues, https://github.com/salesforce/multicloud-py/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE.txt
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
16
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
17
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
18
+ Dynamic: license-file
19
+
20
+ MultiCloud Python SDK package.
@@ -0,0 +1,13 @@
1
+ LICENSE.txt
2
+ pyproject.toml
3
+ multicloud/common/__init__.py
4
+ multicloud/common/credentials.py
5
+ multicloud/common/exceptions.py
6
+ multicloud/common/provider.py
7
+ multicloud/common/providers.py
8
+ multicloud/common/proxy.py
9
+ multicloud_py_common.egg-info/PKG-INFO
10
+ multicloud_py_common.egg-info/SOURCES.txt
11
+ multicloud_py_common.egg-info/dependency_links.txt
12
+ multicloud_py_common.egg-info/requires.txt
13
+ multicloud_py_common.egg-info/top_level.txt
@@ -0,0 +1,5 @@
1
+
2
+ [dev]
3
+ pytest>=7.0.0
4
+ pytest-cov>=4.0.0
5
+ mypy>=1.0.0
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "multicloud-py-common"
7
+ version = "0.1.6"
8
+ license = "Apache-2.0"
9
+ description = "Shared base for the python-multicloud SDK: exception hierarchy, provider registry, entry-point discovery."
10
+ readme = {text = "MultiCloud Python SDK package.", content-type = "text/markdown"}
11
+ requires-python = ">=3.10"
12
+ classifiers = [
13
+ "Programming Language :: Python :: 3",
14
+ "Operating System :: OS Independent",
15
+ ]
16
+
17
+ [project.urls]
18
+ Homepage = "https://github.com/salesforce/multicloud-py"
19
+ Repository = "https://github.com/salesforce/multicloud-py"
20
+ Issues = "https://github.com/salesforce/multicloud-py/issues"
21
+
22
+ [project.optional-dependencies]
23
+ dev = ["pytest>=7.0.0", "pytest-cov>=4.0.0", "mypy>=1.0.0"]
24
+
25
+ [tool.setuptools]
26
+ license-files = ["LICENSE.txt"]
27
+
28
+ [tool.setuptools.packages.find]
29
+ include = ["multicloud*"]
30
+
31
+ # multicloud/ and multicloud/common/ are PEP 420 implicit namespace packages
32
+ # (no __init__.py at multicloud/) so multiple distributions — multicloud-blob,
33
+ # multicloud-sts, multicloud-blob-aws, ... — can contribute submodules under
34
+ # the shared `multicloud.*` namespace. multicloud/common/ keeps its own
35
+ # __init__.py because it is a concrete leaf package owned by THIS distribution.
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+