1616from concurrent .futures import ThreadPoolExecutor , as_completed
1717from dataclasses import dataclass
1818from datetime import timedelta
19+ from enum import Enum
1920from io import BytesIO
2021from queue import Empty , Full , Queue
2122from tempfile import mkstemp
@@ -746,6 +747,35 @@ class _PresignedUrl:
746747 part_number : int | None = None
747748
748749
750+ class _ResolvedEndpoint (Enum ):
751+ """A file transfer protocol this SDK can speak, identified by the (api, api_version) pair the
752+ endpoints API returns."""
753+
754+ IO_OFFLOAD = "IO_OFFLOAD"
755+ FILES_API_V2 = "FILES_API_V2"
756+
757+
758+ # Maps the server's (api, api_version) to a protocol compiled into this SDK. Pairs not listed here are
759+ # skipped, which lets the server advertise newer protocols without breaking older SDKs. IO_OFFLOAD is
760+ # unversioned during the preview, so a versioned IO_OFFLOAD is newer than this SDK.
761+ _RECOGNIZED_ENDPOINTS : dict [tuple [str , Optional [str ]], _ResolvedEndpoint ] = {
762+ ("IO_OFFLOAD" , None ): _ResolvedEndpoint .IO_OFFLOAD ,
763+ ("FILES_API" , "2.0" ): _ResolvedEndpoint .FILES_API_V2 ,
764+ }
765+
766+ _ENDPOINT_SCHEMES = ("http" , "https" )
767+
768+
769+ @dataclass (frozen = True )
770+ class _Endpoint :
771+ """One entry of the ordered endpoint list a file transfer walks, best first."""
772+
773+ kind : _ResolvedEndpoint
774+ base_url : str
775+ """Scheme and hostname as returned by the server, e.g. https://example.cloud.databricks.com."""
776+ multipart_upload_supported : bool
777+
778+
749779class _PresignedUrlRequestBuilder :
750780 """Builds presigned URL requests for file upload operations.
751781
@@ -928,6 +958,12 @@ class FilesExt(files.FilesAPI):
928958 # Timeout in seconds for the storage-proxy health check probe.
929959 _STORAGE_PROXY_PROBE_TIMEOUT : float = 3.0
930960
961+ _ENDPOINTS_API_PATH : str = "/api/2.0/fs/endpoints"
962+
963+ # Endpoint discovery is a single attempt bounded by this timeout: it precedes a transfer, so it
964+ # must fail fast to the default order rather than retry and stall the upload or download.
965+ _ENDPOINTS_RESOLVE_TIMEOUT_SECONDS : float = 10.0
966+
931967 @dataclass (frozen = True )
932968 class _UploadContext :
933969 target_path : str
@@ -956,13 +992,129 @@ def __init__(self, api_client, config: Config):
956992 self ._dp_hostname_available : Optional [bool ] = None
957993 self ._cached_storage_proxy_session : Optional [requests .Session ] = None
958994 self ._storage_proxy_session_lock = Lock ()
995+ self ._cached_endpoints : Optional [list [_Endpoint ]] = None
996+ self ._endpoints_lock = Lock ()
959997
960- def _get_hostname (self ) -> str :
961- """Returns the hostname for file operations .
998+ def _resolve_endpoints (self ) -> list [ _Endpoint ] :
999+ """Returns the ordered endpoints to try for a file transfer, best first .
9621000
963- When storage proxy is enabled, probes it on first call and caches the
964- result. Returns the proxy hostname if available, otherwise the workspace
965- hostname.
1001+ The server is asked once per client and its answer, including a failure, is cached. Anything
1002+ short of a usable list falls back to the built-in order, so endpoint discovery never fails a
1003+ transfer.
1004+ """
1005+ if not self ._config .experimental_files_ext_enable_endpoints_api :
1006+ return self ._default_endpoints ()
1007+ with self ._endpoints_lock :
1008+ if self ._cached_endpoints is None :
1009+ self ._cached_endpoints = self ._fetch_endpoints () or self ._default_endpoints ()
1010+ return list (self ._cached_endpoints )
1011+
1012+ def _default_endpoints (self ) -> list [_Endpoint ]:
1013+ host = self ._config .host
1014+ return [
1015+ _Endpoint (_ResolvedEndpoint .IO_OFFLOAD , host , multipart_upload_supported = True ),
1016+ _Endpoint (_ResolvedEndpoint .FILES_API_V2 , host , multipart_upload_supported = False ),
1017+ ]
1018+
1019+ def _fetch_endpoints (self ) -> list [_Endpoint ]:
1020+ """Fetches the endpoint list from the server, keeping only entries this SDK can speak.
1021+
1022+ Discovery runs before a transfer, so it is a single short-timeout attempt with no retries: a
1023+ slow or failing endpoint must fall back to the default order quickly rather than hold up the
1024+ upload or download.
1025+ """
1026+ url = f"{ self ._config .host } { self ._ENDPOINTS_API_PATH } "
1027+ try :
1028+ response = self ._cloud_provider_session ().request (
1029+ "GET" ,
1030+ url ,
1031+ headers = {** self ._config .authenticate (), "Accept" : "application/json" },
1032+ timeout = self ._ENDPOINTS_RESOLVE_TIMEOUT_SECONDS ,
1033+ )
1034+ except Exception as e :
1035+ # Broad on purpose: network and auth failures must all fail safe to the default order.
1036+ _LOG .warning (f"Failed to resolve file endpoints, using the default endpoints: { e } " )
1037+ return []
1038+
1039+ # Lets a failure below be traced to the server's request log.
1040+ request_id = response .headers .get ("x-request-id" )
1041+ if response .status_code == 404 :
1042+ # Not a warning: until the server-side rollout completes, some workspaces do not serve the API.
1043+ _LOG .info (
1044+ f"Endpoints API is not served for this workspace (request ID { request_id } ), using the default endpoints."
1045+ )
1046+ return []
1047+ if response .status_code != 200 :
1048+ _LOG .warning (
1049+ f"Unexpected status resolving file endpoints ({ response .status_code } , request ID { request_id } ), "
1050+ "using the default endpoints."
1051+ )
1052+ return []
1053+ try :
1054+ body = response .json ()
1055+ except Exception as e :
1056+ _LOG .warning (
1057+ f"Failed to parse endpoints response (request ID { request_id } ), using the default endpoints: { e } "
1058+ )
1059+ return []
1060+
1061+ # Proto3 JSON leaves out an empty repeated field.
1062+ entries = body .get ("endpoints" , []) if isinstance (body , dict ) else None
1063+ if not isinstance (entries , list ):
1064+ _LOG .warning (
1065+ f"Unexpected endpoints response (request ID { request_id } ), using the default endpoints: { body } "
1066+ )
1067+ return []
1068+ endpoints = []
1069+ for entry in entries :
1070+ kind = self ._endpoint_kind (entry )
1071+ if kind is None :
1072+ # Not a warning: an older SDK is expected to skip entries for APIs added after it shipped.
1073+ _LOG .info (f"Skipping endpoint this SDK cannot use (request ID { request_id } ): { entry } " )
1074+ continue
1075+ endpoint = self ._parse_endpoint (entry , kind )
1076+ if endpoint is None :
1077+ _LOG .warning (
1078+ f"Skipping { kind .value } endpoint with an unusable address (request ID { request_id } ): { entry } "
1079+ )
1080+ continue
1081+ endpoints .append (endpoint )
1082+ if not endpoints :
1083+ _LOG .warning (f"No usable endpoints in the response (request ID { request_id } ), using the default endpoints." )
1084+ return endpoints
1085+
1086+ @staticmethod
1087+ def _endpoint_kind (entry ) -> Optional [_ResolvedEndpoint ]:
1088+ """Returns the protocol of a listed endpoint, or None if this SDK does not speak it."""
1089+ if not isinstance (entry , dict ):
1090+ return None
1091+ api = entry .get ("api" )
1092+ api_version = entry .get ("api_version" )
1093+ # The entry is unvalidated JSON: an unhashable value such as a list would make the lookup below raise
1094+ # instead of skipping the entry. IO_OFFLOAD entries have no api_version, so None is allowed.
1095+ if not isinstance (api , str ) or not (api_version is None or isinstance (api_version , str )):
1096+ return None
1097+ return _RECOGNIZED_ENDPOINTS .get ((api , api_version ))
1098+
1099+ @staticmethod
1100+ def _parse_endpoint (entry : dict , kind : _ResolvedEndpoint ) -> Optional [_Endpoint ]:
1101+ scheme = entry .get ("scheme" )
1102+ hostname = entry .get ("hostname" )
1103+ if scheme not in _ENDPOINT_SCHEMES or not isinstance (hostname , str ) or not hostname :
1104+ return None
1105+ # Mirrors the proto getter: an unset optional bool reads as false.
1106+ multipart_upload_supported = entry .get ("multipart_upload_supported" ) is True
1107+ return _Endpoint (kind , f"{ scheme } ://{ hostname } " , multipart_upload_supported )
1108+
1109+ def _active_endpoint (self ) -> _Endpoint :
1110+ """The endpoint used for bulk file transfer.
1111+
1112+ Selected by the storage-proxy probe: the storage proxy (a direct Files API path) when the probe
1113+ finds it available, otherwise the offload (presigned) path on the workspace host. The probe runs
1114+ once and its result is cached.
1115+
1116+ This is the single-endpoint selection; PR wiring the endpoints API replaces it with a walk over
1117+ the server-resolved list.
9661118 """
9671119 if self ._config .experimental_files_ext_enable_storage_proxy :
9681120 if self ._dp_hostname_available is None :
@@ -972,19 +1124,28 @@ def _get_hostname(self) -> str:
9721124 else :
9731125 _LOG .info ("Storage proxy is not available, will use presigned URLs." )
9741126 if self ._dp_hostname_available :
975- return self ._STORAGE_PROXY_HOSTNAME
976- return self ._config .host
1127+ return _Endpoint (
1128+ _ResolvedEndpoint .FILES_API_V2 , self ._STORAGE_PROXY_HOSTNAME , multipart_upload_supported = True
1129+ )
1130+ return _Endpoint (_ResolvedEndpoint .IO_OFFLOAD , self ._config .host , multipart_upload_supported = True )
1131+
1132+ def _get_hostname (self ) -> str :
1133+ """Returns the scheme+hostname for file operations, e.g. https://example.cloud.databricks.com."""
1134+ return self ._active_endpoint ().base_url
9771135
9781136 def _create_request_builder (self ):
979- """Creates the appropriate request builder for file operations.
1137+ """Creates the request builder for the active endpoint."""
1138+ return self ._request_builder_for (self ._active_endpoint ())
1139+
1140+ def _request_builder_for (self , endpoint : _Endpoint ):
1141+ """Maps an endpoint to the builder that speaks its protocol.
9801142
981- Returns a storage proxy builder when the proxy is available,
982- otherwise a presigned URL builder .
1143+ The offload path coordinates presigned URLs through the workspace API; the direct Files API path
1144+ builds URLs straight at the endpoint host .
9831145 """
984- hostname = self ._get_hostname ()
985- if self ._config .experimental_files_ext_enable_storage_proxy and self ._dp_hostname_available :
986- return _StorageProxyRequestBuilder (hostname )
987- return _PresignedUrlRequestBuilder (self ._api , hostname )
1146+ if endpoint .kind == _ResolvedEndpoint .IO_OFFLOAD :
1147+ return _PresignedUrlRequestBuilder (self ._api , endpoint .base_url )
1148+ return _StorageProxyRequestBuilder (endpoint .base_url )
9881149
9891150 def _resolve_workspace_id (self ) -> Optional [str ]:
9901151 """Resolves the workspace ID by querying the SCIM Me endpoint."""
0 commit comments