| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | import asyncio |
| 8 | import importlib |
| 9 | from typing import Any, Dict |
| 10 | |
| 11 | from .datatypes import ProviderSpec, RemoteProviderSpec |
| 12 | |
| 13 | |
| 14 | def instantiate_class_type(fully_qualified_name): |
| 15 | module_name, class_name = fully_qualified_name.rsplit(".", 1) |
| 16 | module = importlib.import_module(module_name) |
| 17 | return getattr(module, class_name) |
| 18 | |
| 19 | |
| 20 | # returns a class implementing the protocol corresponding to the Api |
| 21 | def instantiate_provider( |
| 22 | provider_spec: ProviderSpec, |
| 23 | provider_config: Dict[str, Any], |
| 24 | deps: Dict[str, ProviderSpec], |
| 25 | ): |
| 26 | module = importlib.import_module(provider_spec.module) |
| 27 | |
| 28 | config_type = instantiate_class_type(provider_spec.config_class) |
| 29 | if isinstance(provider_spec, RemoteProviderSpec): |
| 30 | if provider_spec.adapter: |
| 31 | method = "get_adapter_impl" |
| 32 | else: |
| 33 | method = "get_client_impl" |
| 34 | else: |
| 35 | method = "get_provider_impl" |
| 36 | |
| 37 | config = config_type(**provider_config) |
| 38 | fn = getattr(module, method) |
| 39 | impl = asyncio.run(fn(config, deps)) |
| 40 | impl.__provider_spec__ = provider_spec |
| 41 | impl.__provider_config__ = config |
| 42 | return impl |