From ea2c17dc897383e6ecbebc8e645eff0ad9620447 Mon Sep 17 00:00:00 2001 From: Lukas Klingsbo Date: Fri, 6 Nov 2026 17:19:58 +0100 Subject: [PATCH 1/3] feat(supabase)!: replace ClientOptions with keyword arguments and per-service options --- MIGRATION.md | 78 +++-- sdk-compliance.yaml | 30 +- src/supabase/README.md | 18 ++ src/supabase/src/supabase/__init__.py | 5 - src/supabase/src/supabase/aiohttp.py | 39 ++- src/supabase/src/supabase/client.py | 266 ++++++++++++++---- src/supabase/src/supabase/httpx.py | 65 ++++- src/supabase/src/supabase/lib/__init__.py | 1 - .../src/supabase/lib/client_options.py | 153 ---------- src/supabase/src/supabase/types.py | 35 ++- src/supabase/tests/_async/conftest.py | 20 +- src/supabase/tests/_async/test_client.py | 83 +++--- src/supabase/tests/_sync/conftest.py | 12 +- src/supabase/tests/_sync/test_client.py | 77 +++-- src/supabase/tests/test_client.py | 213 +++++++++++--- src/supabase/tests/test_client_options.py | 185 +++--------- 16 files changed, 715 insertions(+), 565 deletions(-) delete mode 100644 src/supabase/src/supabase/lib/__init__.py delete mode 100644 src/supabase/src/supabase/lib/client_options.py diff --git a/MIGRATION.md b/MIGRATION.md index e4f32ab63..dc05f3a53 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -16,7 +16,7 @@ Abbreviated and contracted public names are spelled out. Wire formats do not cha | `realtime` | `PresenceOpts` | `PresenceOptions` | | `realtime` | `VSN` | `PROTOCOL_VERSION` | | `supabase` | `RealtimeClientOptions` keys `hb_interval`, `hb_timeout` | `heartbeat_interval`, `heartbeat_timeout` | -| `supabase` | `AClient`, `AClientOptions` | `AsyncClient`, `AsyncClientOptions` | +| `supabase` | `AClient` | `AsyncClient` | | `supabase` | `ASupabaseException` | `SupabaseException` | | `supabase` | `ASupabaseStorageClient` | `storage3.AsyncStorageClient` | | `supabase` | `httpx.create_aclient`, `aiohttp.create_aclient` | `httpx.create_async_client`, `aiohttp.create_async_client` | @@ -52,45 +52,83 @@ Names that mirror a wire format keep their wire spelling, for example the JWT cl | `from supabase._async.client import AsyncClient` | `from supabase import AsyncClient` | | `from supabase._sync.client import Client` | `from supabase import Client` | | `AsyncSupabaseException`, `SyncSupabaseException` | `SupabaseException` | -| `SyncClientOptions` | `ClientOptions` | | `supabase.SupabaseStorageClient` | `storage3.SyncStorageClient` | | `supabase.client.AsyncSupabaseStorageClient` | `storage3.AsyncStorageClient` | | `client.rpc("fn", {"a": 1}, CountMethod.exact)` | `client.rpc("fn", {"a": 1}, count=CountMethod.exact)` | | `client.rpc("fn", {"a": 1}, None, True)` | `client.rpc("fn", {"a": 1}, head=True)` | -`ClientOptions` configures `Client` and `AsyncClientOptions` configures `AsyncClient`. `supabase.lib.client_options.ClientOptions` used to be their shared base class and is now the sync options class as well. - `rpc` takes `head`, `count` and `get` as keyword arguments, like `PostgrestClient.rpc`. `params` stays the second positional argument. `SupabaseException` is one class, so `except SupabaseException` also catches errors raised by `AsyncClient`. +## Client options are keyword arguments + +`ClientOptions`, `AsyncClientOptions` and the `supabase.lib.client_options` module are removed. `create_client`, `create_async_client`, `Client`, `AsyncClient` and their `create` methods take the settings as keyword-only arguments. Settings that apply to every service are arguments of their own. The settings of one service are grouped in an options class, passed in the argument named after the service. + +```python +client = create_client( + url, + key, + headers={"x-app": "1"}, + request_timeout=30, + postgrest=PostgrestClientOptions(schema="private"), + auth=AuthClientOptions(flow_type="implicit", session_storage=my_storage), + storage=StorageClientOptions(request_timeout=120), +) +``` + +| Before | After | +| -------------------------------------------------------------- | ---------------------------------------------------- | +| `create_client(url, key, http_client)` | `create_client(url, key, http_client=http_client)` | +| `ClientOptions(headers={"x-app": "1"})` | `headers={"x-app": "1"}` | +| `ClientOptions(request_timeout=30)` | `request_timeout=30` | +| `ClientOptions(schema="private")` | `postgrest=PostgrestClientOptions(schema="private")` | +| `ClientOptions(auto_refresh_token=False)` | `auth=AuthClientOptions(auto_refresh_token=False)` | +| `ClientOptions(storage=my_storage)` | `auth=AuthClientOptions(session_storage=my_storage)` | +| `ClientOptions(flow_type="implicit")` | `auth=AuthClientOptions(flow_type="implicit")` | +| `ClientOptions(persist_session=False)` | Leave it out | +| `ClientOptions(postgrest_options=PostgrestClientOptions(...))` | `postgrest=PostgrestClientOptions(...)` | +| `ClientOptions(auth_options=AuthClientOptions(...))` | `auth=AuthClientOptions(...)` | +| `ClientOptions(storage_options=StorageClientOptions(...))` | `storage=StorageClientOptions(...)` | +| `ClientOptions(functions_options=FunctionsClientOptions(...))` | `functions=FunctionsClientOptions(...)` | +| `AsyncClientOptions(realtime=RealtimeClientOptions(...))` | `realtime=RealtimeClientOptions(...)` | +| `client.options.headers` | `client.headers` | +| `options.replace(schema="other")` | `dataclasses.replace(options, schema="other")` | + +`AuthClientOptions.session_storage` takes an `AsyncSupportedStorage` for `AsyncClient` and a `SyncSupportedStorage` for `Client`. It used to be called `storage`, which clashed with the storage service. Left out, the session is kept in memory. + +`persist_session` is removed. It was never passed on to the session manager, so it had no effect. To keep the session only in memory, leave `session_storage` out. + +`headers` are sent on top of the default `X-Client-Info` header instead of replacing it. A header you pass with the same name, in any case, still replaces the default one. + +`client.headers` is a read-only view of the headers sent with every request. Its `Authorization` header follows the session. The headers you pass are copied, so changing the original dictionary later has no effect. + +The options classes take keyword arguments only. + ## Options are dataclasses instead of dictionaries The remaining option `TypedDict`s are dataclasses. Fields you leave out use the same defaults as before. -| Package | Before | After | -| ---------- | ------------------------------------------------------------ | --------------------------------------------------------------------------- | -| `supabase` | `AsyncClientOptions(realtime={"heartbeat_interval": 30})` | `AsyncClientOptions(realtime=RealtimeClientOptions(heartbeat_interval=30))` | -| `storage3` | `list_v2(sort_by={"column": "created_at", "order": "desc"})` | `list_v2(sort_by=SortByV2(column="created_at", order="desc"))` | +| Package | Before | After | +| ---------- | ------------------------------------------------------------ | -------------------------------------------------------------------------------------- | +| `supabase` | `AsyncClientOptions(realtime={"heartbeat_interval": 30})` | `create_async_client(url, key, realtime=RealtimeClientOptions(heartbeat_interval=30))` | +| `storage3` | `list_v2(sort_by={"column": "created_at", "order": "desc"})` | `list_v2(sort_by=SortByV2(column="created_at", order="desc"))` | -`RealtimeClientOptions` is exported from `supabase`, and `SortByV2` from `storage3.types`. `ClientOptions.realtime` and `AsyncClientOptions.realtime` default to `RealtimeClientOptions()` instead of `None`. +`RealtimeClientOptions` is exported from `supabase`, and `SortByV2` from `storage3.types`. The unused `storage3.types.SearchV2Options` and `storage3.types.UploadData` are removed. ## Options are frozen -Option and parameter dataclasses are frozen. Setting a field raises `dataclasses.FrozenInstanceError`. Build a changed copy instead, with `replace()` on the client options or with `dataclasses.replace` on the others. - -This covers `ClientOptions`, `AsyncClientOptions`, `RealtimeClientOptions`, `realtime.RealtimeChannelOptions`, `realtime.PostgresChangesBinding`, the `storage3.types` `SortByType`, `SortByV2` and `TransformOptions`, and the `supabase_auth` credential and parameter classes such as `SignUpWithEmailAndPasswordCredentials` and `VerifyEmailOtpParams`. +Option and parameter dataclasses are frozen. Setting a field raises `dataclasses.FrozenInstanceError`. Build a changed copy with `dataclasses.replace` instead. -| Before | After | -| ------------------------------------------------------ | ---------------------------------------------------------------------- | -| `options.headers["x-app"] = "1"` | `options = options.replace(headers={**options.headers, "x-app": "1"})` | -| `options.schema = "other"` | `options = options.replace(schema="other")` | -| `options.broadcast(ack=True)` without using the result | `options = options.broadcast(ack=True)` | -| `options.postgres_changes_bindings.append(binding)` | `options = options.postgres_changes(...)` | +This covers `PostgrestClientOptions`, `AuthClientOptions`, `StorageClientOptions`, `FunctionsClientOptions`, `RealtimeClientOptions`, `realtime.RealtimeChannelOptions`, `realtime.PostgresChangesBinding`, the `storage3.types` `SortByType`, `SortByV2` and `TransformOptions`, and the `supabase_auth` credential and parameter classes such as `SignUpWithEmailAndPasswordCredentials` and `VerifyEmailOtpParams`. -`ClientOptions.headers` is typed as a read-only `Mapping`. The options copy the headers they are given, so changing the original dictionary later has no effect. The client no longer changes the options it is given. When the session changes it replaces `client.options` with a copy that has the new `Authorization` header. +| Before | After | +| ------------------------------------------------------ | -------------------------------------------------------- | +| `options.schema = "other"` | `options = dataclasses.replace(options, schema="other")` | +| `options.broadcast(ack=True)` without using the result | `options = options.broadcast(ack=True)` | +| `options.postgres_changes_bindings.append(binding)` | `options = options.postgres_changes(...)` | The `RealtimeChannelOptions` builder methods return a new copy and leave the original unchanged, so chained calls keep working. `postgres_changes_bindings` and `PostgresChangesBinding.select` are stored as tuples. @@ -110,6 +148,6 @@ The client constructors of `supabase_auth`, `postgrest`, `storage3` and `supabas | ---------------------------------------------- | -------------------------------------------------------------- | | `SyncStorageClient(url, headers, session, 20)` | `SyncStorageClient(url, headers, session, request_timeout=20)` | -`request_timeout` is in seconds and limits how long a request may go without progress. Set it on `ClientOptions` for every service, on `PostgrestClientOptions`, `AuthClientOptions`, `StorageClientOptions` or `FunctionsClientOptions` for one service, with `request_timeout()` on a database query, or with the `request_timeout` argument of `functions.invoke()`. None, the default, leaves the timeout to the HTTP client. +`request_timeout` is in seconds and limits how long a request may go without progress. Set it with the `request_timeout` argument of the client for every service, on `PostgrestClientOptions`, `AuthClientOptions`, `StorageClientOptions` or `FunctionsClientOptions` for one service, with `request_timeout()` on a database query, or with the `request_timeout` argument of `functions.invoke()`. None, the default, leaves the timeout to the HTTP client. A timed-out request raises `supabase.RequestTimeoutError`, a subclass of the built-in `TimeoutError`, instead of an httpx or aiohttp exception. This also applies to timeouts configured on the HTTP client. diff --git a/sdk-compliance.yaml b/sdk-compliance.yaml index 61c016d9c..99ab3c341 100644 --- a/sdk-compliance.yaml +++ b/sdk-compliance.yaml @@ -403,18 +403,18 @@ features: note: "Every auth event that carries a session sets the Authorization header used by auth, postgrest, storage and functions to that session's access token, and an event without a session resets it to the project key. AsyncClient also passes the token to realtime. The sync Client has no realtime client." client.authentication_integration.oauth_flow_type: status: implemented - note: "flow_type option on ClientOptions and the auth client constructor." + note: "flow_type of AuthClientOptions, passed as the auth argument of the supabase client, and of the auth client constructor." symbols: - - AsyncClientOptions - - ClientOptions + - AuthClientOptions client.authentication_integration.session_url_detection: not_implemented client.session_management.custom_storage: status: implemented - note: "storage option on AsyncClientOptions/ClientOptions and the auth client constructor accepts a custom storage backend." + note: "session_storage of AuthClientOptions, passed as the auth argument of the supabase client, and storage of the auth client constructor accept a custom storage backend." symbols: - AsyncSupportedStorage - SyncSupportedStorage + - AuthClientOptions supporting_symbols: - AsyncSupportedStorage.get_item - AsyncSupportedStorage.remove_item @@ -432,7 +432,7 @@ features: - SyncMemoryStorage.set_item client.session_management.persist_session: status: not_implemented - note: "persist_session is accepted by ClientOptions and the auth client constructors but is not forwarded to the session manager, so sessions are always written to storage." + note: "The supabase client has no persist_session setting. The session is kept in session_storage of AuthClientOptions, which defaults to memory. The auth client constructors accept persist_session but do not forward it to the session manager, so sessions are always written to storage." client.request_configuration.custom_http_client: status: implemented @@ -442,10 +442,14 @@ features: - create_async_client client.request_configuration.global_headers: status: implemented - note: "headers option on ClientOptions, accepted by all sub-client constructors." + note: "headers argument of create_client, create_async_client and the supabase client constructors, accepted by all sub-client constructors. They are sent on top of the default X-Client-Info header. SupabaseClient.headers is a read-only view of the current headers." symbols: - - AsyncClientOptions - - ClientOptions + - create_client + - create_async_client + - AsyncClient + - Client + supporting_symbols: + - SupabaseClient.headers client.observability.trace_propagation: not_implemented client.observability.diagnostic_logging: not_implemented @@ -750,15 +754,15 @@ features: - BaseRequestClient database.configuration.request_timeout: status: implemented - note: "request_timeout (float seconds) on the PostgREST client constructors, and PostgrestClientOptions or the global request_timeout of ClientOptions on the supabase client. request_timeout() on a query overrides it for that query. It bounds how long a request may go without progress, and a timed-out request raises RequestTimeoutError. None (the default) leaves the timeout to the HTTP client." + note: "request_timeout (float seconds) on the PostgREST client constructors, and PostgrestClientOptions or the global request_timeout argument of the supabase client. request_timeout() on a query overrides it for that query. It bounds how long a request may go without progress, and a timed-out request raises RequestTimeoutError. None (the default) leaves the timeout to the HTTP client." symbols: - AsyncPostgrestClient - SyncPostgrestClient - BaseRequestClient.request_timeout supporting_symbols: - PostgrestClientOptions - - ClientOptions - - AsyncClientOptions + - AsyncClient + - Client database.configuration.access_token: status: partially_implemented note: "set_auth(token) sets the bearer token on the client in place; there is no per-request access token option." @@ -803,7 +807,7 @@ features: no_public_symbols: true functions.invocation.timeout: status: implemented - note: "request_timeout argument (float seconds) of invoke(), overriding request_timeout of the functions client constructors, and FunctionsClientOptions or the global request_timeout of ClientOptions on the supabase client. It bounds how long the invocation may go without progress, and a timed-out invocation raises RequestTimeoutError. None (the default) leaves the timeout to the HTTP client." + note: "request_timeout argument (float seconds) of invoke(), overriding request_timeout of the functions client constructors, and FunctionsClientOptions or the global request_timeout argument of the supabase client. It bounds how long the invocation may go without progress, and a timed-out invocation raises RequestTimeoutError. None (the default) leaves the timeout to the HTTP client." symbols: - FunctionsClient.invoke supporting_symbols: @@ -1365,8 +1369,6 @@ supporting_symbols: - Client.postgrest - Client.storage - Client.functions - - ClientOptions - - AsyncClientOptions - AuthClientOptions - StorageClientOptions - SupabaseException diff --git a/src/supabase/README.md b/src/supabase/README.md index 5a51a2702..4cdbdb4d8 100644 --- a/src/supabase/README.md +++ b/src/supabase/README.md @@ -63,6 +63,24 @@ supabase: Client = create_client(url, key) For the async client, use `create_async_client` from `supabase.httpx` or `supabase.aiohttp`, which returns an `AsyncClient`. +Settings are keyword arguments. `headers` and `request_timeout` apply to every service. The settings of one service are grouped in an options class: + +```python +from supabase import AuthClientOptions, PostgrestClientOptions, StorageClientOptions + +supabase = create_client( + url, + key, + headers={"x-app": "my-app"}, + request_timeout=30, + postgrest=PostgrestClientOptions(schema="private"), + auth=AuthClientOptions(flow_type="implicit"), + storage=StorageClientOptions(request_timeout=120), +) +``` + +`request_timeout` is in seconds. The `request_timeout` of a service's options overrides the global one for that service. + Use the supabase client to interface with your database. ### Sign-up diff --git a/src/supabase/src/supabase/__init__.py b/src/supabase/src/supabase/__init__.py index 85b45a1d9..e878d8830 100644 --- a/src/supabase/src/supabase/__init__.py +++ b/src/supabase/src/supabase/__init__.py @@ -23,9 +23,6 @@ from supabase_utils.http.errors import RequestTimeoutError from .client import AsyncClient, Client, SupabaseException - -# Lib -from .lib.client_options import AsyncClientOptions, ClientOptions from .types import ( AuthClientOptions, FunctionsClientOptions, @@ -39,7 +36,6 @@ __all__ = [ "AsyncClient", - "AsyncClientOptions", "AuthApiError", "AuthClientOptions", "AuthError", @@ -52,7 +48,6 @@ "AuthWeakPasswordError", "AuthorizationError", "Client", - "ClientOptions", "CustomAuthError", "FunctionsClientOptions", "FunctionsError", diff --git a/src/supabase/src/supabase/aiohttp.py b/src/supabase/src/supabase/aiohttp.py index 1e5d6b0ac..69510593e 100644 --- a/src/supabase/src/supabase/aiohttp.py +++ b/src/supabase/src/supabase/aiohttp.py @@ -1,20 +1,47 @@ +from collections.abc import Mapping + from aiohttp import ClientSession +from supabase_auth import AsyncSupportedStorage from supabase_utils.http.adapters.aiohttp import AsyncAiohttpSession from .client import AsyncClient -from .lib.client_options import AsyncClientOptions +from .types import ( + AuthClientOptions, + FunctionsClientOptions, + PostgrestClientOptions, + RealtimeClientOptions, + StorageClientOptions, +) def create_async_client( supabase_url: str, supabase_key: str, + *, http_client: ClientSession | None = None, - options: AsyncClientOptions | None = None, + headers: Mapping[str, str] | None = None, + request_timeout: float | None = None, + postgrest: PostgrestClientOptions | None = None, + auth: AuthClientOptions[AsyncSupportedStorage] | None = None, + storage: StorageClientOptions | None = None, + functions: FunctionsClientOptions | None = None, + realtime: RealtimeClientOptions | None = None, ) -> AsyncClient: + """Create an async client that sends its requests with aiohttp. + + `http_client` defaults to a new aiohttp client. See `AsyncClient` for the + other arguments. + """ client = http_client or ClientSession() return AsyncClient( - supabase_url=supabase_url, - supabase_key=supabase_key, - http_session=AsyncAiohttpSession(client=client), - options=options, + supabase_url, + supabase_key, + AsyncAiohttpSession(client=client), + headers=headers, + request_timeout=request_timeout, + postgrest=postgrest, + auth=auth, + storage=storage, + functions=functions, + realtime=realtime, ) diff --git a/src/supabase/src/supabase/client.py b/src/supabase/src/supabase/client.py index 25d5f6437..7c01ecfc8 100644 --- a/src/supabase/src/supabase/client.py +++ b/src/supabase/src/supabase/client.py @@ -1,7 +1,9 @@ from __future__ import annotations +import platform from abc import ABC, abstractmethod from functools import cached_property +from types import MappingProxyType from typing import TYPE_CHECKING, Any, Literal, Self, overload, override from postgrest import APIError as PostgrestAPIError @@ -17,6 +19,7 @@ ) from supabase_auth import ( AsyncSupabaseAuthClient, + AsyncSupportedStorage, AuthApiError, AuthError, AuthImplicitGrantRedirectError, @@ -28,6 +31,7 @@ AuthWeakPasswordError, CustomAuthError, SyncSupabaseAuthClient, + SyncSupportedStorage, UserDoesNotExistError, ) from supabase_functions import ( @@ -44,9 +48,16 @@ HttpSession, SyncHttpIO, ) +from supabase_utils.http.request import validate_request_timeout from yarl import URL -from .lib.client_options import AsyncClientOptions, ClientOptions +from .types import ( + AuthClientOptions, + FunctionsClientOptions, + PostgrestClientOptions, + RealtimeClientOptions, + StorageClientOptions, +) from .version import __version__ if TYPE_CHECKING: @@ -70,7 +81,6 @@ __all__ = [ "AsyncClient", - "AsyncClientOptions", "AuthApiError", "AuthError", "AuthImplicitGrantRedirectError", @@ -82,7 +92,6 @@ "AuthWeakPasswordError", "AuthorizationError", "Client", - "ClientOptions", "CustomAuthError", "FunctionsError", "FunctionsHttpError", @@ -101,6 +110,17 @@ ] +_DEFAULT_HEADERS = { + "X-Client-Info": ( + f"supabase-py/{__version__}" + f"; platform={platform.system()}" + f"; platform-version={platform.release()}" + f"; runtime=python" + f"; runtime-version={platform.python_version()}" + ) +} + + class SupabaseException(Exception): """Raised when the client is created with a missing or invalid URL or key.""" @@ -122,11 +142,22 @@ def _is_new_api_key(key: str) -> bool: class SupabaseClient[ HttpIO: (SyncHttpIO, AsyncHttpIO), - Options: (AsyncClientOptions, ClientOptions), + Storage: (AsyncSupportedStorage, SyncSupportedStorage), ](ABC): """Behavior shared by the async and the sync Supabase client.""" - def __init__(self, supabase_url: str, supabase_key: str, options: Options) -> None: + def __init__( + self, + supabase_url: str, + supabase_key: str, + *, + headers: Mapping[str, str] | None, + request_timeout: float | None, + postgrest: PostgrestClientOptions | None, + auth: AuthClientOptions[Storage] | None, + storage: StorageClientOptions | None, + functions: FunctionsClientOptions | None, + ) -> None: """Instantiate the client. Parameters @@ -135,8 +166,24 @@ def __init__(self, supabase_url: str, supabase_key: str, options: Options) -> No The URL to the Supabase instance that should be connected to. supabase_key: str The API key to the Supabase instance that should be connected to. - options - The options used to configure the client and its sub-clients. + headers + Headers sent with every request, on top of the default ones. + request_timeout + Seconds a request to the database, auth, storage or edge functions + may go without progress before it fails with `RequestTimeoutError`. + It limits how long the connection may stall, not the whole request, + so a large transfer that keeps moving is not cut short. None (the + default) leaves the timeout to the HTTP client. The + `request_timeout` of a service's options overrides it for that + service. + postgrest + Options for the database client. + auth + Options for the auth client. + storage + Options for the storage client. + functions + Options for the edge functions client. """ if not supabase_url: raise SupabaseException("supabase_url is required") @@ -154,18 +201,30 @@ def __init__(self, supabase_url: str, supabase_key: str, options: Options) -> No ): raise SupabaseException(f"Invalid URL: {supabase_url}") + validate_request_timeout(request_timeout) self.supabase_key = supabase_key - self.options: Options = options.replace( - headers={ - **{ - key: value - for key, value in options.headers.items() - if key.lower() not in ("apikey", "authorization") - }, - **self._get_auth_headers(options.headers), - } - ) - authorization = self.options.headers["Authorization"] + self._request_timeout = request_timeout + self._postgrest_options = postgrest or PostgrestClientOptions() + self._auth_options: AuthClientOptions[Storage] = auth or AuthClientOptions() + self._storage_options = storage or StorageClientOptions() + self._functions_options = functions or FunctionsClientOptions() + + custom_headers = { + key: value + for key, value in (headers or {}).items() + if key.lower() not in ("apikey", "authorization") + } + custom_keys = {key.lower() for key in custom_headers} + self._headers = { + **{ + key: value + for key, value in _DEFAULT_HEADERS.items() + if key.lower() not in custom_keys + }, + **custom_headers, + **self._get_auth_headers(headers or {}), + } + authorization = self._headers["Authorization"] self._access_token = ( authorization.removeprefix("Bearer ") if authorization.startswith("Bearer ") @@ -177,6 +236,15 @@ def __init__(self, supabase_url: str, supabase_key: str, options: Options) -> No self.storage_url = self.supabase_url.joinpath("storage", "v1", "") self.functions_url = self.supabase_url.joinpath("functions", "v1") + @property + def headers(self) -> Mapping[str, str]: + """The headers sent with every request. + + `Authorization` follows the session: it holds the access token of the + signed in user, or the API key when nobody is signed in. + """ + return MappingProxyType(self._headers) + @property @abstractmethod def auth(self) -> SupabaseAuthHttpClient[HttpIO, Any]: ... @@ -271,10 +339,10 @@ def rpc( """ return self.postgrest.rpc(fn, params or {}, head=head, count=count, get=get) - def _request_timeout(self, service_options: _ServiceClientOptions) -> float | None: + def _timeout_for(self, service_options: _ServiceClientOptions) -> float | None: if service_options.request_timeout is not None: return service_options.request_timeout - return self.options.request_timeout + return self._request_timeout def _create_auth_header(self, token: str) -> str: return f"Bearer {token}" @@ -296,7 +364,7 @@ def _functions_authorization(self, authorization: str) -> str | None: return authorization def _functions_headers(self) -> dict[str, str]: - headers = dict(self.options.headers) + headers = dict(self._headers) authorization = self._functions_authorization(headers.pop("Authorization")) return ( headers @@ -311,9 +379,7 @@ def _listen_to_auth_events( def _set_access_token(self, access_token: str) -> None: authorization = self._create_auth_header(access_token) - self.options = self.options.replace( - headers={**self.options.headers, "Authorization": authorization} - ) + self._headers = {**self._headers, "Authorization": authorization} self._access_token = access_token self.auth.default_headers = self.auth.default_headers.override( "Authorization", authorization @@ -334,7 +400,7 @@ def _set_access_token(self, access_token: str) -> None: ) -class AsyncClient(SupabaseClient[AsyncHttpIO, AsyncClientOptions]): +class AsyncClient(SupabaseClient[AsyncHttpIO, AsyncSupportedStorage]): """Async Supabase client.""" def __init__( @@ -342,10 +408,32 @@ def __init__( supabase_url: str, supabase_key: str, http_session: AsyncHttpSession, - options: AsyncClientOptions | None = None, + *, + headers: Mapping[str, str] | None = None, + request_timeout: float | None = None, + postgrest: PostgrestClientOptions | None = None, + auth: AuthClientOptions[AsyncSupportedStorage] | None = None, + storage: StorageClientOptions | None = None, + functions: FunctionsClientOptions | None = None, + realtime: RealtimeClientOptions | None = None, ) -> None: + """Instantiate the client. + + `http_session` sends the requests and `realtime` configures the + realtime connections. See `SupabaseClient` for the other arguments. + """ self.http_session = http_session - super().__init__(supabase_url, supabase_key, options or AsyncClientOptions()) + self._realtime_options = realtime or RealtimeClientOptions() + super().__init__( + supabase_url, + supabase_key, + headers=headers, + request_timeout=request_timeout, + postgrest=postgrest, + auth=auth, + storage=storage, + functions=functions, + ) self.realtime_url = self.supabase_url.joinpath("realtime", "v1").with_scheme( "wss" if self.supabase_url.scheme == "https" else "ws" ) @@ -357,10 +445,29 @@ async def create( supabase_url: str, supabase_key: str, http_session: AsyncHttpSession, - options: AsyncClientOptions | None = None, + *, + headers: Mapping[str, str] | None = None, + request_timeout: float | None = None, + postgrest: PostgrestClientOptions | None = None, + auth: AuthClientOptions[AsyncSupportedStorage] | None = None, + storage: StorageClientOptions | None = None, + functions: FunctionsClientOptions | None = None, + realtime: RealtimeClientOptions | None = None, ) -> AsyncClient: - auth_header = _find_authorization(options.headers) if options else None - client = cls(supabase_url, supabase_key, http_session, options) + """Create a client that uses the session in the session storage, if any.""" + client = cls( + supabase_url, + supabase_key, + http_session, + headers=headers, + request_timeout=request_timeout, + postgrest=postgrest, + auth=auth, + storage=storage, + functions=functions, + realtime=realtime, + ) + auth_header = _find_authorization(headers) if headers else None if auth_header is None: try: @@ -389,12 +496,11 @@ def auth(self) -> AsyncSupabaseAuthClient: return AsyncSupabaseAuthClient( url=str(self.auth_url), http_session=self.http_session, - auto_refresh_token=self.options.auto_refresh_token, - persist_session=self.options.persist_session, - storage=self.options.storage, - headers=self.options.headers, - flow_type=self.options.flow_type, - request_timeout=self._request_timeout(self.options.auth_options), + headers=self._headers, + auto_refresh_token=self._auth_options.auto_refresh_token, + storage=self._auth_options.session_storage, + flow_type=self._auth_options.flow_type, + request_timeout=self._timeout_for(self._auth_options), ) @cached_property @@ -403,9 +509,9 @@ def postgrest(self) -> AsyncPostgrestClient: return AsyncPostgrestClient( str(self.rest_url), http_session=self.http_session, - headers=self.options.headers, - schema=self.options.schema, - request_timeout=self._request_timeout(self.options.postgrest_options), + headers=self._headers, + schema=self._postgrest_options.schema, + request_timeout=self._timeout_for(self._postgrest_options), ) @cached_property @@ -413,9 +519,9 @@ def postgrest(self) -> AsyncPostgrestClient: def storage(self) -> AsyncStorageClient: return AsyncStorageClient( url=str(self.storage_url), - headers=self.options.headers, + headers=self._headers, http_session=self.http_session, - request_timeout=self._request_timeout(self.options.storage_options), + request_timeout=self._timeout_for(self._storage_options), ) @cached_property @@ -425,7 +531,7 @@ def functions(self) -> AsyncFunctionsClient: url=str(self.functions_url), headers=self._functions_headers(), http_session=self.http_session, - request_timeout=self._request_timeout(self.options.functions_options), + request_timeout=self._timeout_for(self._functions_options), ) def schema(self, schema: str) -> AsyncPostgrestClient: @@ -444,12 +550,12 @@ def realtime(self) -> connect_once: return connect_once( str(self.realtime_url), token_callback=self._realtime_access_token, - heartbeat_interval=self.options.realtime.heartbeat_interval, - heartbeat_timeout=self.options.realtime.heartbeat_timeout, + heartbeat_interval=self._realtime_options.heartbeat_interval, + heartbeat_timeout=self._realtime_options.heartbeat_timeout, ) -class Client(SupabaseClient[SyncHttpIO, ClientOptions]): +class Client(SupabaseClient[SyncHttpIO, SyncSupportedStorage]): """Sync Supabase client.""" def __init__( @@ -457,10 +563,30 @@ def __init__( supabase_url: str, supabase_key: str, http_session: HttpSession, - options: ClientOptions | None = None, + *, + headers: Mapping[str, str] | None = None, + request_timeout: float | None = None, + postgrest: PostgrestClientOptions | None = None, + auth: AuthClientOptions[SyncSupportedStorage] | None = None, + storage: StorageClientOptions | None = None, + functions: FunctionsClientOptions | None = None, ) -> None: + """Instantiate the client. + + `http_session` sends the requests. See `SupabaseClient` for the other + arguments. + """ self.http_session = http_session - super().__init__(supabase_url, supabase_key, options or ClientOptions()) + super().__init__( + supabase_url, + supabase_key, + headers=headers, + request_timeout=request_timeout, + postgrest=postgrest, + auth=auth, + storage=storage, + functions=functions, + ) self.auth.on_auth_state_change(self._listen_to_auth_events) @classmethod @@ -469,10 +595,27 @@ def create( supabase_url: str, supabase_key: str, http_session: HttpSession, - options: ClientOptions | None = None, + *, + headers: Mapping[str, str] | None = None, + request_timeout: float | None = None, + postgrest: PostgrestClientOptions | None = None, + auth: AuthClientOptions[SyncSupportedStorage] | None = None, + storage: StorageClientOptions | None = None, + functions: FunctionsClientOptions | None = None, ) -> Client: - auth_header = _find_authorization(options.headers) if options else None - client = cls(supabase_url, supabase_key, http_session, options) + """Create a client that uses the session in the session storage, if any.""" + client = cls( + supabase_url, + supabase_key, + http_session, + headers=headers, + request_timeout=request_timeout, + postgrest=postgrest, + auth=auth, + storage=storage, + functions=functions, + ) + auth_header = _find_authorization(headers) if headers else None if auth_header is None: try: @@ -501,12 +644,11 @@ def auth(self) -> SyncSupabaseAuthClient: return SyncSupabaseAuthClient( url=str(self.auth_url), http_session=self.http_session, - auto_refresh_token=self.options.auto_refresh_token, - persist_session=self.options.persist_session, - storage=self.options.storage, - headers=self.options.headers, - flow_type=self.options.flow_type, - request_timeout=self._request_timeout(self.options.auth_options), + headers=self._headers, + auto_refresh_token=self._auth_options.auto_refresh_token, + storage=self._auth_options.session_storage, + flow_type=self._auth_options.flow_type, + request_timeout=self._timeout_for(self._auth_options), ) @cached_property @@ -515,9 +657,9 @@ def postgrest(self) -> SyncPostgrestClient: return SyncPostgrestClient( str(self.rest_url), http_session=self.http_session, - headers=self.options.headers, - schema=self.options.schema, - request_timeout=self._request_timeout(self.options.postgrest_options), + headers=self._headers, + schema=self._postgrest_options.schema, + request_timeout=self._timeout_for(self._postgrest_options), ) @cached_property @@ -525,9 +667,9 @@ def postgrest(self) -> SyncPostgrestClient: def storage(self) -> SyncStorageClient: return SyncStorageClient( url=str(self.storage_url), - headers=self.options.headers, + headers=self._headers, http_session=self.http_session, - request_timeout=self._request_timeout(self.options.storage_options), + request_timeout=self._timeout_for(self._storage_options), ) @cached_property @@ -537,7 +679,7 @@ def functions(self) -> SyncFunctionsClient: url=str(self.functions_url), headers=self._functions_headers(), http_session=self.http_session, - request_timeout=self._request_timeout(self.options.functions_options), + request_timeout=self._timeout_for(self._functions_options), ) def schema(self, schema: str) -> SyncPostgrestClient: diff --git a/src/supabase/src/supabase/httpx.py b/src/supabase/src/supabase/httpx.py index a6f4074e3..2340b8166 100644 --- a/src/supabase/src/supabase/httpx.py +++ b/src/supabase/src/supabase/httpx.py @@ -1,44 +1,87 @@ +from collections.abc import Mapping + from httpx import AsyncClient as AsyncHttpxClient from httpx import Client as SyncHttpxClient +from supabase_auth import AsyncSupportedStorage, SyncSupportedStorage from supabase_utils.http.adapters.httpx import AsyncHttpxSession, HttpxSession from .client import AsyncClient, Client -from .lib.client_options import AsyncClientOptions, ClientOptions +from .types import ( + AuthClientOptions, + FunctionsClientOptions, + PostgrestClientOptions, + RealtimeClientOptions, + StorageClientOptions, +) def create_client( supabase_url: str, supabase_key: str, + *, http_client: SyncHttpxClient | None = None, - options: ClientOptions | None = None, + headers: Mapping[str, str] | None = None, + request_timeout: float | None = None, + postgrest: PostgrestClientOptions | None = None, + auth: AuthClientOptions[SyncSupportedStorage] | None = None, + storage: StorageClientOptions | None = None, + functions: FunctionsClientOptions | None = None, ) -> Client: + """Create a sync client that sends its requests with httpx. + + `http_client` defaults to a new httpx client. See `Client` for the other + arguments. + """ client = http_client or SyncHttpxClient( http2=True, verify=True, follow_redirects=True, ) return Client( - supabase_url=supabase_url, - supabase_key=supabase_key, - http_session=HttpxSession(client=client), - options=options, + supabase_url, + supabase_key, + HttpxSession(client=client), + headers=headers, + request_timeout=request_timeout, + postgrest=postgrest, + auth=auth, + storage=storage, + functions=functions, ) def create_async_client( supabase_url: str, supabase_key: str, + *, http_client: AsyncHttpxClient | None = None, - options: AsyncClientOptions | None = None, + headers: Mapping[str, str] | None = None, + request_timeout: float | None = None, + postgrest: PostgrestClientOptions | None = None, + auth: AuthClientOptions[AsyncSupportedStorage] | None = None, + storage: StorageClientOptions | None = None, + functions: FunctionsClientOptions | None = None, + realtime: RealtimeClientOptions | None = None, ) -> AsyncClient: + """Create an async client that sends its requests with httpx. + + `http_client` defaults to a new httpx client. See `AsyncClient` for the + other arguments. + """ client = http_client or AsyncHttpxClient( http2=True, verify=True, follow_redirects=True, ) return AsyncClient( - supabase_url=supabase_url, - supabase_key=supabase_key, - http_session=AsyncHttpxSession(client=client), - options=options, + supabase_url, + supabase_key, + AsyncHttpxSession(client=client), + headers=headers, + request_timeout=request_timeout, + postgrest=postgrest, + auth=auth, + storage=storage, + functions=functions, + realtime=realtime, ) diff --git a/src/supabase/src/supabase/lib/__init__.py b/src/supabase/src/supabase/lib/__init__.py deleted file mode 100644 index 8b1378917..000000000 --- a/src/supabase/src/supabase/lib/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/supabase/src/supabase/lib/client_options.py b/src/supabase/src/supabase/lib/client_options.py deleted file mode 100644 index 887c161d4..000000000 --- a/src/supabase/src/supabase/lib/client_options.py +++ /dev/null @@ -1,153 +0,0 @@ -import dataclasses -import platform -from collections.abc import Mapping -from dataclasses import dataclass, field -from enum import Enum -from typing import Literal, Self - -from supabase_auth import ( - AsyncMemoryStorage, - AsyncSupportedStorage, - AuthFlowType, - SyncMemoryStorage, - SyncSupportedStorage, -) -from supabase_utils.http.request import validate_request_timeout - -from supabase.types import ( - AuthClientOptions, - FunctionsClientOptions, - PostgrestClientOptions, - RealtimeClientOptions, - StorageClientOptions, -) - -from ..version import __version__ - -DEFAULT_HEADERS = { - "X-Client-Info": ( - f"supabase-py/{__version__}" - f"; platform={platform.system()}" - f"; platform-version={platform.release()}" - f"; runtime=python" - f"; runtime-version={platform.python_version()}" - ) -} - - -class _Unchanged(Enum): - UNCHANGED = "unchanged" - - -@dataclass(frozen=True) -class _ClientOptionsBase[Storage: (AsyncSupportedStorage, SyncSupportedStorage)]: - schema: str = "public" - """ - The Postgres schema which your tables belong to. - Must be on the list of exposed schemas in Supabase. Defaults to 'public'. - """ - - headers: Mapping[str, str] = field(default_factory=DEFAULT_HEADERS.copy) - """Optional headers for initializing the client.""" - - auto_refresh_token: bool = True - """Automatically refreshes the token for logged in users.""" - - persist_session: bool = True - """Whether to persist a logged in session to storage.""" - - realtime: RealtimeClientOptions = field(default_factory=RealtimeClientOptions) - """Options for the realtime connections.""" - - flow_type: AuthFlowType = "pkce" - """flow type to use for authentication""" - - request_timeout: float | None = None - """ - Seconds a request to the database, auth, storage or edge functions may go - without progress before it fails with `RequestTimeoutError`. It limits how - long the connection may stall, not the whole request, so a large transfer - that keeps moving is not cut short. None (the default) leaves the timeout - to the HTTP client. The `request_timeout` of a service's options overrides - it for that service. - """ - - postgrest_options: PostgrestClientOptions = field( - default_factory=PostgrestClientOptions - ) - """Options for the database client.""" - - auth_options: AuthClientOptions = field(default_factory=AuthClientOptions) - """Options for the auth client.""" - - storage_options: StorageClientOptions = field(default_factory=StorageClientOptions) - """Options for the storage client.""" - - functions_options: FunctionsClientOptions = field( - default_factory=FunctionsClientOptions - ) - """Options for the edge functions client.""" - - def __post_init__(self) -> None: - validate_request_timeout(self.request_timeout) - object.__setattr__(self, "headers", dict(self.headers)) - - def replace( - self, - *, - schema: str | None = None, - headers: Mapping[str, str] | None = None, - auto_refresh_token: bool | None = None, - persist_session: bool | None = None, - storage: Storage | None = None, - realtime: RealtimeClientOptions | None = None, - flow_type: AuthFlowType | None = None, - request_timeout: float | None | Literal[_Unchanged.UNCHANGED] = ( - _Unchanged.UNCHANGED - ), - postgrest_options: PostgrestClientOptions | None = None, - auth_options: AuthClientOptions | None = None, - storage_options: StorageClientOptions | None = None, - functions_options: FunctionsClientOptions | None = None, - ) -> Self: - """Create a copy with the given options changed. - - Options left as None keep their value, except `request_timeout`, where - None leaves the timeout to the HTTP client. Leave `request_timeout` out - to keep its value. - """ - changes = { - "schema": schema, - "headers": headers, - "auto_refresh_token": auto_refresh_token, - "persist_session": persist_session, - "storage": storage, - "realtime": realtime, - "flow_type": flow_type, - "postgrest_options": postgrest_options, - "auth_options": auth_options, - "storage_options": storage_options, - "functions_options": functions_options, - } - updated = dataclasses.replace( - self, **{key: value for key, value in changes.items() if value is not None} - ) - if request_timeout is _Unchanged.UNCHANGED: - return updated - return dataclasses.replace(updated, request_timeout=request_timeout) - - -@dataclass(frozen=True) -class AsyncClientOptions(_ClientOptionsBase[AsyncSupportedStorage]): - """Options for `AsyncClient`.""" - - storage: AsyncSupportedStorage = field(default_factory=AsyncMemoryStorage) - """A storage provider. Used to store the logged in session.""" - - -@dataclass(frozen=True) -class ClientOptions(_ClientOptionsBase[SyncSupportedStorage]): - """Options for the sync `Client`.""" - - storage: SyncSupportedStorage = field(default_factory=SyncMemoryStorage) - """A storage provider. Used to store the logged in session.""" diff --git a/src/supabase/src/supabase/types.py b/src/supabase/src/supabase/types.py index b46ca6bab..88777a478 100644 --- a/src/supabase/src/supabase/types.py +++ b/src/supabase/src/supabase/types.py @@ -5,6 +5,7 @@ DEFAULT_HEARTBEAT_TIMEOUT, validate_heartbeat, ) +from supabase_auth import AsyncSupportedStorage, AuthFlowType, SyncSupportedStorage from supabase_utils.http.request import validate_request_timeout @@ -22,32 +23,50 @@ def __post_init__(self) -> None: validate_heartbeat(self.heartbeat_interval, self.heartbeat_timeout) -@dataclass(frozen=True) +@dataclass(frozen=True, kw_only=True) class _ServiceClientOptions: """Options shared by the database, auth, storage and edge functions clients.""" request_timeout: float | None = None - """Seconds a request to the service may go without progress before it fails with `RequestTimeoutError`. Overrides `request_timeout` of the client options when set.""" + """Seconds a request to the service may go without progress before it fails with `RequestTimeoutError`. Overrides the `request_timeout` argument of the client when set.""" def __post_init__(self) -> None: validate_request_timeout(self.request_timeout) -@dataclass(frozen=True) +@dataclass(frozen=True, kw_only=True) class PostgrestClientOptions(_ServiceClientOptions): """Options for the database client. Use `request_timeout()` on a query to override its timeout for that query.""" + schema: str = "public" + """The Postgres schema which your tables belong to. Must be on the list of exposed schemas in Supabase.""" -@dataclass(frozen=True) -class AuthClientOptions(_ServiceClientOptions): - """Options for the auth client.""" +@dataclass(frozen=True, kw_only=True) +class AuthClientOptions[Storage: (AsyncSupportedStorage, SyncSupportedStorage)]( + _ServiceClientOptions +): + """Options for the auth client. -@dataclass(frozen=True) + `AsyncClient` takes an `AsyncSupportedStorage` as `session_storage` and + `Client` a `SyncSupportedStorage`. + """ + + auto_refresh_token: bool = True + """Automatically refreshes the token for logged in users.""" + + session_storage: Storage | None = None + """Where the logged in session is stored. None (the default) keeps it in memory.""" + + flow_type: AuthFlowType = "pkce" + """The flow type to use for authentication.""" + + +@dataclass(frozen=True, kw_only=True) class StorageClientOptions(_ServiceClientOptions): """Options for the storage client.""" -@dataclass(frozen=True) +@dataclass(frozen=True, kw_only=True) class FunctionsClientOptions(_ServiceClientOptions): """Options for the edge functions client. Use the `request_timeout` argument of `invoke()` to override its timeout for one invocation.""" diff --git a/src/supabase/tests/_async/conftest.py b/src/supabase/tests/_async/conftest.py index 57ed83792..247df2566 100644 --- a/src/supabase/tests/_async/conftest.py +++ b/src/supabase/tests/_async/conftest.py @@ -1,9 +1,8 @@ -from typing import Protocol +from typing import Any, Protocol import pytest from supabase import AsyncClient as AsyncSupabaseClient -from supabase import AsyncClientOptions from supabase.aiohttp import create_async_client as create_aiohttp_client from supabase.httpx import create_async_client as create_httpx_client @@ -17,24 +16,17 @@ def pytest_configure(config: pytest.Config) -> None: REST_URL = "http://127.0.0.1:3000" -def httpx( - supabase_key: str, supabase_url: str, options: AsyncClientOptions | None = None -) -> AsyncSupabaseClient: - return create_httpx_client(supabase_key, supabase_url, options=options) +def httpx(supabase_url: str, supabase_key: str, **kwargs: Any) -> AsyncSupabaseClient: + return create_httpx_client(supabase_url, supabase_key, **kwargs) -def aiohttp( - supabase_key: str, supabase_url: str, options: AsyncClientOptions | None = None -) -> AsyncSupabaseClient: - return create_aiohttp_client(supabase_key, supabase_url, options=options) +def aiohttp(supabase_url: str, supabase_key: str, **kwargs: Any) -> AsyncSupabaseClient: + return create_aiohttp_client(supabase_url, supabase_key, **kwargs) class AsyncClientCallable(Protocol): def __call__( - self, - supabase_key: str, - supabase_url: str, - options: AsyncClientOptions | None = None, + self, supabase_url: str, supabase_key: str, **kwargs: Any ) -> AsyncSupabaseClient: ... diff --git a/src/supabase/tests/_async/test_client.py b/src/supabase/tests/_async/test_client.py index b182104f1..160393240 100644 --- a/src/supabase/tests/_async/test_client.py +++ b/src/supabase/tests/_async/test_client.py @@ -9,7 +9,7 @@ from supabase import ( AsyncClient, - AsyncClientOptions, + AuthClientOptions, ) from .conftest import AsyncClientCallable @@ -55,8 +55,8 @@ async def test_uses_key_as_authorization_header_by_default( create_async_client: AsyncClientCallable, ) -> None: async with create_async_client(url, key) as client: - assert client.options.headers.get("apiKey") == key - assert client.options.headers.get("Authorization") == f"Bearer {key}" + assert client.headers.get("apiKey") == key + assert client.headers.get("Authorization") == f"Bearer {key}" assert client.postgrest.default_headers.get("apiKey") == key assert client.postgrest.default_headers.get("Authorization") == f"Bearer {key}" @@ -100,8 +100,8 @@ async def test_auth_events_with_a_session_use_its_access_token( assert client.postgrest is postgrest assert client.storage is storage assert client.functions is functions - assert client.options.headers.get("apiKey") == key - assert client.options.headers.get("Authorization") == authorization + assert client.headers.get("apiKey") == key + assert client.headers.get("Authorization") == authorization assert client.postgrest.default_headers.get("Authorization") == authorization assert client.storage.default_headers.get("Authorization") == authorization assert client.functions.default_headers.get("Authorization") == authorization @@ -120,7 +120,7 @@ async def test_auth_events_without_a_session_use_the_key( client.auth.session_manager.notify_all_subscribers("SIGNED_OUT", None) authorization = f"Bearer {key}" - assert client.options.headers.get("Authorization") == authorization + assert client.headers.get("Authorization") == authorization assert client.postgrest.default_headers.get("Authorization") == authorization assert client.storage.default_headers.get("Authorization") == authorization assert client.functions.default_headers.get("Authorization") == authorization @@ -139,7 +139,7 @@ async def test_create_uses_the_stored_session_token() -> None: ) authorization = "Bearer secretuserjwt" - assert client.options.headers.get("Authorization") == authorization + assert client.headers.get("Authorization") == authorization assert client.postgrest.default_headers.get("Authorization") == authorization assert client.auth.default_headers.get("Authorization") == authorization assert await realtime_access_token(client) == "secretuserjwt" @@ -150,11 +150,11 @@ async def test_supports_setting_a_global_authorization_header( ) -> None: authorization = "Bearer secretuserjwt" - options = AsyncClientOptions(headers={"Authorization": authorization}) - - async with create_async_client(url, key, options) as client: - assert client.options.headers.get("apiKey") == key - assert client.options.headers.get("Authorization") == authorization + async with create_async_client( + url, key, headers={"Authorization": authorization} + ) as client: + assert client.headers.get("apiKey") == key + assert client.headers.get("Authorization") == authorization assert client.postgrest.default_headers.get("apiKey") == key assert client.postgrest.default_headers.get("Authorization") == authorization @@ -171,61 +171,57 @@ async def test_supports_setting_a_global_authorization_header( async def test_realtime_uses_the_key_with_a_non_bearer_authorization_header( create_async_client: AsyncClientCallable, ) -> None: - options = AsyncClientOptions(headers={"Authorization": "Basic dXNlcjpwYXNz"}) - - async with create_async_client(url, key, options) as client: + async with create_async_client( + url, key, headers={"Authorization": "Basic dXNlcjpwYXNz"} + ) as client: assert await realtime_access_token(client) == key async def test_mutable_headers_issue(create_async_client: AsyncClientCallable) -> None: - shared_options = AsyncClientOptions( - storage=AsyncMemoryStorage(), headers={"Authorization": "Bearer initial-token"} - ) + shared_headers = {"Authorization": "Bearer initial-token"} + shared_auth = AuthClientOptions(session_storage=AsyncMemoryStorage()) async with ( - create_async_client(url, key, shared_options) as client1, - create_async_client(url, key, shared_options) as client2, + create_async_client( + url, key, headers=shared_headers, auth=shared_auth + ) as client1, + create_async_client( + url, key, headers=shared_headers, auth=shared_auth + ) as client2, ): client1._set_access_token("modified-token") - assert client2.options.headers["Authorization"] == "Bearer initial-token" - assert client1.options.headers["Authorization"] == "Bearer modified-token" - assert shared_options.headers["Authorization"] == "Bearer initial-token" + assert client2.headers["Authorization"] == "Bearer initial-token" + assert client1.headers["Authorization"] == "Bearer modified-token" + assert shared_headers["Authorization"] == "Bearer initial-token" async def test_global_authorization_header_issue( create_async_client: AsyncClientCallable, ) -> None: authorization = "Bearer secretuserjwt" - options = AsyncClientOptions(headers={"Authorization": authorization}) - - async with create_async_client(url, key, options) as client: - assert client.options.headers.get("apiKey") == key + async with create_async_client( + url, key, headers={"Authorization": authorization} + ) as client: + assert client.headers.get("apiKey") == key async def test_custom_headers(create_async_client: AsyncClientCallable) -> None: - options = AsyncClientOptions( - headers={ - "x-app-name": "apple", - "x-version": "1.0", - } - ) + headers = {"x-app-name": "apple", "x-version": "1.0"} - async with create_async_client(url, key, options) as client: - assert client.options.headers.get("x-app-name") == "apple" - assert client.options.headers.get("x-version") == "1.0" + async with create_async_client(url, key, headers=headers) as client: + assert client.headers.get("x-app-name") == "apple" + assert client.headers.get("x-version") == "1.0" async def test_custom_headers_immutable( create_async_client: AsyncClientCallable, ) -> None: headers = {"x-app-name": "apple", "x-version": "1.0"} - options = AsyncClientOptions(headers=headers) - headers["x-app-name"] = "grapes" + async with create_async_client(url, key, headers=headers) as client: + headers["x-app-name"] = "grapes" - async with create_async_client(url, key, options) as client: - assert client.options.headers.get("x-app-name") == "apple" - assert client.options.headers.get("x-version") == "1.0" - assert options.headers.get("x-app-name") == "apple" + assert client.headers.get("x-app-name") == "apple" + assert client.headers.get("x-version") == "1.0" async def test_httpx_client_base_url_isolation( @@ -237,8 +233,7 @@ async def test_httpx_client_base_url_isolation( See: https://github.com/supabase/supabase-py/issues/1244 """ # Create client with shared httpx instance - options = AsyncClientOptions() - async with create_async_client(url, key, options) as client: + async with create_async_client(url, key) as client: # Access storage and capture its base_url storage = client.storage storage_base_url = str(storage.base_url).rstrip("/") diff --git a/src/supabase/tests/_sync/conftest.py b/src/supabase/tests/_sync/conftest.py index f08174788..088542eca 100644 --- a/src/supabase/tests/_sync/conftest.py +++ b/src/supabase/tests/_sync/conftest.py @@ -1,8 +1,8 @@ -from typing import Protocol +from typing import Any, Protocol import pytest -from supabase import Client, ClientOptions +from supabase import Client from supabase.httpx import create_client as create_httpx_client @@ -15,15 +15,13 @@ def pytest_configure(config: pytest.Config) -> None: REST_URL = "http://127.0.0.1:3000" -def httpx( - supabase_key: str, supabase_url: str, options: ClientOptions | None = None -) -> Client: - return create_httpx_client(supabase_key, supabase_url, options=options) +def httpx(supabase_url: str, supabase_key: str, **kwargs: Any) -> Client: + return create_httpx_client(supabase_url, supabase_key, **kwargs) class SyncClientCallable(Protocol): def __call__( - self, supabase_key: str, supabase_url: str, options: ClientOptions | None = None + self, supabase_url: str, supabase_key: str, **kwargs: Any ) -> Client: ... diff --git a/src/supabase/tests/_sync/test_client.py b/src/supabase/tests/_sync/test_client.py index 9fb19daa8..879bcfdbb 100644 --- a/src/supabase/tests/_sync/test_client.py +++ b/src/supabase/tests/_sync/test_client.py @@ -8,8 +8,8 @@ from supabase_utils.http.adapters.httpx import HttpxSession from supabase import ( + AuthClientOptions, Client, - ClientOptions, ) from .conftest import SyncClientCallable @@ -46,8 +46,8 @@ def test_uses_key_as_authorization_header_by_default( create_client: SyncClientCallable, ) -> None: with create_client(url, key) as client: - assert client.options.headers.get("apiKey") == key - assert client.options.headers.get("Authorization") == f"Bearer {key}" + assert client.headers.get("apiKey") == key + assert client.headers.get("Authorization") == f"Bearer {key}" assert client.postgrest.default_headers.get("apiKey") == key assert client.postgrest.default_headers.get("Authorization") == f"Bearer {key}" @@ -77,8 +77,8 @@ def test_updates_the_authorization_header_on_auth_events( create_client: SyncClientCallable, ) -> None: with create_client(url, key) as client: - assert client.options.headers.get("apiKey") == key - assert client.options.headers.get("Authorization") == f"Bearer {key}" + assert client.headers.get("apiKey") == key + assert client.headers.get("Authorization") == f"Bearer {key}" access_token = "secretuserjwt" mock_session = MagicMock(access_token=access_token) @@ -87,8 +87,8 @@ def test_updates_the_authorization_header_on_auth_events( updated_authorization = f"Bearer {access_token}" - assert client.options.headers.get("apiKey") == key - assert client.options.headers.get("Authorization") == updated_authorization + assert client.headers.get("apiKey") == key + assert client.headers.get("Authorization") == updated_authorization assert client.postgrest.default_headers.get("apiKey") == key assert ( @@ -121,8 +121,8 @@ def test_auth_events_with_a_session_use_its_access_token( assert client.postgrest is postgrest assert client.storage is storage assert client.functions is functions - assert client.options.headers.get("apiKey") == key - assert client.options.headers.get("Authorization") == authorization + assert client.headers.get("apiKey") == key + assert client.headers.get("Authorization") == authorization assert client.postgrest.default_headers.get("Authorization") == authorization assert client.storage.default_headers.get("Authorization") == authorization assert client.functions.default_headers.get("Authorization") == authorization @@ -140,7 +140,7 @@ def test_auth_events_without_a_session_use_the_key( client.auth.session_manager.notify_all_subscribers("SIGNED_OUT", None) authorization = f"Bearer {key}" - assert client.options.headers.get("Authorization") == authorization + assert client.headers.get("Authorization") == authorization assert client.postgrest.default_headers.get("Authorization") == authorization assert client.storage.default_headers.get("Authorization") == authorization assert client.functions.default_headers.get("Authorization") == authorization @@ -156,7 +156,7 @@ def test_create_uses_the_stored_session_token() -> None: client = Client.create(url, key, HttpxSession(client=http_client)) authorization = "Bearer secretuserjwt" - assert client.options.headers.get("Authorization") == authorization + assert client.headers.get("Authorization") == authorization assert client.postgrest.default_headers.get("Authorization") == authorization assert client.auth.default_headers.get("Authorization") == authorization @@ -166,11 +166,9 @@ def test_supports_setting_a_global_authorization_header( ) -> None: authorization = "Bearer secretuserjwt" - options = ClientOptions(headers={"Authorization": authorization}) - - with create_client(url, key, options) as client: - assert client.options.headers.get("apiKey") == key - assert client.options.headers.get("Authorization") == authorization + with create_client(url, key, headers={"Authorization": authorization}) as client: + assert client.headers.get("apiKey") == key + assert client.headers.get("Authorization") == authorization assert client.postgrest.default_headers.get("apiKey") == key assert client.postgrest.default_headers.get("Authorization") == authorization @@ -183,50 +181,40 @@ def test_supports_setting_a_global_authorization_header( def test_mutable_headers_issue(create_client: SyncClientCallable) -> None: - shared_options = ClientOptions( - storage=SyncMemoryStorage(), headers={"Authorization": "Bearer initial-token"} - ) + shared_headers = {"Authorization": "Bearer initial-token"} + shared_auth = AuthClientOptions(session_storage=SyncMemoryStorage()) with ( - create_client(url, key, shared_options) as client1, - create_client(url, key, shared_options) as client2, + create_client(url, key, headers=shared_headers, auth=shared_auth) as client1, + create_client(url, key, headers=shared_headers, auth=shared_auth) as client2, ): client1._set_access_token("modified-token") - assert client2.options.headers["Authorization"] == "Bearer initial-token" - assert client1.options.headers["Authorization"] == "Bearer modified-token" - assert shared_options.headers["Authorization"] == "Bearer initial-token" + assert client2.headers["Authorization"] == "Bearer initial-token" + assert client1.headers["Authorization"] == "Bearer modified-token" + assert shared_headers["Authorization"] == "Bearer initial-token" def test_global_authorization_header_issue(create_client: SyncClientCallable) -> None: authorization = "Bearer secretuserjwt" - options = ClientOptions(headers={"Authorization": authorization}) - - with create_client(url, key, options) as client: - assert client.options.headers.get("apiKey") == key + with create_client(url, key, headers={"Authorization": authorization}) as client: + assert client.headers.get("apiKey") == key def test_custom_headers(create_client: SyncClientCallable) -> None: - options = ClientOptions( - headers={ - "x-app-name": "apple", - "x-version": "1.0", - } - ) + headers = {"x-app-name": "apple", "x-version": "1.0"} - with create_client(url, key, options) as client: - assert client.options.headers.get("x-app-name") == "apple" - assert client.options.headers.get("x-version") == "1.0" + with create_client(url, key, headers=headers) as client: + assert client.headers.get("x-app-name") == "apple" + assert client.headers.get("x-version") == "1.0" def test_custom_headers_immutable(create_client: SyncClientCallable) -> None: headers = {"x-app-name": "apple", "x-version": "1.0"} - options = ClientOptions(headers=headers) - headers["x-app-name"] = "grapes" + with create_client(url, key, headers=headers) as client: + headers["x-app-name"] = "grapes" - with create_client(url, key, options) as client: - assert client.options.headers.get("x-app-name") == "apple" - assert client.options.headers.get("x-version") == "1.0" - assert options.headers.get("x-app-name") == "apple" + assert client.headers.get("x-app-name") == "apple" + assert client.headers.get("x-version") == "1.0" def test_httpx_client_base_url_isolation(create_client: SyncClientCallable) -> None: @@ -236,8 +224,7 @@ def test_httpx_client_base_url_isolation(create_client: SyncClientCallable) -> N See: https://github.com/supabase/supabase-py/issues/1244 """ # Create client with shared httpx instance - options = ClientOptions() - with create_client(url, key, options) as client: + with create_client(url, key) as client: # Access storage and capture its base_url storage = client.storage storage_base_url = str(storage.base_url).rstrip("/") diff --git a/src/supabase/tests/test_client.py b/src/supabase/tests/test_client.py index ec63789b4..d756fd62d 100644 --- a/src/supabase/tests/test_client.py +++ b/src/supabase/tests/test_client.py @@ -4,14 +4,18 @@ import pytest from httpx import AsyncClient as AsyncHttpxClient from httpx import Client as SyncHttpxClient -from supabase_auth import AsyncSupabaseAuthClient, SyncSupabaseAuthClient +from supabase_auth import ( + AsyncMemoryStorage, + AsyncSupabaseAuthClient, + SyncMemoryStorage, + SyncSupabaseAuthClient, +) from supabase_utils.http.adapters.httpx import AsyncHttpxSession, HttpxSession from supabase import ( AsyncClient, - AsyncClientOptions, + AuthClientOptions, Client, - ClientOptions, FunctionsClientOptions, PostgrestClientOptions, RealtimeClientOptions, @@ -59,31 +63,41 @@ async def test_async_client_requires_a_key() -> None: def test_sync_client_keeps_a_lowercase_authorization_header() -> None: - options = ClientOptions(headers={"authorization": "Bearer userjwt"}) with SyncHttpxClient() as http_client: - client = Client(URL, KEY, HttpxSession(client=http_client), options) + client = Client( + URL, + KEY, + HttpxSession(client=http_client), + headers={"authorization": "Bearer userjwt"}, + ) - assert "authorization" not in client.options.headers - assert client.options.headers["Authorization"] == "Bearer userjwt" + assert "authorization" not in client.headers + assert client.headers["Authorization"] == "Bearer userjwt" assert client.postgrest.default_headers.get("Authorization") == "Bearer userjwt" async def test_async_client_keeps_a_lowercase_authorization_header() -> None: - options = AsyncClientOptions(headers={"authorization": "Bearer userjwt"}) async with AsyncHttpxClient() as http_client: - client = AsyncClient(URL, KEY, AsyncHttpxSession(client=http_client), options) + client = AsyncClient( + URL, + KEY, + AsyncHttpxSession(client=http_client), + headers={"authorization": "Bearer userjwt"}, + ) - assert "authorization" not in client.options.headers - assert client.options.headers["Authorization"] == "Bearer userjwt" + assert "authorization" not in client.headers + assert client.headers["Authorization"] == "Bearer userjwt" assert client.postgrest.default_headers.get("Authorization") == "Bearer userjwt" async def test_async_client_passes_realtime_options_to_connections() -> None: - options = AsyncClientOptions( - realtime=RealtimeClientOptions(heartbeat_interval=30, heartbeat_timeout=10) - ) async with AsyncHttpxClient() as http_client: - client = AsyncClient(URL, KEY, AsyncHttpxSession(client=http_client), options) + client = AsyncClient( + URL, + KEY, + AsyncHttpxSession(client=http_client), + realtime=RealtimeClientOptions(heartbeat_interval=30, heartbeat_timeout=10), + ) connection = client.realtime @@ -92,7 +106,6 @@ async def test_async_client_passes_realtime_options_to_connections() -> None: def test_sync_create_does_not_replace_a_lowercase_authorization_header() -> None: - options = ClientOptions(headers={"authorization": "Bearer userjwt"}) session = MagicMock(access_token="storedjwt") with ( SyncHttpxClient() as http_client, @@ -100,20 +113,27 @@ def test_sync_create_does_not_replace_a_lowercase_authorization_header() -> None SyncSupabaseAuthClient, "get_session", MagicMock(return_value=session) ), ): - client = Client.create(URL, KEY, HttpxSession(client=http_client), options) + client = Client.create( + URL, + KEY, + HttpxSession(client=http_client), + headers={"authorization": "Bearer userjwt"}, + ) assert client.postgrest.default_headers.get("Authorization") == "Bearer userjwt" async def test_async_create_does_not_replace_a_lowercase_authorization_header() -> None: - options = AsyncClientOptions(headers={"authorization": "Bearer userjwt"}) session = MagicMock(access_token="storedjwt") async with AsyncHttpxClient() as http_client: with patch.object( AsyncSupabaseAuthClient, "get_session", AsyncMock(return_value=session) ): client = await AsyncClient.create( - URL, KEY, AsyncHttpxSession(client=http_client), options + URL, + KEY, + AsyncHttpxSession(client=http_client), + headers={"authorization": "Bearer userjwt"}, ) assert client.postgrest.default_headers.get("Authorization") == "Bearer userjwt" @@ -221,10 +241,14 @@ async def test_async_functions_send_the_session_token_with_a_new_format_key( def test_sync_functions_send_a_custom_authorization_header_with_a_new_format_key( key: str, ) -> None: - options = ClientOptions(headers={"Authorization": "Bearer customjwt"}) requests: list[httpx.Request] = [] with SyncHttpxClient(transport=recording_transport(requests)) as http_client: - client = Client(URL, key, HttpxSession(client=http_client), options) + client = Client( + URL, + key, + HttpxSession(client=http_client), + headers={"Authorization": "Bearer customjwt"}, + ) client.functions.invoke("hello") assert requests[0].headers.get("authorization") == "Bearer customjwt" @@ -234,23 +258,29 @@ def test_sync_functions_send_a_custom_authorization_header_with_a_new_format_key async def test_async_functions_send_a_custom_authorization_header_with_a_new_format_key( key: str, ) -> None: - options = AsyncClientOptions(headers={"Authorization": "Bearer customjwt"}) requests: list[httpx.Request] = [] async with AsyncHttpxClient(transport=recording_transport(requests)) as http_client: - client = AsyncClient(URL, key, AsyncHttpxSession(client=http_client), options) + client = AsyncClient( + URL, + key, + AsyncHttpxSession(client=http_client), + headers={"Authorization": "Bearer customjwt"}, + ) await client.functions.invoke("hello") assert requests[0].headers.get("authorization") == "Bearer customjwt" def test_sync_client_passes_request_timeouts_to_sub_clients() -> None: - options = ClientOptions( - request_timeout=10, - postgrest_options=PostgrestClientOptions(request_timeout=3), - storage_options=StorageClientOptions(request_timeout=120), - ) with SyncHttpxClient() as http_client: - client = Client(URL, KEY, HttpxSession(client=http_client), options) + client = Client( + URL, + KEY, + HttpxSession(client=http_client), + request_timeout=10, + postgrest=PostgrestClientOptions(request_timeout=3), + storage=StorageClientOptions(request_timeout=120), + ) assert client.postgrest.executor.request_timeout == 3 assert client.storage.executor.request_timeout == 120 assert client.auth.executor.request_timeout == 10 @@ -258,12 +288,129 @@ def test_sync_client_passes_request_timeouts_to_sub_clients() -> None: async def test_async_client_passes_request_timeouts_to_sub_clients() -> None: - options = AsyncClientOptions( - functions_options=FunctionsClientOptions(request_timeout=60), - ) async with AsyncHttpxClient() as http_client: - client = AsyncClient(URL, KEY, AsyncHttpxSession(client=http_client), options) + client = AsyncClient( + URL, + KEY, + AsyncHttpxSession(client=http_client), + functions=FunctionsClientOptions(request_timeout=60), + ) assert client.functions.executor.request_timeout == 60 assert client.postgrest.executor.request_timeout is None assert client.storage.executor.request_timeout is None assert client.auth.executor.request_timeout is None + + +@pytest.mark.parametrize("request_timeout", [0, -1, float("nan"), float("inf")]) +def test_sync_client_rejects_an_invalid_request_timeout( + request_timeout: float, +) -> None: + with ( + SyncHttpxClient() as http_client, + pytest.raises(ValueError, match="positive number of seconds"), + ): + Client( + URL, + KEY, + HttpxSession(client=http_client), + request_timeout=request_timeout, + ) + + +@pytest.mark.parametrize("request_timeout", [0, -1, float("nan"), float("inf")]) +async def test_async_client_rejects_an_invalid_request_timeout( + request_timeout: float, +) -> None: + async with AsyncHttpxClient() as http_client: + with pytest.raises(ValueError, match="positive number of seconds"): + AsyncClient( + URL, + KEY, + AsyncHttpxSession(client=http_client), + request_timeout=request_timeout, + ) + + +def test_sync_client_passes_service_options_to_sub_clients() -> None: + session_storage = SyncMemoryStorage() + with SyncHttpxClient() as http_client: + client = Client( + URL, + KEY, + HttpxSession(client=http_client), + postgrest=PostgrestClientOptions(schema="private"), + auth=AuthClientOptions( + auto_refresh_token=False, + session_storage=session_storage, + flow_type="implicit", + ), + ) + assert client.postgrest.default_headers.get("Accept-Profile") == "private" + assert client.auth.session_manager.storage is session_storage + assert client.auth.session_manager.auto_refresh_token is False + assert client.auth.flow_type == "implicit" + + +async def test_async_client_passes_service_options_to_sub_clients() -> None: + session_storage = AsyncMemoryStorage() + async with AsyncHttpxClient() as http_client: + client = AsyncClient( + URL, + KEY, + AsyncHttpxSession(client=http_client), + postgrest=PostgrestClientOptions(schema="private"), + auth=AuthClientOptions( + auto_refresh_token=False, + session_storage=session_storage, + flow_type="implicit", + ), + ) + assert client.postgrest.default_headers.get("Accept-Profile") == "private" + assert client.auth.session_manager.storage is session_storage + assert client.auth.session_manager.auto_refresh_token is False + assert client.auth.flow_type == "implicit" + + +def test_sync_client_uses_service_defaults() -> None: + with SyncHttpxClient() as http_client: + client = Client(URL, KEY, HttpxSession(client=http_client)) + assert client.postgrest.default_headers.get("Accept-Profile") == "public" + assert isinstance(client.auth.session_manager.storage, SyncMemoryStorage) + assert client.auth.session_manager.auto_refresh_token is True + assert client.auth.flow_type == "pkce" + + +def test_client_sends_default_headers_with_custom_headers() -> None: + with SyncHttpxClient() as http_client: + client = Client( + URL, KEY, HttpxSession(client=http_client), headers={"x-app": "1"} + ) + + assert client.headers["x-app"] == "1" + assert client.headers["X-Client-Info"].startswith("supabase-py/") + assert ( + client.postgrest.default_headers.get("X-Client-Info") + == (client.headers["X-Client-Info"]) + ) + + +def test_custom_headers_override_default_headers_regardless_of_case() -> None: + with SyncHttpxClient() as http_client: + client = Client( + URL, + KEY, + HttpxSession(client=http_client), + headers={"x-client-info": "my-app"}, + ) + + assert "X-Client-Info" not in client.headers + assert client.headers["x-client-info"] == "my-app" + assert client.postgrest.default_headers.get("X-Client-Info") == "my-app" + + +def test_client_headers_are_read_only() -> None: + with SyncHttpxClient() as http_client: + client = Client(URL, KEY, HttpxSession(client=http_client)) + + with pytest.raises(TypeError): + client.headers["x-app"] = "1" # pyrefly: ignore[unsupported-operation] diff --git a/src/supabase/tests/test_client_options.py b/src/supabase/tests/test_client_options.py index e6e7d2787..6747b6bbe 100644 --- a/src/supabase/tests/test_client_options.py +++ b/src/supabase/tests/test_client_options.py @@ -1,110 +1,49 @@ import dataclasses import pytest -from supabase_auth import AsyncMemoryStorage, SyncMemoryStorage +from supabase_auth import SyncMemoryStorage from supabase import ( - AsyncClientOptions, AuthClientOptions, - ClientOptions, FunctionsClientOptions, PostgrestClientOptions, RealtimeClientOptions, StorageClientOptions, ) +from supabase.types import _ServiceClientOptions +SERVICE_OPTIONS = [ + PostgrestClientOptions, + AuthClientOptions, + StorageClientOptions, + FunctionsClientOptions, +] -class TestClientOptions: - async def test_replace_returns_updated_async_client_options(self) -> None: - storage = AsyncMemoryStorage() - await storage.set_item("key", "value") - options = AsyncClientOptions( - schema="schema", - headers={"key": "value"}, - auto_refresh_token=False, - persist_session=False, - storage=storage, - ) - - actual = options.replace(schema="new schema") - expected = AsyncClientOptions( - schema="new schema", - headers={"key": "value"}, - auto_refresh_token=False, - persist_session=False, - storage=storage, - ) - - assert actual == expected - def test_replace_returns_updated_options(self) -> None: - storage = SyncMemoryStorage() - storage.set_item("key", "value") - options = ClientOptions( - schema="schema", - headers={"key": "value"}, - auto_refresh_token=False, - persist_session=False, - storage=storage, - ) +class TestClientOptions: + def test_postgrest_options_default_to_the_public_schema(self) -> None: + assert PostgrestClientOptions().schema == "public" - actual = options.replace(schema="new schema") - assert actual - expected = ClientOptions( - schema="new schema", - headers={"key": "value"}, - auto_refresh_token=False, - persist_session=False, - storage=storage, - ) + def test_auth_options_defaults(self) -> None: + options = AuthClientOptions() - assert actual == expected + assert options.auto_refresh_token is True + assert options.session_storage is None + assert options.flow_type == "pkce" - def test_replace_updates_only_new_options(self) -> None: - # Arrange + def test_dataclasses_replace_keeps_the_other_fields(self) -> None: storage = SyncMemoryStorage() - storage.set_item("key", "value") - options = ClientOptions(storage=storage) - new_options = options.replace() - - # Act - new_options.storage.set_item("key", "new_value") - - # Assert - assert options.storage.get_item("key") == "new_value" - assert new_options.storage.get_item("key") == "new_value" - - def test_replace_honors_falsy_values(self) -> None: - options = ClientOptions(headers={"key": "value"}) - - actual = options.replace( - auto_refresh_token=False, persist_session=False, headers={} - ) - - assert actual.auto_refresh_token is False - assert actual.persist_session is False - assert actual.headers == {} - - def test_replace_keeps_realtime_options(self) -> None: - realtime = RealtimeClientOptions(heartbeat_interval=1) + options = AuthClientOptions(session_storage=storage, request_timeout=10) - assert ( - ClientOptions(realtime=realtime).replace(schema="other").realtime - == realtime - ) - assert ( - AsyncClientOptions(realtime=realtime).replace(schema="other").realtime - == realtime - ) - - def test_replace_updates_realtime_options(self) -> None: - options = ClientOptions(realtime=RealtimeClientOptions(heartbeat_interval=1)) - realtime = RealtimeClientOptions(heartbeat_timeout=10) + updated = dataclasses.replace(options, flow_type="implicit") - assert options.replace(realtime=realtime).realtime == realtime + assert updated.session_storage is storage + assert updated.request_timeout == 10 + assert updated.flow_type == "implicit" + assert options.flow_type == "pkce" def test_realtime_options_default_to_realtime_defaults(self) -> None: - assert ClientOptions().realtime == RealtimeClientOptions( + assert RealtimeClientOptions() == RealtimeClientOptions( heartbeat_interval=25, heartbeat_timeout=5 ) @@ -131,70 +70,32 @@ def test_realtime_options_reject_non_positive_durations( heartbeat_timeout=heartbeat_timeout, ) - def test_options_are_frozen(self) -> None: - options = ClientOptions() + @pytest.mark.parametrize("options_class", SERVICE_OPTIONS) + def test_service_options_are_frozen( + self, options_class: type[_ServiceClientOptions] + ) -> None: + options = options_class() with pytest.raises(dataclasses.FrozenInstanceError): - options.schema = "other" # pyrefly: ignore[read-only] - - def test_options_copy_the_given_headers(self) -> None: - headers = {"key": "value"} - options = ClientOptions(headers=headers) - - headers["key"] = "changed" - - assert options.headers == {"key": "value"} - - def test_request_timeouts_default_to_none(self) -> None: - options = ClientOptions() - - assert options.request_timeout is None - assert options.postgrest_options.request_timeout is None - assert options.auth_options.request_timeout is None - assert options.storage_options.request_timeout is None - assert options.functions_options.request_timeout is None - - def test_replace_keeps_and_updates_request_timeouts(self) -> None: - options = AsyncClientOptions( - request_timeout=10, - storage_options=StorageClientOptions(request_timeout=120), - ) - - kept = options.replace(schema="other") - updated = options.replace( - request_timeout=20, - postgrest_options=PostgrestClientOptions(request_timeout=5), - auth_options=AuthClientOptions(request_timeout=6), - functions_options=FunctionsClientOptions(request_timeout=7), - ) + options.request_timeout = 10 # pyrefly: ignore[read-only] - assert kept.request_timeout == 10 - assert kept.storage_options.request_timeout == 120 - assert updated.request_timeout == 20 - assert updated.storage_options.request_timeout == 120 - assert updated.postgrest_options.request_timeout == 5 - assert updated.auth_options.request_timeout == 6 - assert updated.functions_options.request_timeout == 7 - - def test_replace_clears_request_timeout_with_none(self) -> None: - options = ClientOptions(request_timeout=10) + @pytest.mark.parametrize("options_class", SERVICE_OPTIONS) + def test_service_options_are_keyword_only( + self, options_class: type[_ServiceClientOptions] + ) -> None: + with pytest.raises(TypeError): + options_class(10) # pyrefly: ignore[bad-argument-count] - assert options.replace(request_timeout=None).request_timeout is None + @pytest.mark.parametrize("options_class", SERVICE_OPTIONS) + def test_request_timeout_defaults_to_none( + self, options_class: type[_ServiceClientOptions] + ) -> None: + assert options_class().request_timeout is None - @pytest.mark.parametrize( - "options_class", - [ - PostgrestClientOptions, - AuthClientOptions, - StorageClientOptions, - FunctionsClientOptions, - ClientOptions, - AsyncClientOptions, - ], - ) + @pytest.mark.parametrize("options_class", SERVICE_OPTIONS) @pytest.mark.parametrize("timeout", [0, -1, float("nan"), float("inf")]) def test_request_timeout_must_be_positive( - self, options_class: type, timeout: float + self, options_class: type[_ServiceClientOptions], timeout: float ) -> None: with pytest.raises(ValueError, match="positive number of seconds"): options_class(request_timeout=timeout) From e5384a9789780684047cde6d3b606602e78663f5 Mon Sep 17 00:00:00 2001 From: Lukas Klingsbo Date: Fri, 6 Nov 2026 17:23:15 +0100 Subject: [PATCH 2/3] fix(supabase): address review findings on client options --- MIGRATION.md | 38 ++++++++++++++--------------- sdk-compliance.yaml | 2 ++ src/supabase/src/supabase/client.py | 2 +- src/supabase/tests/test_client.py | 12 +++++++++ 4 files changed, 34 insertions(+), 20 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index dc05f3a53..7a31e8f21 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -63,7 +63,7 @@ Names that mirror a wire format keep their wire spelling, for example the JWT cl ## Client options are keyword arguments -`ClientOptions`, `AsyncClientOptions` and the `supabase.lib.client_options` module are removed. `create_client`, `create_async_client`, `Client`, `AsyncClient` and their `create` methods take the settings as keyword-only arguments. Settings that apply to every service are arguments of their own. The settings of one service are grouped in an options class, passed in the argument named after the service. +`ClientOptions`, `AsyncClientOptions`, their v2 names `SyncClientOptions` and `AClientOptions`, and the `supabase.lib.client_options` module are removed. `create_client`, `create_async_client`, `Client`, `AsyncClient` and their `create` methods take the settings as keyword-only arguments. Settings that apply to every service are arguments of their own. The settings of one service are grouped in an options class, passed in the argument named after the service. ```python client = create_client( @@ -77,23 +77,23 @@ client = create_client( ) ``` -| Before | After | -| -------------------------------------------------------------- | ---------------------------------------------------- | -| `create_client(url, key, http_client)` | `create_client(url, key, http_client=http_client)` | -| `ClientOptions(headers={"x-app": "1"})` | `headers={"x-app": "1"}` | -| `ClientOptions(request_timeout=30)` | `request_timeout=30` | -| `ClientOptions(schema="private")` | `postgrest=PostgrestClientOptions(schema="private")` | -| `ClientOptions(auto_refresh_token=False)` | `auth=AuthClientOptions(auto_refresh_token=False)` | -| `ClientOptions(storage=my_storage)` | `auth=AuthClientOptions(session_storage=my_storage)` | -| `ClientOptions(flow_type="implicit")` | `auth=AuthClientOptions(flow_type="implicit")` | -| `ClientOptions(persist_session=False)` | Leave it out | -| `ClientOptions(postgrest_options=PostgrestClientOptions(...))` | `postgrest=PostgrestClientOptions(...)` | -| `ClientOptions(auth_options=AuthClientOptions(...))` | `auth=AuthClientOptions(...)` | -| `ClientOptions(storage_options=StorageClientOptions(...))` | `storage=StorageClientOptions(...)` | -| `ClientOptions(functions_options=FunctionsClientOptions(...))` | `functions=FunctionsClientOptions(...)` | -| `AsyncClientOptions(realtime=RealtimeClientOptions(...))` | `realtime=RealtimeClientOptions(...)` | -| `client.options.headers` | `client.headers` | -| `options.replace(schema="other")` | `dataclasses.replace(options, schema="other")` | +| Before | After | +| -------------------------------------------------------------- | ------------------------------------------------------------------ | +| `create_client(url, key, http_client)` | `create_client(url, key, http_client=http_client)` | +| `ClientOptions(headers={"x-app": "1"})` | `headers={"x-app": "1"}` | +| `ClientOptions(request_timeout=30)` | `request_timeout=30` | +| `ClientOptions(schema="private")` | `postgrest=PostgrestClientOptions(schema="private")` | +| `ClientOptions(auto_refresh_token=False)` | `auth=AuthClientOptions(auto_refresh_token=False)` | +| `ClientOptions(storage=my_storage)` | `auth=AuthClientOptions(session_storage=my_storage)` | +| `ClientOptions(flow_type="implicit")` | `auth=AuthClientOptions(flow_type="implicit")` | +| `ClientOptions(persist_session=False)` | Leave it out | +| `ClientOptions(postgrest_options=PostgrestClientOptions(...))` | `postgrest=PostgrestClientOptions(...)` | +| `ClientOptions(auth_options=AuthClientOptions(...))` | `auth=AuthClientOptions(...)` | +| `ClientOptions(storage_options=StorageClientOptions(...))` | `storage=StorageClientOptions(...)` | +| `ClientOptions(functions_options=FunctionsClientOptions(...))` | `functions=FunctionsClientOptions(...)` | +| `AsyncClientOptions(realtime=RealtimeClientOptions(...))` | `realtime=RealtimeClientOptions(...)` | +| `client.options.headers` | `client.headers` | +| `options.replace(schema="other")` | `postgrest=dataclasses.replace(postgrest_options, schema="other")` | `AuthClientOptions.session_storage` takes an `AsyncSupportedStorage` for `AsyncClient` and a `SyncSupportedStorage` for `Client`. It used to be called `storage`, which clashed with the storage service. Left out, the session is kept in memory. @@ -103,7 +103,7 @@ client = create_client( `client.headers` is a read-only view of the headers sent with every request. Its `Authorization` header follows the session. The headers you pass are copied, so changing the original dictionary later has no effect. -The options classes take keyword arguments only. +`PostgrestClientOptions`, `AuthClientOptions`, `StorageClientOptions` and `FunctionsClientOptions` take keyword arguments only. ## Options are dataclasses instead of dictionaries diff --git a/sdk-compliance.yaml b/sdk-compliance.yaml index 99ab3c341..2eb9bdefc 100644 --- a/sdk-compliance.yaml +++ b/sdk-compliance.yaml @@ -482,6 +482,8 @@ features: - SyncPostgrestClient.schema - AsyncClient.schema - Client.schema + supporting_symbols: + - PostgrestClientOptions database.query.rpc: status: implemented symbols: diff --git a/src/supabase/src/supabase/client.py b/src/supabase/src/supabase/client.py index 7c01ecfc8..a8cf1409e 100644 --- a/src/supabase/src/supabase/client.py +++ b/src/supabase/src/supabase/client.py @@ -379,7 +379,7 @@ def _listen_to_auth_events( def _set_access_token(self, access_token: str) -> None: authorization = self._create_auth_header(access_token) - self._headers = {**self._headers, "Authorization": authorization} + self._headers["Authorization"] = authorization self._access_token = access_token self.auth.default_headers = self.auth.default_headers.override( "Authorization", authorization diff --git a/src/supabase/tests/test_client.py b/src/supabase/tests/test_client.py index d756fd62d..c31f99f52 100644 --- a/src/supabase/tests/test_client.py +++ b/src/supabase/tests/test_client.py @@ -414,3 +414,15 @@ def test_client_headers_are_read_only() -> None: with pytest.raises(TypeError): client.headers["x-app"] = "1" # pyrefly: ignore[unsupported-operation] + + +def test_client_headers_follow_the_session() -> None: + with SyncHttpxClient() as http_client: + client = Client(URL, KEY, HttpxSession(client=http_client)) + headers = client.headers + + client.auth.session_manager.notify_all_subscribers( + "SIGNED_IN", MagicMock(access_token="userjwt") + ) + + assert headers["Authorization"] == "Bearer userjwt" From 9d45221033d05db7bfb994ed4e83c1064420a911 Mon Sep 17 00:00:00 2001 From: Lukas Klingsbo Date: Fri, 6 Nov 2026 17:31:50 +0100 Subject: [PATCH 3/3] fix(supabase): validate request_timeout before creating the http client --- src/supabase/README.md | 2 +- src/supabase/src/supabase/aiohttp.py | 2 ++ src/supabase/src/supabase/httpx.py | 3 +++ src/supabase/tests/test_client.py | 24 ++++++++++++++++++++++++ 4 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/supabase/README.md b/src/supabase/README.md index 4cdbdb4d8..519c21642 100644 --- a/src/supabase/README.md +++ b/src/supabase/README.md @@ -63,7 +63,7 @@ supabase: Client = create_client(url, key) For the async client, use `create_async_client` from `supabase.httpx` or `supabase.aiohttp`, which returns an `AsyncClient`. -Settings are keyword arguments. `headers` and `request_timeout` apply to every service. The settings of one service are grouped in an options class: +Settings are keyword arguments. `headers` and `request_timeout` apply to the database, auth, storage and edge functions, not to the realtime connection of `AsyncClient`. The settings of one service are grouped in an options class: ```python from supabase import AuthClientOptions, PostgrestClientOptions, StorageClientOptions diff --git a/src/supabase/src/supabase/aiohttp.py b/src/supabase/src/supabase/aiohttp.py index 69510593e..7fe5dc8a2 100644 --- a/src/supabase/src/supabase/aiohttp.py +++ b/src/supabase/src/supabase/aiohttp.py @@ -3,6 +3,7 @@ from aiohttp import ClientSession from supabase_auth import AsyncSupportedStorage from supabase_utils.http.adapters.aiohttp import AsyncAiohttpSession +from supabase_utils.http.request import validate_request_timeout from .client import AsyncClient from .types import ( @@ -32,6 +33,7 @@ def create_async_client( `http_client` defaults to a new aiohttp client. See `AsyncClient` for the other arguments. """ + validate_request_timeout(request_timeout) client = http_client or ClientSession() return AsyncClient( supabase_url, diff --git a/src/supabase/src/supabase/httpx.py b/src/supabase/src/supabase/httpx.py index 2340b8166..a544b31c3 100644 --- a/src/supabase/src/supabase/httpx.py +++ b/src/supabase/src/supabase/httpx.py @@ -4,6 +4,7 @@ from httpx import Client as SyncHttpxClient from supabase_auth import AsyncSupportedStorage, SyncSupportedStorage from supabase_utils.http.adapters.httpx import AsyncHttpxSession, HttpxSession +from supabase_utils.http.request import validate_request_timeout from .client import AsyncClient, Client from .types import ( @@ -32,6 +33,7 @@ def create_client( `http_client` defaults to a new httpx client. See `Client` for the other arguments. """ + validate_request_timeout(request_timeout) client = http_client or SyncHttpxClient( http2=True, verify=True, @@ -68,6 +70,7 @@ def create_async_client( `http_client` defaults to a new httpx client. See `AsyncClient` for the other arguments. """ + validate_request_timeout(request_timeout) client = http_client or AsyncHttpxClient( http2=True, verify=True, diff --git a/src/supabase/tests/test_client.py b/src/supabase/tests/test_client.py index c31f99f52..9c442834b 100644 --- a/src/supabase/tests/test_client.py +++ b/src/supabase/tests/test_client.py @@ -12,6 +12,8 @@ ) from supabase_utils.http.adapters.httpx import AsyncHttpxSession, HttpxSession +import supabase.aiohttp +import supabase.httpx from supabase import ( AsyncClient, AuthClientOptions, @@ -426,3 +428,25 @@ def test_client_headers_follow_the_session() -> None: ) assert headers["Authorization"] == "Bearer userjwt" + + +@pytest.mark.parametrize("request_timeout", [0, -1, float("nan"), float("inf")]) +def test_factories_reject_an_invalid_request_timeout_before_creating_a_session( + request_timeout: float, +) -> None: + factories = [ + supabase.httpx.create_client, + supabase.httpx.create_async_client, + supabase.aiohttp.create_async_client, + ] + for factory in factories: + with ( + patch("supabase.aiohttp.ClientSession") as aiohttp_session, + patch("supabase.httpx.SyncHttpxClient") as sync_httpx_client, + patch("supabase.httpx.AsyncHttpxClient") as async_httpx_client, + pytest.raises(ValueError, match="positive number of seconds"), + ): + factory(URL, KEY, request_timeout=request_timeout) + aiohttp_session.assert_not_called() + sync_httpx_client.assert_not_called() + async_httpx_client.assert_not_called()