From 87809e6d9cc821531d91e936213d9d0382c16516 Mon Sep 17 00:00:00 2001 From: Lukas Klingsbo Date: Tue, 3 Nov 2026 19:07:17 +0100 Subject: [PATCH 1/2] refactor: keep internal helpers out of the public api Prefix internal helpers, session managers, timers and transport methods with an underscore so the capability check no longer counts them as public API. Register the remaining public names in sdk-compliance.yaml and remove the unused sanitize_pattern_param. --- sdk-compliance.yaml | 5 ++ src/auth/src/supabase_auth/admin_api.py | 32 ++++---- src/auth/src/supabase_auth/client.py | 78 +++++++++---------- src/auth/src/supabase_auth/helpers.py | 36 ++++----- src/auth/src/supabase_auth/mfa.py | 18 ++--- src/auth/src/supabase_auth/session.py | 24 +++--- src/auth/src/supabase_auth/timer.py | 4 +- src/auth/tests/test_helpers.py | 8 +- .../src/supabase_functions/client.py | 4 +- .../src/supabase_functions/errors.py | 2 +- src/functions/tests/test_errors.py | 8 +- .../src/postgrest/request_builder.py | 8 +- src/postgrest/src/postgrest/utils.py | 6 +- .../tests/_async/test_request_builder.py | 4 +- .../tests/_sync/test_request_builder.py | 4 +- src/realtime/src/realtime/channel.py | 20 ++--- src/realtime/src/realtime/client.py | 12 +-- src/realtime/tests/test_unknown_refs.py | 2 +- src/storage/src/storage3/analytics.py | 8 +- src/storage/src/storage3/client.py | 14 ++-- src/storage/src/storage3/exceptions.py | 4 +- src/storage/src/storage3/file_api.py | 24 +++--- src/storage/src/storage3/vectors.py | 34 ++++---- 23 files changed, 180 insertions(+), 179 deletions(-) diff --git a/sdk-compliance.yaml b/sdk-compliance.yaml index e42f7f058..f51ff1706 100644 --- a/sdk-compliance.yaml +++ b/sdk-compliance.yaml @@ -752,6 +752,8 @@ features: status: implemented symbols: - BaseRequestClient.retry + supporting_symbols: + - BaseRequestClient database.configuration.request_timeout: status: implemented note: "No timeout parameter. Configure the timeout on the httpx client passed in through http_session, or wrap async calls in asyncio.wait_for (asyncio.timeout on Python 3.11+)." @@ -1004,6 +1006,7 @@ features: - StorageClient.create_bucket supporting_symbols: - CreateOrUpdateBucketBody + - BucketName storage.file_buckets.get_bucket: status: implemented symbols: @@ -1198,6 +1201,7 @@ features: - StorageVectorsClient - VectorBucketScope - VectorIndexScope + - StorageVectorsClient.get_bucket storage.vector_buckets.create_index: status: implemented symbols: @@ -1423,3 +1427,4 @@ supporting_symbols: - SystemMessage - ChannelErrorMessage - ChannelCloseMessage + - ChannelLeaveMessage diff --git a/src/auth/src/supabase_auth/admin_api.py b/src/auth/src/supabase_auth/admin_api.py index 388903d8e..f3b6f0f45 100644 --- a/src/auth/src/supabase_auth/admin_api.py +++ b/src/auth/src/supabase_auth/admin_api.py @@ -20,12 +20,12 @@ from yarl import URL from .helpers import ( - handle_error_response, + _handle_error_response, + _redirect_to_as_query, + _validate_adapter, + _validate_model, parse_link_response, parse_user_response, - redirect_to_as_query, - validate_adapter, - validate_model, validate_uuid, ) from .types import ( @@ -74,7 +74,7 @@ def delete_factor( method="DELETE", path=["admin", "users", user_id, "factors", factor_id], ) - return validate_model(response, AuthMFAAdminDeleteFactorResponse) + return _validate_model(response, AuthMFAAdminDeleteFactorResponse) @handle_http_io def list_factors(self, user_id: str) -> HttpMethod[AuthMFAAdminListFactorsResponse]: @@ -86,7 +86,7 @@ def list_factors(self, user_id: str) -> HttpMethod[AuthMFAAdminListFactorsRespon method="GET", path=["admin", "users", user_id, "factors"], ) - return validate_adapter(response, AuthMFAAdminListFactorsResponseParser) + return _validate_adapter(response, AuthMFAAdminListFactorsResponseParser) @dataclass @@ -125,7 +125,7 @@ def list_clients( query=query, ) - result = validate_model(response, OAuthClientListResponse) + result = _validate_model(response, OAuthClientListResponse) # Parse pagination headers total = response.headers.get("x-total-count") @@ -166,7 +166,7 @@ def create_client( body=params, ) - return OAuthClientResponse(client=validate_model(response, OAuthClient)) + return OAuthClientResponse(client=_validate_model(response, OAuthClient)) @handle_http_io def get_client( @@ -185,7 +185,7 @@ def get_client( method="GET", path=["admin", "oauth", "clients", client_id], ) - return OAuthClientResponse(client=validate_model(response, OAuthClient)) + return OAuthClientResponse(client=_validate_model(response, OAuthClient)) @handle_http_io def update_client( @@ -206,7 +206,7 @@ def update_client( path=["admin", "oauth", "clients", client_id], body=params, ) - return OAuthClientResponse(client=validate_model(response, OAuthClient)) + return OAuthClientResponse(client=_validate_model(response, OAuthClient)) @handle_http_io def delete_client( @@ -226,7 +226,7 @@ def delete_client( path=["admin", "oauth", "clients", client_id], ) if not response.is_success: - raise handle_error_response(response) + raise _handle_error_response(response) @handle_http_io def regenerate_client_secret( @@ -245,7 +245,7 @@ def regenerate_client_secret( method="POST", path=["admin", "oauth", "clients", client_id, "regenerate_secret"], ) - return OAuthClientResponse(client=validate_model(response, OAuthClient)) + return OAuthClientResponse(client=_validate_model(response, OAuthClient)) class SupabaseAuthAdmin(Generic[HttpIO]): @@ -279,7 +279,7 @@ def invite_user_by_email( method="POST", path=["invite"], body={"email": email, "data": data}, - query=redirect_to_as_query(redirect_to), + query=_redirect_to_as_query(redirect_to), ) return parse_user_response(response) @@ -294,7 +294,7 @@ def generate_link( method="POST", path=["admin", "generate_link"], body=params.body, - query=redirect_to_as_query(params.redirect_to), + query=_redirect_to_as_query(params.redirect_to), ) return parse_link_response(response) @@ -335,7 +335,7 @@ def list_users( path=["admin", "users"], query=query, ) - return validate_model(response, UserList).users + return _validate_model(response, UserList).users @handle_http_io def get_user_by_id(self, uid: str) -> HttpMethod[UserResponse]: @@ -389,7 +389,7 @@ def delete_user( method="DELETE", path=["admin", "users", id], body=body ) if not response.is_success: - raise handle_error_response(response) + raise _handle_error_response(response) class SyncSupabaseAuthAdmin(SupabaseAuthAdmin[SyncHttpIO]): diff --git a/src/auth/src/supabase_auth/client.py b/src/auth/src/supabase_auth/client.py index b683836e0..0fdc63a0d 100644 --- a/src/auth/src/supabase_auth/client.py +++ b/src/auth/src/supabase_auth/client.py @@ -30,28 +30,28 @@ UserDoesntExist, ) from .helpers import ( + _handle_error_response, + _redirect_to_as_query, decode_jwt, generate_pkce_challenge, generate_pkce_verifier, - handle_error_response, parse_auth_otp_response, parse_auth_response, parse_jwks, parse_link_identity_response, parse_sso_response, parse_user_response, - redirect_to_as_query, validate_exp, ) from .mfa import AsyncSupabaseAuthMFAClient, SyncSupabaseAuthMFAClient from .session import ( AsyncMemoryStorage, - AsyncSessionManager, AsyncSupportedStorage, - SessionManagerCommon, SyncMemoryStorage, - SyncSessionManager, SyncSupportedStorage, + _AsyncSessionManager, + _SessionManagerCommon, + _SyncSessionManager, ) from .types import ( JWK, @@ -85,7 +85,7 @@ from .version import __version__ -def is_implicit_grant_flow(url: URL) -> bool: +def _is_implicit_grant_flow(url: URL) -> bool: params = url.query return "access_token" in params or "error_description" in params @@ -121,7 +121,7 @@ class SupabaseAuthHttpClient(Generic[HttpIO]): executor: HttpIO base_url: URL default_headers: Headers - session_manager: SessionManagerCommon[HttpIO] + session_manager: _SessionManagerCommon[HttpIO] _jwks: JWKSet flow_type: AuthFlowType = "implicit" _jwks_ttl: float = 600 # 10 minutes @@ -172,7 +172,7 @@ def _sign_up( """ body: BaseModel | dict[str, JSON] = credentials.body if isinstance(credentials, SignUpWithEmailAndPasswordCredentials): - query = redirect_to_as_query(credentials.redirect_to) + query = _redirect_to_as_query(credentials.redirect_to) body = _with_pkce_challenge(body, code_verifier) else: query = URLQuery.empty() @@ -248,7 +248,7 @@ def _sign_out(self, session: Session, scope: SignOutScope) -> HttpMethod[None]: headers=session.encode_access_token(), ) if not response.is_success: - raise handle_error_response(response) + raise _handle_error_response(response) def _sign_in_with_oauth( self, @@ -310,7 +310,7 @@ def _unlink_identity( headers=session.encode_access_token(), ) if not response.is_success: - raise handle_error_response(response) + raise _handle_error_response(response) return response @handle_http_io @@ -321,7 +321,7 @@ def _sign_in_with_otp( ) -> HttpMethod[AuthOtpResponse]: body: BaseModel | dict[str, JSON] = credentials.body if isinstance(credentials, SignInWithEmailAndPasswordlessCredentials): - query = redirect_to_as_query(credentials.email_redirect_to) + query = _redirect_to_as_query(credentials.email_redirect_to) body = _with_pkce_challenge(body, code_verifier) else: query = URLQuery.empty() @@ -339,7 +339,7 @@ def resend( credentials: ResendCredentials, ) -> HttpMethod[AuthOtpResponse]: if isinstance(credentials, ResendEmailCredentials): - query = redirect_to_as_query(credentials.email_redirect_to) + query = _redirect_to_as_query(credentials.email_redirect_to) else: query = URLQuery.empty() response = yield JSONRequest( @@ -355,7 +355,7 @@ def _verify_otp(self, params: VerifyOtpParams) -> HttpMethod[AuthResponse]: if isinstance(params, VerifyTokenHashParams): query = URLQuery.empty() else: - query = redirect_to_as_query(params.redirect_to) + query = _redirect_to_as_query(params.redirect_to) response = yield JSONRequest( method="POST", path=["verify"], @@ -373,7 +373,7 @@ def _reauthenticate(self, session: Session) -> HttpMethod[AuthResponse]: headers=session.encode_access_token(), ) if not response.is_success: - raise handle_error_response(response) + raise _handle_error_response(response) return AuthResponse(user=None, session=None) @handle_http_io @@ -391,7 +391,7 @@ def _update_user( method="PUT", path=["user"], body=_with_pkce_challenge(attributes, code_verifier), - query=redirect_to_as_query(email_redirect_to), + query=_redirect_to_as_query(email_redirect_to), headers=session.encode_access_token(), ) user_response = parse_user_response(response) @@ -474,10 +474,10 @@ def _reset_password_for_email( }, code_verifier, ), - query=redirect_to_as_query(redirect_to), + query=_redirect_to_as_query(redirect_to), ) if not response.is_success: - raise handle_error_response(response) + raise _handle_error_response(response) @handle_http_io def _get_session_from_url( @@ -485,7 +485,7 @@ def _get_session_from_url( url: str, ) -> HttpMethod[tuple[Session, str | None]]: result = URL(url) - if not is_implicit_grant_flow(result): + if not _is_implicit_grant_flow(result): raise AuthImplicitGrantRedirectError("Not a valid implicit grant flow url.") params = result.query error_description = params.get("error_description") @@ -549,7 +549,7 @@ def _get_url_for_provider( def _exchange_code_for_session( self, code_verifier: str | None, auth_code: str, redirect_to: str | None ) -> HttpMethod[AuthResponse]: - query = redirect_to_as_query(redirect_to).set("grant_type", "pkce") + query = _redirect_to_as_query(redirect_to).set("grant_type", "pkce") response = yield JSONRequest( method="POST", path=["token"], @@ -653,7 +653,7 @@ def __init__( user_headers = Headers.from_mapping(headers) if headers else Headers.empty() default_headers = supabase_headers.update(user_headers) executor = AsyncHttpIO(session=http_session) - self.session_manager: AsyncSessionManager = AsyncSessionManager( + self.session_manager: _AsyncSessionManager = _AsyncSessionManager( base_url=self.base_url, executor=executor, default_headers=default_headers, @@ -694,7 +694,7 @@ async def __aexit__( # Initializations async def initialize(self, *, url: str | None = None) -> None: - if url and is_implicit_grant_flow(URL(url)): + if url and _is_implicit_grant_flow(URL(url)): await self.initialize_from_url(url) else: await self.initialize_from_storage() @@ -704,7 +704,7 @@ async def initialize_from_storage(self) -> None: async def initialize_from_url(self, url: str) -> None: try: - if is_implicit_grant_flow(URL(url)): + if _is_implicit_grant_flow(URL(url)): session, redirect_type = await self._get_session_from_url(url) await self.session_manager.save_session(session) self.session_manager.notify_all_subscribers("SIGNED_IN", session) @@ -716,7 +716,7 @@ async def initialize_from_url(self, url: str) -> None: await self.session_manager.remove_session() raise e - async def save_session_and_sign_in(self, auth_response: AuthResponse) -> None: + async def _save_session_and_sign_in(self, auth_response: AuthResponse) -> None: await self.session_manager.remove_session() if auth_response.session: await self.session_manager.save_session(auth_response.session) @@ -771,7 +771,7 @@ async def exchange_code_for_session( await self.session_manager.storage.remove_item( self._code_verifier_storage_key ) - await self.save_session_and_sign_in(auth_response) + await self._save_session_and_sign_in(auth_response) return auth_response # Public methods @@ -783,7 +783,7 @@ async def sign_in_anonymously( Creates a new anonymous user. """ auth_response = await self._sign_in_anonymously(data, captcha_token) - await self.save_session_and_sign_in(auth_response) + await self._save_session_and_sign_in(auth_response) return auth_response async def sign_up( @@ -803,7 +803,7 @@ async def sign_up( await self.session_manager.storage.remove_item( self._code_verifier_storage_key ) - await self.save_session_and_sign_in(auth_response) + await self._save_session_and_sign_in(auth_response) return auth_response async def sign_in_with_password( @@ -814,7 +814,7 @@ async def sign_in_with_password( Log in an existing user with an email or phone and password. """ auth_response = await self._sign_in_with_password(credentials) - await self.save_session_and_sign_in(auth_response) + await self._save_session_and_sign_in(auth_response) return auth_response async def sign_in_with_id_token( @@ -831,7 +831,7 @@ async def sign_in_with_id_token( auth_response = await self._sign_in_with_id_token( provider, token, access_token, nonce, captcha_token ) - await self.save_session_and_sign_in(auth_response) + await self._save_session_and_sign_in(auth_response) return auth_response async def sign_in_with_oauth( @@ -930,7 +930,7 @@ async def verify_otp(self, params: VerifyOtpParams) -> AuthResponse: Log in a user given a User supplied OTP received via mobile. """ auth_response = await self._verify_otp(params) - await self.save_session_and_sign_in(auth_response) + await self._save_session_and_sign_in(auth_response) return auth_response async def reauthenticate(self) -> AuthResponse: @@ -1092,7 +1092,7 @@ def __init__( user_headers = Headers.from_mapping(headers) if headers else Headers.empty() default_headers = supabase_headers.update(user_headers) executor = SyncHttpIO(session=http_session) - self.session_manager: SyncSessionManager = SyncSessionManager( + self.session_manager: _SyncSessionManager = _SyncSessionManager( base_url=self.base_url, executor=executor, default_headers=default_headers, @@ -1133,7 +1133,7 @@ def __exit__( # Initializations def initialize(self, *, url: str | None = None) -> None: - if url and is_implicit_grant_flow(URL(url)): + if url and _is_implicit_grant_flow(URL(url)): self.initialize_from_url(url) else: self.initialize_from_storage() @@ -1143,7 +1143,7 @@ def initialize_from_storage(self) -> None: def initialize_from_url(self, url: str) -> None: try: - if is_implicit_grant_flow(URL(url)): + if _is_implicit_grant_flow(URL(url)): session, redirect_type = self._get_session_from_url(url) self.session_manager.save_session(session) self.session_manager.notify_all_subscribers("SIGNED_IN", session) @@ -1155,7 +1155,7 @@ def initialize_from_url(self, url: str) -> None: self.session_manager.remove_session() raise e - def save_session_and_sign_in(self, auth_response: AuthResponse) -> None: + def _save_session_and_sign_in(self, auth_response: AuthResponse) -> None: self.session_manager.remove_session() if auth_response.session: self.session_manager.save_session(auth_response.session) @@ -1204,7 +1204,7 @@ def exchange_code_for_session( ) finally: self.session_manager.storage.remove_item(self._code_verifier_storage_key) - self.save_session_and_sign_in(auth_response) + self._save_session_and_sign_in(auth_response) return auth_response # Public methods @@ -1216,7 +1216,7 @@ def sign_in_anonymously( Creates a new anonymous user. """ auth_response = self._sign_in_anonymously(data, captcha_token) - self.save_session_and_sign_in(auth_response) + self._save_session_and_sign_in(auth_response) return auth_response def sign_up( @@ -1234,7 +1234,7 @@ def sign_up( auth_response = self._sign_up(credentials, code_verifier) if code_verifier and auth_response.session: self.session_manager.storage.remove_item(self._code_verifier_storage_key) - self.save_session_and_sign_in(auth_response) + self._save_session_and_sign_in(auth_response) return auth_response def sign_in_with_password( @@ -1245,7 +1245,7 @@ def sign_in_with_password( Log in an existing user with an email or phone and password. """ auth_response = self._sign_in_with_password(credentials) - self.save_session_and_sign_in(auth_response) + self._save_session_and_sign_in(auth_response) return auth_response def sign_in_with_id_token( @@ -1262,7 +1262,7 @@ def sign_in_with_id_token( auth_response = self._sign_in_with_id_token( provider, token, access_token, nonce, captcha_token ) - self.save_session_and_sign_in(auth_response) + self._save_session_and_sign_in(auth_response) return auth_response def sign_in_with_oauth( @@ -1357,7 +1357,7 @@ def verify_otp(self, params: VerifyOtpParams) -> AuthResponse: Log in a user given a User supplied OTP received via mobile. """ auth_response = self._verify_otp(params) - self.save_session_and_sign_in(auth_response) + self._save_session_and_sign_in(auth_response) return auth_response def reauthenticate(self) -> AuthResponse: diff --git a/src/auth/src/supabase_auth/helpers.py b/src/auth/src/supabase_auth/helpers.py index e87437395..7daf4abca 100644 --- a/src/auth/src/supabase_auth/helpers.py +++ b/src/auth/src/supabase_auth/helpers.py @@ -49,7 +49,7 @@ TBaseModel = TypeVar("TBaseModel", bound=BaseModel) -def model_validate(model: Type[TBaseModel], contents: str | bytes) -> TBaseModel: +def _model_validate(model: Type[TBaseModel], contents: str | bytes) -> TBaseModel: """Compatibility layer between pydantic 1 and 2 for parsing an instance of a BaseModel from varied""" try: @@ -60,7 +60,7 @@ def model_validate(model: Type[TBaseModel], contents: str | bytes) -> TBaseModel return model.parse_raw(contents) -def model_dump(model: BaseModel) -> Dict[str, Any]: +def _model_dump(model: BaseModel) -> Dict[str, Any]: """Compatibility layer between pydantic 1 and 2 for dumping a model's contents as a dict""" try: # pydantic > 2 @@ -70,7 +70,7 @@ def model_dump(model: BaseModel) -> Dict[str, Any]: return model.dict() -def model_dump_json(model: BaseModel) -> str: +def _model_dump_json(model: BaseModel) -> str: """Compatibility layer between pydantic 1 and 2 for dumping a model's contents as json""" try: # pydantic > 2 @@ -82,25 +82,25 @@ def model_dump_json(model: BaseModel) -> str: def parse_auth_response(response: Response) -> AuthResponse: try: - session = validate_model(response, Session) + session = _validate_model(response, Session) user = session.user except ValidationError: session = None - user = validate_model(response, User) + user = _validate_model(response, User) return AuthResponse(user=user, session=session) def parse_auth_otp_response(response: Response) -> AuthOtpResponse: - return validate_model(response, AuthOtpResponse) + return _validate_model(response, AuthOtpResponse) def parse_link_identity_response(response: Response) -> LinkIdentityResponse: - return validate_model(response, LinkIdentityResponse) + return _validate_model(response, LinkIdentityResponse) def parse_link_response(response: Response) -> GenerateLinkResponse: - properties = validate_model(response, GenerateLinkProperties) - user = validate_model(response, User) + properties = _validate_model(response, GenerateLinkProperties) + user = _validate_model(response, User) return GenerateLinkResponse(properties=properties, user=user) @@ -112,11 +112,11 @@ def parse_user_response(response: Response) -> UserResponse: parsed = UserParser.validate_json(response.content) return UserResponse(user=parsed) if isinstance(parsed, User) else parsed else: - raise handle_error_response(response) + raise _handle_error_response(response) def parse_sso_response(response: Response) -> SSOResponse: - return model_validate(SSOResponse, response.content) + return _model_validate(SSOResponse, response.content) JWKSetParser = TypeAdapter(JWKSet) @@ -133,24 +133,24 @@ def parse_jwks(response: Response) -> JWKSet: Model = TypeVar("Model", bound=BaseModel) -def validate_model(response: Response, model: type[Model]) -> Model: +def _validate_model(response: Response, model: type[Model]) -> Model: if response.is_success: return model.model_validate_json(response.content) else: - raise handle_error_response(response) + raise _handle_error_response(response) Inner = TypeVar("Inner") -def validate_adapter(response: Response, adapter: TypeAdapter[Inner]) -> Inner: +def _validate_adapter(response: Response, adapter: TypeAdapter[Inner]) -> Inner: if response.is_success: return adapter.validate_json(response.content) else: - raise handle_error_response(response) + raise _handle_error_response(response) -def handle_error_response(response: Response) -> AuthError: +def _handle_error_response(response: Response) -> AuthError: try: raw_error = RawApiError.model_validate_json(response.content) except ValidationError: @@ -200,7 +200,7 @@ def handle_error_response(response: Response) -> AuthError: ) -def str_from_base64url(base64url: str) -> str: +def _str_from_base64url(base64url: str) -> str: # Addding padding otherwise the following error happens: # binascii.Error: Incorrect padding base64url_with_padding = base64url + "=" * (-len(base64url) % 4) @@ -311,7 +311,7 @@ def validate_uuid(id: str | None) -> None: raise ValueError(f"Invalid id, '{id}' is not a valid uuid") -def redirect_to_as_query(redirect_to: str | None) -> URLQuery: +def _redirect_to_as_query(redirect_to: str | None) -> URLQuery: if redirect_to: return URLQuery.from_mapping({"redirect_to": redirect_to}) return URLQuery.empty() diff --git a/src/auth/src/supabase_auth/mfa.py b/src/auth/src/supabase_auth/mfa.py index b68ac4314..f94ed1ff9 100644 --- a/src/auth/src/supabase_auth/mfa.py +++ b/src/auth/src/supabase_auth/mfa.py @@ -16,10 +16,10 @@ from .errors import AuthSessionMissingError from .helpers import ( + _validate_model, decode_jwt, - validate_model, ) -from .session import AsyncSessionManager, SyncSessionManager +from .session import _AsyncSessionManager, _SyncSessionManager from .types import ( AMREntry, AuthMFAChallengeResponse, @@ -54,7 +54,7 @@ def _enroll( body=params, headers=session.encode_access_token(), ) - auth_response = validate_model(response, AuthMFAEnrollResponse) + auth_response = _validate_model(response, AuthMFAEnrollResponse) if params.factor_type == "totp" and auth_response.totp: auth_response.totp.qr_code = ( f"data:image/svg+xml;utf-8,{auth_response.totp.qr_code}" @@ -73,7 +73,7 @@ def _challenge_http( body={"channel": channel}, headers=session.encode_access_token(), ) - return validate_model(response, AuthMFAChallengeResponse) + return _validate_model(response, AuthMFAChallengeResponse) @handle_http_io def _challenge( @@ -97,8 +97,8 @@ def _verify_http( }, headers=session.encode_access_token(), ) - auth_response = validate_model(response, AuthMFAVerifyResponse) - session = validate_model(response, Session) + auth_response = _validate_model(response, AuthMFAVerifyResponse) + session = _validate_model(response, Session) return auth_response, session @handle_http_io @@ -129,7 +129,7 @@ def _unenroll( path=["factors", factor_id], headers=session.encode_access_token(), ) - return validate_model(response, AuthMFAUnenrollResponse) + return _validate_model(response, AuthMFAUnenrollResponse) def _list_factors( self, user_response: UserResponse | None @@ -172,7 +172,7 @@ def _get_authenticator_assurance_level( @dataclass class AsyncSupabaseAuthMFAClient(SupabaseAuthMFAHttpClient[AsyncHttpIO]): - session_manager: AsyncSessionManager + session_manager: _AsyncSessionManager async def enroll(self, params: MFAEnrollParams) -> AuthMFAEnrollResponse: """ @@ -271,7 +271,7 @@ async def get_authenticator_assurance_level( @dataclass class SyncSupabaseAuthMFAClient(SupabaseAuthMFAHttpClient[SyncHttpIO]): - session_manager: SyncSessionManager + session_manager: _SyncSessionManager def enroll(self, params: MFAEnrollParams) -> AuthMFAEnrollResponse: """ diff --git a/src/auth/src/supabase_auth/session.py b/src/auth/src/supabase_auth/session.py index 6822e9d27..6e1b25b3e 100644 --- a/src/auth/src/supabase_auth/session.py +++ b/src/auth/src/supabase_auth/session.py @@ -22,7 +22,7 @@ from .constants import EXPIRY_MARGIN, MAX_RETRIES, RETRY_INTERVAL, STORAGE_KEY from .errors import AuthRetryableError, AuthSessionMissingError from .helpers import parse_auth_response, parse_user_response -from .timer import AsyncTimer, SyncTimer +from .timer import _AsyncTimer, _SyncTimer from .types import AuthChangeEvent, AuthResponse, Session, Subscription, UserResponse logger = logging.getLogger(__name__) @@ -57,7 +57,7 @@ async def remove_item(self, key: str) -> None: @dataclass -class SessionManagerCommon(Generic[HttpIO]): +class _SessionManagerCommon(Generic[HttpIO]): """ Common methods shared between sync and async implementations of the session manager. @@ -131,9 +131,9 @@ def notify_all_subscribers( @dataclass -class AsyncSessionManager(SessionManagerCommon[AsyncHttpIO]): +class _AsyncSessionManager(_SessionManagerCommon[AsyncHttpIO]): storage: AsyncSupportedStorage - refresh_token_timer: AsyncTimer | None = None + refresh_token_timer: _AsyncTimer | None = None async def __aexit__( self, @@ -144,7 +144,7 @@ async def __aexit__( if self.refresh_token_timer: self.refresh_token_timer.cancel() - async def __aenter__(self) -> AsyncSessionManager: + async def __aenter__(self) -> _AsyncSessionManager: return self async def remove_session(self) -> None: @@ -239,7 +239,7 @@ async def recover_and_refresh(self) -> None: ): if self.refresh_token_timer: self.refresh_token_timer.cancel() - self.refresh_token_timer = AsyncTimer( + self.refresh_token_timer = _AsyncTimer( (RETRY_INTERVAL ** (2 * (self.network_retries - 1))), self.recover_and_refresh, ) @@ -271,7 +271,7 @@ def start_auto_refresh_token(self, value: float) -> None: if value <= 0 or not self.auto_refresh_token: return - self.refresh_token_timer = AsyncTimer(value, self.refresh_token_function) + self.refresh_token_timer = _AsyncTimer(value, self.refresh_token_function) self.refresh_token_timer.start() @@ -304,9 +304,9 @@ def remove_item(self, key: str) -> None: @dataclass -class SyncSessionManager(SessionManagerCommon[SyncHttpIO]): +class _SyncSessionManager(_SessionManagerCommon[SyncHttpIO]): storage: SyncSupportedStorage - refresh_token_timer: SyncTimer | None = None + refresh_token_timer: _SyncTimer | None = None def __exit__( self, @@ -317,7 +317,7 @@ def __exit__( if self.refresh_token_timer: self.refresh_token_timer.cancel() - def __enter__(self) -> SyncSessionManager: + def __enter__(self) -> _SyncSessionManager: return self def remove_session(self) -> None: @@ -425,7 +425,7 @@ def recover_and_refresh(self) -> None: ): if self.refresh_token_timer: self.refresh_token_timer.cancel() - self.refresh_token_timer = SyncTimer( + self.refresh_token_timer = _SyncTimer( (RETRY_INTERVAL ** (2 * (self.network_retries - 1))), self.recover_and_refresh, ) @@ -444,5 +444,5 @@ def start_auto_refresh_token(self, value: float) -> None: if value <= 0 or not self.auto_refresh_token: return - self.refresh_token_timer = SyncTimer(value, self.refresh_token_function) + self.refresh_token_timer = _SyncTimer(value, self.refresh_token_function) self.refresh_token_timer.start() diff --git a/src/auth/src/supabase_auth/timer.py b/src/auth/src/supabase_auth/timer.py index 4d4fd2c60..ad56987f8 100644 --- a/src/auth/src/supabase_auth/timer.py +++ b/src/auth/src/supabase_auth/timer.py @@ -3,7 +3,7 @@ from typing import Awaitable, Callable -class AsyncTimer: +class _AsyncTimer: def __init__( self, seconds: float, @@ -33,7 +33,7 @@ def is_alive(self) -> bool: return self._task is not None -class SyncTimer: +class _SyncTimer: def __init__( self, seconds: float, diff --git a/src/auth/tests/test_helpers.py b/src/auth/tests/test_helpers.py index b86c863b3..b534023c2 100644 --- a/src/auth/tests/test_helpers.py +++ b/src/auth/tests/test_helpers.py @@ -17,10 +17,10 @@ AuthWeakPasswordError, ) from supabase_auth.helpers import ( + _handle_error_response, decode_jwt, generate_pkce_challenge, generate_pkce_verifier, - handle_error_response, parse_link_identity_response, parse_response_api_version, validate_exp, @@ -146,7 +146,7 @@ def error_response(status: int, body: Any) -> Response: def test_handle_error_response_legacy_weak_password_without_error_code() -> None: - result = handle_error_response( + result = _handle_error_response( error_response( 422, { @@ -175,7 +175,7 @@ def test_handle_error_response_legacy_weak_password_without_error_code() -> None def test_handle_error_response_legacy_weak_password_ignores_malformed_reasons( weak_password: Any, ) -> None: - result = handle_error_response( + result = _handle_error_response( error_response( 422, {"message": "Password too weak", "weak_password": weak_password}, @@ -189,7 +189,7 @@ def test_handle_error_response_legacy_weak_password_ignores_malformed_reasons( def test_handle_error_response_weak_password_with_error_code() -> None: - result = handle_error_response( + result = _handle_error_response( error_response( 422, { diff --git a/src/functions/src/supabase_functions/client.py b/src/functions/src/supabase_functions/client.py index 4e0af7614..957324f79 100644 --- a/src/functions/src/supabase_functions/client.py +++ b/src/functions/src/supabase_functions/client.py @@ -23,7 +23,7 @@ from supabase_utils.types import JSON from yarl import URL -from .errors import _is_relay_error, on_error_response +from .errors import _is_relay_error, _on_error_response from .utils import ( FunctionRegion, is_valid_str_arg, @@ -136,7 +136,7 @@ def invoke( function_name, body, region, headers, method ) if _is_relay_error(response) or not response.is_success: - raise on_error_response(response) + raise _on_error_response(response) return response diff --git a/src/functions/src/supabase_functions/errors.py b/src/functions/src/supabase_functions/errors.py index 3f32590a8..3e7b12c32 100644 --- a/src/functions/src/supabase_functions/errors.py +++ b/src/functions/src/supabase_functions/errors.py @@ -55,7 +55,7 @@ def _error_message_from(response: Response) -> str | None: return response.content.decode("utf-8", errors="replace") or None -def on_error_response(response: Response) -> FunctionsHttpError | FunctionsRelayError: +def _on_error_response(response: Response) -> FunctionsHttpError | FunctionsRelayError: if _is_relay_error(response): return FunctionsRelayError( response.content.decode("utf-8", errors="replace"), code=response.status diff --git a/src/functions/tests/test_errors.py b/src/functions/tests/test_errors.py index ad6bdc243..3d4616267 100644 --- a/src/functions/tests/test_errors.py +++ b/src/functions/tests/test_errors.py @@ -11,7 +11,7 @@ FunctionsHttpError, FunctionsRelayError, _error_message_from, - on_error_response, + _on_error_response, ) @@ -150,20 +150,20 @@ def test_error_message_from(content: bytes, expected: str | None) -> None: def test_on_error_response_http_error() -> None: - error = on_error_response(make_response(b'{"error": "boom"}', status=404)) + error = _on_error_response(make_response(b'{"error": "boom"}', status=404)) assert isinstance(error, FunctionsHttpError) assert error.message == "boom" assert error.status == 404 def test_on_error_response_http_error_fallback_message() -> None: - error = on_error_response(make_response(b"", status=500)) + error = _on_error_response(make_response(b"", status=500)) assert isinstance(error, FunctionsHttpError) assert "https://example.com/test-function" in error.message def test_on_error_response_relay_error_keeps_raw_text() -> None: - error = on_error_response( + error = _on_error_response( make_response( b'{"error": "relay"}', status=546, diff --git a/src/postgrest/src/postgrest/request_builder.py b/src/postgrest/src/postgrest/request_builder.py index 59834490e..f1e449d79 100644 --- a/src/postgrest/src/postgrest/request_builder.py +++ b/src/postgrest/src/postgrest/request_builder.py @@ -39,7 +39,7 @@ from .exceptions import APIError, APIErrorFromJSON, generate_default_error_message from .types import CountMethod, Filters, FilterValue, ReturnMethod -from .utils import _sanitize_array_param, model_validate_json, sanitize_param +from .utils import _model_validate_json, _sanitize_array_param, sanitize_param if sys.version_info >= (3, 11): from typing import Self @@ -669,13 +669,13 @@ def retry(self, enabled: bool) -> Self: def _api_error(response: Response) -> APIError: try: - json_obj = model_validate_json(APIErrorFromJSON, response.content) + json_obj = _model_validate_json(APIErrorFromJSON, response.content) except ValidationError: return APIError(generate_default_error_message(response)) return APIError(dict(json_obj)) -def can_retry(resp: Response, retry_enabled: bool, attempt_count: int) -> bool: +def _can_retry(resp: Response, retry_enabled: bool, attempt_count: int) -> bool: if not retry_enabled or attempt_count >= MAX_RETRIES: return False if not (resp.request.method == "GET" or resp.request.method == "HEAD"): @@ -688,7 +688,7 @@ def send_with_retry(req: PostgrestRequest) -> HttpMethod[Response]: attempt = req while True: resp = yield attempt - if resp.is_success or not can_retry(resp, req.retry, attempt_count): + if resp.is_success or not _can_retry(resp, req.retry, attempt_count): break attempt_count += 1 attempt = copy.copy(req) diff --git a/src/postgrest/src/postgrest/utils.py b/src/postgrest/src/postgrest/utils.py index f0a3ffc55..fc7a98553 100644 --- a/src/postgrest/src/postgrest/utils.py +++ b/src/postgrest/src/postgrest/utils.py @@ -69,10 +69,6 @@ def _sanitize_array_param(values: Iterable[Any]) -> str: return f"{{{','.join(_sanitize_array_element(value) for value in values)}}}" -def sanitize_pattern_param(pattern: str) -> str: - return sanitize_param(pattern.replace("%", "*")) - - def _rpc_query_param(value: Any) -> Any: """Format an RPC argument sent in the query string, as in GET or HEAD calls. @@ -97,7 +93,7 @@ def is_http_url(url: URL) -> bool: TBaseModel = TypeVar("TBaseModel", bound=BaseModel) -def model_validate_json(model: Type[TBaseModel], contents) -> TBaseModel: +def _model_validate_json(model: Type[TBaseModel], contents) -> TBaseModel: """Compatibility layer between pydantic 1 and 2 for parsing an instance of a BaseModel from varied""" try: diff --git a/src/postgrest/tests/_async/test_request_builder.py b/src/postgrest/tests/_async/test_request_builder.py index f64b6f012..b5d10de93 100644 --- a/src/postgrest/tests/_async/test_request_builder.py +++ b/src/postgrest/tests/_async/test_request_builder.py @@ -16,7 +16,7 @@ SingleAPIResponse, SingleRequestBuilder, TextRequestBuilder, - can_retry, + _can_retry, ) from postgrest.types import CountMethod, ReturnMethod @@ -42,7 +42,7 @@ def test_select_request_retries_transient_response( status=503, headers=Headers.empty(), content=b"", request=request ) - assert can_retry(response, retry_enabled=True, attempt_count=0) + assert _can_retry(response, retry_enabled=True, attempt_count=0) class TestSelect: diff --git a/src/postgrest/tests/_sync/test_request_builder.py b/src/postgrest/tests/_sync/test_request_builder.py index 532320848..a72bff2f8 100644 --- a/src/postgrest/tests/_sync/test_request_builder.py +++ b/src/postgrest/tests/_sync/test_request_builder.py @@ -16,7 +16,7 @@ SingleAPIResponse, SingleRequestBuilder, TextRequestBuilder, - can_retry, + _can_retry, ) from postgrest.types import CountMethod, ReturnMethod @@ -42,7 +42,7 @@ def test_select_request_retries_transient_response( status=503, headers=Headers.empty(), content=b"", request=request ) - assert can_retry(response, retry_enabled=True, attempt_count=0) + assert _can_retry(response, retry_enabled=True, attempt_count=0) class TestSelect: diff --git a/src/realtime/src/realtime/channel.py b/src/realtime/src/realtime/channel.py index 938fae32e..b2dd8de9a 100644 --- a/src/realtime/src/realtime/channel.py +++ b/src/realtime/src/realtime/channel.py @@ -255,7 +255,7 @@ async def subscribe(self) -> ReplyMessage: ref=join_ref, join_ref=join_ref, ) - msg = await self.socket.send(message) + msg = await self.socket._send(message) logger.info(f"Subscribe reply: {msg!r}") if msg.payload.status != "ok": raise Exception( @@ -269,7 +269,7 @@ async def subscribe(self) -> ReplyMessage: async def messages(self) -> AsyncIterator[ChannelMessage]: while True: get_task = asyncio.create_task(self.message_stream.get()) - message = await self.socket.get_message_or_raise(get_task) + message = await self.socket._get_message_or_raise(get_task) server_message = ServerMessageAdapter.validate_python(message) if isinstance(server_message, PresenceStateMessage): for presence_event in self.presence._on_state_event( @@ -288,7 +288,7 @@ async def unsubscribe(self) -> None: self.state = ChannelStates.LEAVING self.socket._remove_channel(self) try: - await self.send_event(ChannelEvents.leave, payload={}) + await self._send_event(ChannelEvents.leave, payload={}) finally: self.state = ChannelStates.CLOSED self.message_stream.put_nowait( @@ -324,7 +324,7 @@ def presence_state(self) -> RealtimePresenceState: """ return self.presence.state - async def send_event( + async def _send_event( self, event: ChannelEvents, payload: Mapping[str, JSON] ) -> ReplyMessage: message = Message( @@ -334,9 +334,9 @@ async def send_event( join_ref=self.join_ref, payload=payload, ) - return await self.socket.send(message) + return await self.socket._send(message) - async def send_event_no_wait( + async def _send_event_no_wait( self, event: ChannelEvents, payload: Mapping[str, JSON] ) -> None: message = Message( @@ -346,7 +346,7 @@ async def send_event_no_wait( join_ref=self.join_ref, payload=payload, ) - return await self.socket.send_no_wait(message) + return await self.socket._send_no_wait(message) # Broadcast methods async def send_broadcast(self, event: str, data: JSON) -> ReplyMessage | None: @@ -358,9 +358,9 @@ async def send_broadcast(self, event: str, data: JSON) -> ReplyMessage | None: """ payload = {"type": "broadcast", "event": event, "payload": data} if self.params.broadcast_ack: - return await self.send_event(ChannelEvents.broadcast, payload) + return await self._send_event(ChannelEvents.broadcast, payload) else: - await self.send_event_no_wait(ChannelEvents.broadcast, payload) + await self._send_event_no_wait(ChannelEvents.broadcast, payload) return None # Internal methods @@ -369,6 +369,6 @@ def _broadcast_endpoint_url(self): return self.socket.http_endpoint.joinpath("api", "broadcast") async def send_presence(self, event: str, data: JSON) -> ReplyMessage: - return await self.send_event( + return await self._send_event( ChannelEvents.presence, {"event": event, "payload": data} ) diff --git a/src/realtime/src/realtime/client.py b/src/realtime/src/realtime/client.py index 109a5570e..94c319659 100644 --- a/src/realtime/src/realtime/client.py +++ b/src/realtime/src/realtime/client.py @@ -219,7 +219,7 @@ async def close(self) -> None: await self._ws_connection.close() - async def get_message_or_raise(self, fut: asyncio.Future[Message]) -> Message: + async def _get_message_or_raise(self, fut: asyncio.Future[Message]) -> Message: done, pending = await asyncio.wait( (fut, self._connection_failure), return_when=asyncio.FIRST_COMPLETED ) @@ -240,7 +240,7 @@ async def heartbeat(self) -> None: ) logger.info("sending heartbeat") res = await asyncio.wait_for( - self.send(data), timeout=self.heartbeat_timeout + self._send(data), timeout=self.heartbeat_timeout ) logger.info(f"heartbeat response: {res!r}") await self.set_auth() @@ -334,7 +334,7 @@ async def set_auth(self, token: str | None = None) -> None: results = await asyncio.gather( *( - channel.send_event_no_wait( + channel._send_event_no_wait( ChannelEvents.access_token, {"access_token": token} ) for channel in list(self.channels.values()) @@ -351,7 +351,7 @@ def _make_ref(self) -> str: self.ref += 1 return f"{self.ref}" - async def send(self, message: Message) -> ReplyMessage: + async def _send(self, message: Message) -> ReplyMessage: assert message.ref, "Cannot wait for reponse on a message without ref" message_str = message.model_dump_json() @@ -362,13 +362,13 @@ async def send(self, message: Message) -> ReplyMessage: try: await self._ws_connection.send(message_str) logger.debug(f"waiting for ref='{message.ref}'") - response = await self.get_message_or_raise(receive) + response = await self._get_message_or_raise(receive) finally: del self.message_refs[message.ref] return ReplyMessage.model_validate(response) - async def send_no_wait(self, message: Message) -> None: + async def _send_no_wait(self, message: Message) -> None: message_str = message.model_dump_json() logger.debug(f"sending: {message_str}") await self._ws_connection.send(message_str) diff --git a/src/realtime/tests/test_unknown_refs.py b/src/realtime/tests/test_unknown_refs.py index dbdd62d46..9b3797a7d 100644 --- a/src/realtime/tests/test_unknown_refs.py +++ b/src/realtime/tests/test_unknown_refs.py @@ -89,7 +89,7 @@ async def test_orphan_reply_is_not_forwarded_to_the_channel(server: FakeServer): async with connect_once(f"http://{URL}:{PORT}", get_token) as client: channel = client.channel("room") await channel.subscribe() - await channel.socket.send_no_wait( + await channel.socket._send_no_wait( Message(topic=channel.topic, event=ChannelEvents.leave, payload={}, ref="x") ) await asyncio.sleep(0.1) diff --git a/src/storage/src/storage3/analytics.py b/src/storage/src/storage3/analytics.py index 06fbf80a4..c2b980103 100644 --- a/src/storage/src/storage3/analytics.py +++ b/src/storage/src/storage3/analytics.py @@ -16,7 +16,7 @@ ) from yarl import URL -from .exceptions import validate_adapter, validate_model +from .exceptions import _validate_adapter, _validate_model from .types import ( AnalyticsBucket, AnalyticsBucketDeleteResponse, @@ -43,7 +43,7 @@ def create(self, bucket_name: str) -> HttpMethod[AnalyticsBucket]: path=["bucket"], body=body, ) - return validate_model(response, AnalyticsBucket) + return _validate_model(response, AnalyticsBucket) @handle_http_io def list( @@ -69,7 +69,7 @@ def list( path=["bucket"], query=filtered_params, ) - return validate_adapter(response, AnalyticsBucketsParser) + return _validate_adapter(response, AnalyticsBucketsParser) @handle_http_io def delete(self, bucket_name: str) -> HttpMethod[AnalyticsBucketDeleteResponse]: @@ -77,7 +77,7 @@ def delete(self, bucket_name: str) -> HttpMethod[AnalyticsBucketDeleteResponse]: method="DELETE", path=["bucket", bucket_name], ) - return validate_model(response, AnalyticsBucketDeleteResponse) + return _validate_model(response, AnalyticsBucketDeleteResponse) def catalog( self, catalog_name: str, access_key_id: str, secret_access_key: str diff --git a/src/storage/src/storage3/client.py b/src/storage/src/storage3/client.py index c259a89b9..6cad8709a 100644 --- a/src/storage/src/storage3/client.py +++ b/src/storage/src/storage3/client.py @@ -19,7 +19,7 @@ from yarl import URL from .analytics import StorageAnalyticsClient -from .exceptions import validate_adapter, validate_model +from .exceptions import _validate_adapter, _validate_model from .file_api import StorageFileApiClient from .types import Bucket, BucketName, CreateOrUpdateBucketBody, MessageResponse from .vectors import StorageVectorsClient @@ -86,7 +86,7 @@ def list_buckets(self) -> HttpMethod[list[Bucket]]: method="GET", path=["bucket"], ) - return validate_adapter(response, ListBucketAdapter) + return _validate_adapter(response, ListBucketAdapter) @handle_http_io def get_bucket(self, id: str) -> HttpMethod[Bucket]: @@ -101,7 +101,7 @@ def get_bucket(self, id: str) -> HttpMethod[Bucket]: method="GET", path=["bucket", id], ) - return validate_model(response, Bucket) + return _validate_model(response, Bucket) @handle_http_io def create_bucket( @@ -138,7 +138,7 @@ def create_bucket( exclude_none=True, ) - return validate_model(response, BucketName) + return _validate_model(response, BucketName) @handle_http_io def update_bucket( @@ -171,7 +171,7 @@ def update_bucket( body=body, exclude_none=True, ) - return validate_model(response, MessageResponse) + return _validate_model(response, MessageResponse) @handle_http_io def empty_bucket(self, id: str) -> HttpMethod[MessageResponse]: @@ -187,7 +187,7 @@ def empty_bucket(self, id: str) -> HttpMethod[MessageResponse]: path=["bucket", id, "empty"], ) - return validate_model(response, MessageResponse) + return _validate_model(response, MessageResponse) @handle_http_io def delete_bucket(self, id: str) -> HttpMethod[MessageResponse]: @@ -203,7 +203,7 @@ def delete_bucket(self, id: str) -> HttpMethod[MessageResponse]: method="DELETE", path=["bucket", id], ) - return validate_model(response, MessageResponse) + return _validate_model(response, MessageResponse) class AsyncStorageClient(StorageClient[AsyncHttpIO]): diff --git a/src/storage/src/storage3/exceptions.py b/src/storage/src/storage3/exceptions.py index 5b6deeeb3..89fe721ce 100644 --- a/src/storage/src/storage3/exceptions.py +++ b/src/storage/src/storage3/exceptions.py @@ -62,7 +62,7 @@ def parse_api_error(response: Response) -> StorageApiError: Inner = TypeVar("Inner") -def validate_adapter(response: Response, type_adapter: TypeAdapter[Inner]) -> Inner: +def _validate_adapter(response: Response, type_adapter: TypeAdapter[Inner]) -> Inner: if response.is_success: return type_adapter.validate_json(response.content) raise parse_api_error(response) @@ -71,7 +71,7 @@ def validate_adapter(response: Response, type_adapter: TypeAdapter[Inner]) -> In Model = TypeVar("Model", bound=BaseModel) -def validate_model(response: Response, model: type[Model]) -> Model: +def _validate_model(response: Response, model: type[Model]) -> Model: if response.is_success: return model.model_validate_json(response.content) raise parse_api_error(response) diff --git a/src/storage/src/storage3/file_api.py b/src/storage/src/storage3/file_api.py index 4f92a0a6a..818266a14 100644 --- a/src/storage/src/storage3/file_api.py +++ b/src/storage/src/storage3/file_api.py @@ -25,7 +25,7 @@ from supabase_utils.types import JSONParser from yarl import URL -from .exceptions import parse_api_error, validate_adapter, validate_model +from .exceptions import _validate_adapter, _validate_model, parse_api_error from .types import ( CreateSignedUrlBody, CreateSignedUrlResponse, @@ -57,7 +57,7 @@ def relative_path_to_parts(path: str) -> Tuple[str, ...]: return url.parts -def maybe_read_file(file: BufferedReader | bytes | FileIO | str | Path) -> bytes: +def _maybe_read_file(file: BufferedReader | bytes | FileIO | str | Path) -> bytes: if isinstance(file, (BufferedReader, FileIO)): # bytes or byte-stream-like object received return file.read() @@ -170,7 +170,7 @@ def upload_to_signed_url( file_field = FileField( name="file", filename=path_parts[-1], - data=maybe_read_file(file), + data=_maybe_read_file(file), content_type=content_type, ) fields.append(file_field) @@ -182,7 +182,7 @@ def upload_to_signed_url( query=query_params, ) - return validate_model(response, UploadResponse) + return _validate_model(response, UploadResponse) def _make_signed_url(self, signed_url: str, download_query: URLQuery) -> str: url = URL(signed_url[1:]) # ignore starting slash @@ -341,7 +341,7 @@ def move(self, from_path: str, to_path: str) -> HttpMethod[MessageResponse]: "destinationKey": to_path, }, ) - return validate_model(response, MessageResponse) + return _validate_model(response, MessageResponse) @handle_http_io def copy(self, from_path: str, to_path: str) -> HttpMethod[UploadResponse]: @@ -365,7 +365,7 @@ def copy(self, from_path: str, to_path: str) -> HttpMethod[UploadResponse]: }, ) - return validate_model(response, UploadResponse) + return _validate_model(response, UploadResponse) @handle_http_io def remove(self, paths: list[str]) -> HttpMethod[list[FileObject]]: @@ -382,7 +382,7 @@ def remove(self, paths: list[str]) -> HttpMethod[list[FileObject]]: path=["object", self.id], body={"prefixes": paths}, ) - return validate_adapter(response, FileObjectsAdapter) + return _validate_adapter(response, FileObjectsAdapter) @handle_http_io def info( @@ -402,7 +402,7 @@ def info( method="GET", path=["object", "info", self.id, *path_parts], ) - return validate_model(response, FileObject) + return _validate_model(response, FileObject) @handle_http_io def exists( @@ -460,7 +460,7 @@ def list( path=["object", "list", self.id], body=body, ) - return validate_adapter(response, ListFileObjectsAdapter) + return _validate_adapter(response, ListFileObjectsAdapter) @handle_http_io def list_v2( @@ -484,7 +484,7 @@ def list_v2( body=body, exclude_none=True, ) - return validate_model(response, SearchV2Result) + return _validate_model(response, SearchV2Result) @handle_http_io def download( @@ -567,7 +567,7 @@ def _upload_or_update( file_field = FileField( name="file", filename=path[-1], - data=maybe_read_file(file), + data=_maybe_read_file(file), content_type=content_type, ) fields.append(file_field) @@ -578,7 +578,7 @@ def _upload_or_update( headers=http_headers, ) - return validate_model(response, UploadResponse) + return _validate_model(response, UploadResponse) @handle_http_io def upload( diff --git a/src/storage/src/storage3/vectors.py b/src/storage/src/storage3/vectors.py index 0b0731691..090f48ccf 100644 --- a/src/storage/src/storage3/vectors.py +++ b/src/storage/src/storage3/vectors.py @@ -13,7 +13,7 @@ from supabase_utils.types import JSON from yarl import URL -from .exceptions import VectorBucketException, parse_api_error, validate_model +from .exceptions import VectorBucketException, _validate_model, parse_api_error from .types import ( DistanceMetric, GetVectorBucketResponse, @@ -43,7 +43,7 @@ class VectorBucketScope(Generic[HttpIO]): bucket_name: str executor: HttpIO - def with_metadata(self, **data: JSON) -> JSON: + def _with_metadata(self, **data: JSON) -> JSON: return remove_none(vectorBucketName=self.bucket_name, **data) @handle_http_io @@ -55,7 +55,7 @@ def create_index( data_type: str, metadata: MetadataConfiguration | None = None, ) -> HttpMethod[None]: - body = self.with_metadata( + body = self._with_metadata( indexName=index_name, dimension=dimension, distanceMetric=distance_metric, @@ -74,7 +74,7 @@ def create_index( @handle_http_io def get_index(self, index_name: str) -> HttpMethod[GetVectorIndexResponse | None]: - body = self.with_metadata(indexName=index_name) + body = self._with_metadata(indexName=index_name) response = yield JSONRequest( method="POST", path=["GetIndex"], @@ -94,7 +94,7 @@ def list_indexes( max_results: int | None = None, prefix: str | None = None, ) -> HttpMethod[ListVectorIndexesResponse]: - body = self.with_metadata( + body = self._with_metadata( nextToken=next_token, maxResults=max_results, prefix=prefix ) response = yield JSONRequest( @@ -102,11 +102,11 @@ def list_indexes( path=["ListIndexes"], body=body, ) - return validate_model(response, ListVectorIndexesResponse) + return _validate_model(response, ListVectorIndexesResponse) @handle_http_io def delete_index(self, index_name: str) -> HttpMethod[None]: - body = self.with_metadata(indexName=index_name) + body = self._with_metadata(indexName=index_name) response = yield JSONRequest(method="POST", path=["DeleteIndex"], body=body) if not response.is_success: raise parse_api_error(response) @@ -129,7 +129,7 @@ class VectorIndexScope(Generic[HttpIO]): default_headers: Headers base_url: URL - def with_metadata(self, **data: JSON) -> JSON: + def _with_metadata(self, **data: JSON) -> JSON: return remove_none( vectorBucketName=self.bucket_name, indexName=self.index_name, @@ -138,7 +138,7 @@ def with_metadata(self, **data: JSON) -> JSON: @handle_http_io def put(self, vectors: List[VectorObject]) -> HttpMethod[None]: - body = self.with_metadata( + body = self._with_metadata( vectors=[v.model_dump(exclude_none=True) for v in vectors] ) response = yield JSONRequest( @@ -153,7 +153,7 @@ def put(self, vectors: List[VectorObject]) -> HttpMethod[None]: def get( self, *keys: str, return_data: bool = True, return_metadata: bool = True ) -> HttpMethod[GetVectorsResponse]: - body = self.with_metadata( + body = self._with_metadata( keys=keys, returnData=return_data, returnMetadata=return_metadata, @@ -163,7 +163,7 @@ def get( path=["GetVectors"], body=body, ) - return validate_model(response, GetVectorsResponse) + return _validate_model(response, GetVectorsResponse) @handle_http_io def list( @@ -175,7 +175,7 @@ def list( segment_count: int | None = None, segment_index: int | None = None, ) -> HttpMethod[ListVectorsResponse]: - body = self.with_metadata( + body = self._with_metadata( maxResults=max_results, nextToken=next_token, returnData=return_data, @@ -188,7 +188,7 @@ def list( path=["ListVectors"], body=body, ) - return validate_model(response, ListVectorsResponse) + return _validate_model(response, ListVectorsResponse) @handle_http_io def query( @@ -199,7 +199,7 @@ def query( return_distance: bool = True, return_metadata: bool = True, ) -> HttpMethod[QueryVectorsResponse]: - body = self.with_metadata( + body = self._with_metadata( queryVector=dict(query_vector), topK=topK, filter=filter, @@ -211,13 +211,13 @@ def query( path=["QueryVectors"], body=body, ) - return validate_model(response, QueryVectorsResponse) + return _validate_model(response, QueryVectorsResponse) @handle_http_io def delete(self, keys: List[str]) -> HttpMethod[None]: if len(keys) < 1 or len(keys) > 500: raise VectorBucketException("Keys batch size must be between 1 and 500.") - body = self.with_metadata(keys=keys) + body = self._with_metadata(keys=keys) response = yield JSONRequest( method="POST", path=["DeleteVectors"], @@ -283,7 +283,7 @@ def list_buckets( body=body, exclude_none=True, ) - return validate_model(response, ListVectorBucketsResponse) + return _validate_model(response, ListVectorBucketsResponse) @handle_http_io def delete_bucket(self, bucket_name: str) -> HttpMethod[None]: From 01caa7bce4926819970633892689371271ca244a Mon Sep 17 00:00:00 2001 From: Lukas Klingsbo Date: Tue, 3 Nov 2026 19:08:57 +0100 Subject: [PATCH 2/2] chore: mark auth auto refresh as having no public symbols --- sdk-compliance.yaml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/sdk-compliance.yaml b/sdk-compliance.yaml index f51ff1706..51e2637f6 100644 --- a/sdk-compliance.yaml +++ b/sdk-compliance.yaml @@ -181,9 +181,7 @@ features: auth.session.auto_refresh: status: implemented note: "Token refresh runs automatically as an internal background task controlled by the auto_refresh_token constructor option." - symbols: - - AsyncSessionManager.start_auto_refresh_token - - SyncSessionManager.start_auto_refresh_token + no_public_symbols: true auth.session.sign_out_reason: not_implemented auth.identities.link_identity: