supabase_functions 2.32.0__tar.gz → 2.34.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,15 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: supabase-functions
3
- Version: 2.32.0
3
+ Version: 2.34.0
4
4
  Summary: Library for Supabase Functions
5
5
  Author: Joel Lee, Andrew Smith
6
6
  Author-email: Joel Lee <joel@joellee.org>, Andrew Smith <a.smith@silentworks.co.uk>
7
7
  License-Expression: MIT
8
8
  Requires-Dist: httpx[http2]>=0.26,<0.29
9
- Requires-Dist: strenum>=0.4.15
10
9
  Requires-Dist: yarl>=1.20.1
11
10
  Maintainer: Leonardo Santiago
12
11
  Maintainer-email: Leonardo Santiago <leonardo.santiago@supabase.io>
13
- Requires-Python: >=3.9
12
+ Requires-Python: >=3.11
14
13
  Project-URL: changelog, https://github.com/supabase/supabase-py/tree/main/CHANGELOG.md
15
14
  Project-URL: homepage, https://github.com/supabase/supabase-py/tree/main/src/functions
16
15
  Project-URL: repository, https://github.com/supabase/supabase-py
@@ -33,6 +32,12 @@ uv add supabase_functions
33
32
  poetry add supabase_functions
34
33
  ```
35
34
 
35
+ ## Supabase Service Compatibility
36
+
37
+ `supabase_functions` only guarantees compatibility with the [latest Supabase Edge Runtime release](https://github.com/supabase/edge-runtime/releases). Older Supabase Edge Runtime releases are supported on a best-effort basis, but compatibility is not guaranteed.
38
+
39
+ If you self-host the Supabase Edge Runtime, we recommend upgrading to the latest release when upgrading this SDK.
40
+
36
41
  ## Usage
37
42
 
38
43
  Deploy your Edge Function following the [Supabase Functions documentation](https://supabase.com/docs/guides/functions).
@@ -15,6 +15,12 @@ uv add supabase_functions
15
15
  poetry add supabase_functions
16
16
  ```
17
17
 
18
+ ## Supabase Service Compatibility
19
+
20
+ `supabase_functions` only guarantees compatibility with the [latest Supabase Edge Runtime release](https://github.com/supabase/edge-runtime/releases). Older Supabase Edge Runtime releases are supported on a best-effort basis, but compatibility is not guaranteed.
21
+
22
+ If you self-host the Supabase Edge Runtime, we recommend upgrading to the latest release when upgrading this SDK.
23
+
18
24
  ## Usage
19
25
 
20
26
  Deploy your Edge Function following the [Supabase Functions documentation](https://supabase.com/docs/guides/functions).
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "supabase_functions"
3
- version = "2.32.0" # {x-release-please-version}
3
+ version = "2.34.0" # {x-release-please-version}
4
4
  description = "Library for Supabase Functions"
5
5
  authors = [
6
6
  { name = "Joel Lee", email = "joel@joellee.org" },
@@ -11,10 +11,9 @@ maintainers = [
11
11
  ]
12
12
  license = "MIT"
13
13
  readme = "README.md"
14
- requires-python = ">=3.9"
14
+ requires-python = ">=3.11"
15
15
  dependencies = [
16
16
  "httpx[http2] >=0.26,<0.29",
17
- "strenum >=0.4.15",
18
17
  "yarl>=1.20.1",
19
18
  ]
20
19
 
@@ -26,10 +25,10 @@ changelog = "https://github.com/supabase/supabase-py/tree/main/CHANGELOG.md"
26
25
 
27
26
  [dependency-groups]
28
27
  tests = [
29
- "pyjwt >=2.8.0",
30
- "pytest >=7.4.2,<9.0.0",
28
+ "pyjwt>=2.15.1",
29
+ "pytest >=9.0.3",
31
30
  "pytest-cov >=4,<7",
32
- "pytest-asyncio >=0.21.1,<1.2.0",
31
+ "pytest-asyncio >=1.3.0",
33
32
  ]
34
33
  lints = [
35
34
  "unasync>=0.6.0",
@@ -1,6 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
- from typing import Literal, Union, overload
3
+ from typing import Literal, overload
4
4
 
5
5
  from ._async.functions_client import AsyncFunctionsClient
6
6
  from ._sync.functions_client import SyncFunctionsClient
@@ -16,13 +16,21 @@ __all__ = [
16
16
 
17
17
  @overload
18
18
  def create_client(
19
- url: str, headers: dict[str, str], *, is_async: Literal[True], verify: bool
19
+ url: str,
20
+ headers: dict[str, str],
21
+ *,
22
+ is_async: Literal[True],
23
+ verify: bool = ...,
20
24
  ) -> AsyncFunctionsClient: ...
21
25
 
22
26
 
23
27
  @overload
24
28
  def create_client(
25
- url: str, headers: dict[str, str], *, is_async: Literal[False], verify: bool
29
+ url: str,
30
+ headers: dict[str, str],
31
+ *,
32
+ is_async: Literal[False],
33
+ verify: bool = ...,
26
34
  ) -> SyncFunctionsClient: ...
27
35
 
28
36
 
@@ -32,8 +40,8 @@ def create_client(
32
40
  *,
33
41
  is_async: bool,
34
42
  verify: bool = True,
35
- ) -> Union[AsyncFunctionsClient, SyncFunctionsClient]:
43
+ ) -> AsyncFunctionsClient | SyncFunctionsClient:
36
44
  if is_async:
37
- return AsyncFunctionsClient(url, headers, verify)
45
+ return AsyncFunctionsClient(url, headers, verify=verify)
38
46
  else:
39
- return SyncFunctionsClient(url, headers, verify)
47
+ return SyncFunctionsClient(url, headers, verify=verify)
@@ -1,9 +1,9 @@
1
1
  import platform
2
- import sys
3
- from typing import Any, Dict, Literal, Optional, Union
2
+ from typing import Any, Literal
4
3
  from warnings import warn
5
4
 
6
- from httpx import AsyncClient, HTTPError, QueryParams, Response
5
+ from httpx import URL as HttpxURL
6
+ from httpx import AsyncClient, Headers, HTTPError, QueryParams, Request, Response
7
7
  from yarl import URL
8
8
 
9
9
  from ..errors import FunctionsHttpError, FunctionsRelayError, _error_message_from
@@ -17,36 +17,67 @@ from ..version import __version__
17
17
  HTTPMethod = Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"]
18
18
 
19
19
 
20
+ def _port_or_default(url: HttpxURL) -> int | None:
21
+ if url.port is not None:
22
+ return url.port
23
+ return {"http": 80, "https": 443}.get(url.scheme)
24
+
25
+
26
+ def _keeps_credentials(source: HttpxURL, target: HttpxURL) -> bool:
27
+ if source.host != target.host:
28
+ return False
29
+ if source.scheme == target.scheme:
30
+ return _port_or_default(source) == _port_or_default(target)
31
+ return (
32
+ source.scheme == "http"
33
+ and _port_or_default(source) == 80
34
+ and target.scheme == "https"
35
+ and _port_or_default(target) == 443
36
+ )
37
+
38
+
39
+ class _RedirectGuardClient(AsyncClient):
40
+ """Drops the ``apiKey`` header on redirects that leave the origin.
41
+
42
+ httpx only strips ``Authorization`` on such redirects, so the project key
43
+ (the ``service_role`` key in server side usage) would otherwise be sent to
44
+ whatever host an invoked edge function redirects to.
45
+ """
46
+
47
+ def _redirect_headers(
48
+ self, request: Request, url: HttpxURL, method: str
49
+ ) -> Headers:
50
+ headers = super()._redirect_headers(request, url, method)
51
+ if not _keeps_credentials(request.url, url):
52
+ headers.pop("apiKey", None)
53
+ return headers
54
+
55
+
20
56
  class AsyncFunctionsClient:
21
57
  def __init__(
22
58
  self,
23
59
  url: str,
24
- headers: Dict,
25
- timeout: Optional[int] = None,
26
- verify: Optional[bool] = None,
27
- proxy: Optional[str] = None,
28
- http_client: Optional[AsyncClient] = None,
60
+ headers: dict,
61
+ timeout: int | None = None,
62
+ verify: bool | None = None,
63
+ proxy: str | None = None,
64
+ http_client: AsyncClient | None = None,
29
65
  ) -> None:
30
66
  if not is_http_url(url):
31
67
  raise ValueError("url must be a valid HTTP URL string")
32
68
  self.url = URL(url)
33
- self.headers = {
34
- "X-Client-Info": (
35
- f"supabase-py/supabase_functions v{__version__}"
36
- f"; platform={platform.system()}"
37
- f"; platform-version={platform.release()}"
38
- f"; runtime=python"
39
- f"; runtime-version={platform.python_version()}"
40
- ),
41
- **headers,
42
- }
43
-
44
- if sys.version_info < (3, 10):
45
- warn(
46
- "Python versions below 3.10 are deprecated and will not be supported in future versions. Please upgrade to Python 3.10 or newer.",
47
- DeprecationWarning,
48
- stacklevel=2,
49
- )
69
+ self.headers = Headers(
70
+ {
71
+ "X-Client-Info": (
72
+ f"supabase-py/supabase_functions v{__version__}"
73
+ f"; platform={platform.system()}"
74
+ f"; platform-version={platform.release()}"
75
+ f"; runtime=python"
76
+ f"; runtime-version={platform.python_version()}"
77
+ )
78
+ }
79
+ )
80
+ self.headers.update(headers)
50
81
 
51
82
  if timeout is not None:
52
83
  warn(
@@ -69,7 +100,7 @@ class AsyncFunctionsClient:
69
100
 
70
101
  self.verify = bool(verify) if verify is not None else True
71
102
  self.timeout = int(abs(timeout)) if timeout is not None else 60
72
- self._client = http_client or AsyncClient(
103
+ self._client = http_client or _RedirectGuardClient(
73
104
  verify=self.verify,
74
105
  timeout=self.timeout,
75
106
  proxy=proxy,
@@ -81,12 +112,11 @@ class AsyncFunctionsClient:
81
112
  self,
82
113
  method: HTTPMethod,
83
114
  path: list[str],
84
- headers: Optional[Dict[str, str]] = None,
85
- json: Optional[Union[Dict[Any, Any], str, bytes]] = None,
86
- params: Optional[QueryParams] = None,
115
+ headers: Headers,
116
+ json: dict[Any, Any] | str | bytes | None = None,
117
+ params: QueryParams | None = None,
87
118
  ) -> Response:
88
119
  url = self.url.joinpath(*path)
89
- headers = {**self.headers, **(headers or {})}
90
120
  response = (
91
121
  await self._client.request(
92
122
  method, str(url), content=json, headers=headers, params=params
@@ -96,6 +126,9 @@ class AsyncFunctionsClient:
96
126
  method, str(url), json=json, headers=headers, params=params
97
127
  )
98
128
  )
129
+ # Relay failures set this header even on non-2xx responses.
130
+ if response.headers.get("x-relay-error") == "true":
131
+ raise FunctionsRelayError(response.text, response.status_code)
99
132
  try:
100
133
  response.raise_for_status()
101
134
  except HTTPError as exc:
@@ -123,13 +156,14 @@ class AsyncFunctionsClient:
123
156
  self.headers["Authorization"] = f"Bearer {token}"
124
157
 
125
158
  async def invoke(
126
- self, function_name: str, invoke_options: Optional[Dict] = None
127
- ) -> Union[Dict, bytes]:
159
+ self, function_name: str, invoke_options: dict | None = None
160
+ ) -> dict | bytes:
128
161
  """Invokes a function
129
162
 
130
163
  Parameters
131
164
  ----------
132
- function_name : the name of the function to invoke
165
+ function_name : the name of the function to invoke. It may carry a query
166
+ string, as in `hello?name=bob`. A `#fragment` is dropped.
133
167
  invoke_options : object with the following properties
134
168
  `headers`: object representing the headers to send with the request
135
169
  `body`: the body of the request
@@ -138,8 +172,13 @@ class AsyncFunctionsClient:
138
172
  """
139
173
  if not is_valid_str_arg(function_name):
140
174
  raise ValueError("function_name must a valid string value.")
141
- headers: Dict[str, str] = {}
142
- params = QueryParams()
175
+ # Like a URL, a name such as "hello?name=bob" carries query params and
176
+ # the fragment is never sent.
177
+ path, _, query = function_name.split("#", 1)[0].partition("?")
178
+ if not is_valid_str_arg(path):
179
+ raise ValueError("function_name must a valid string value.")
180
+ headers = Headers(self.headers)
181
+ params = QueryParams(query)
143
182
  body = None
144
183
  method: HTTPMethod = "POST"
145
184
  response_type = "text/plain"
@@ -161,24 +200,17 @@ class AsyncFunctionsClient:
161
200
  params = params.set("forceFunctionRegion", region.value)
162
201
 
163
202
  body = invoke_options.get("body")
164
- if isinstance(body, str):
165
- headers["Content-Type"] = "text/plain"
166
- elif isinstance(body, dict):
167
- headers["Content-Type"] = "application/json"
168
- elif isinstance(body, bytes):
169
- headers["Content-Type"] = "application/octet-stream"
203
+ if headers.get("content-type", None) is None:
204
+ if isinstance(body, str):
205
+ headers["Content-Type"] = "text/plain"
206
+ elif isinstance(body, dict):
207
+ headers["Content-Type"] = "application/json"
208
+ elif isinstance(body, bytes):
209
+ headers["Content-Type"] = "application/octet-stream"
170
210
 
171
211
  response = await self._request(
172
- method, [function_name], headers=headers, json=body, params=params
212
+ method, [path], headers=headers, json=body, params=params
173
213
  )
174
- is_relay_error = response.headers.get("x-relay-header")
175
-
176
- if is_relay_error and is_relay_error == "true":
177
- raise FunctionsRelayError(
178
- _error_message_from(response)
179
- or "An error occurred while relaying your edge function request."
180
- )
181
-
182
214
  if response_type == "json":
183
215
  data = response.json()
184
216
  else:
@@ -1,9 +1,9 @@
1
1
  import platform
2
- import sys
3
- from typing import Any, Dict, Literal, Optional, Union
2
+ from typing import Any, Literal
4
3
  from warnings import warn
5
4
 
6
- from httpx import Client, HTTPError, QueryParams, Response
5
+ from httpx import URL as HttpxURL
6
+ from httpx import Client, Headers, HTTPError, QueryParams, Request, Response
7
7
  from yarl import URL
8
8
 
9
9
  from ..errors import FunctionsHttpError, FunctionsRelayError, _error_message_from
@@ -17,36 +17,67 @@ from ..version import __version__
17
17
  HTTPMethod = Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"]
18
18
 
19
19
 
20
+ def _port_or_default(url: HttpxURL) -> int | None:
21
+ if url.port is not None:
22
+ return url.port
23
+ return {"http": 80, "https": 443}.get(url.scheme)
24
+
25
+
26
+ def _keeps_credentials(source: HttpxURL, target: HttpxURL) -> bool:
27
+ if source.host != target.host:
28
+ return False
29
+ if source.scheme == target.scheme:
30
+ return _port_or_default(source) == _port_or_default(target)
31
+ return (
32
+ source.scheme == "http"
33
+ and _port_or_default(source) == 80
34
+ and target.scheme == "https"
35
+ and _port_or_default(target) == 443
36
+ )
37
+
38
+
39
+ class _RedirectGuardClient(Client):
40
+ """Drops the ``apiKey`` header on redirects that leave the origin.
41
+
42
+ httpx only strips ``Authorization`` on such redirects, so the project key
43
+ (the ``service_role`` key in server side usage) would otherwise be sent to
44
+ whatever host an invoked edge function redirects to.
45
+ """
46
+
47
+ def _redirect_headers(
48
+ self, request: Request, url: HttpxURL, method: str
49
+ ) -> Headers:
50
+ headers = super()._redirect_headers(request, url, method)
51
+ if not _keeps_credentials(request.url, url):
52
+ headers.pop("apiKey", None)
53
+ return headers
54
+
55
+
20
56
  class SyncFunctionsClient:
21
57
  def __init__(
22
58
  self,
23
59
  url: str,
24
- headers: Dict,
25
- timeout: Optional[int] = None,
26
- verify: Optional[bool] = None,
27
- proxy: Optional[str] = None,
28
- http_client: Optional[Client] = None,
60
+ headers: dict,
61
+ timeout: int | None = None,
62
+ verify: bool | None = None,
63
+ proxy: str | None = None,
64
+ http_client: Client | None = None,
29
65
  ) -> None:
30
66
  if not is_http_url(url):
31
67
  raise ValueError("url must be a valid HTTP URL string")
32
68
  self.url = URL(url)
33
- self.headers = {
34
- "X-Client-Info": (
35
- f"supabase-py/supabase_functions v{__version__}"
36
- f"; platform={platform.system()}"
37
- f"; platform-version={platform.release()}"
38
- f"; runtime=python"
39
- f"; runtime-version={platform.python_version()}"
40
- ),
41
- **headers,
42
- }
43
-
44
- if sys.version_info < (3, 10):
45
- warn(
46
- "Python versions below 3.10 are deprecated and will not be supported in future versions. Please upgrade to Python 3.10 or newer.",
47
- DeprecationWarning,
48
- stacklevel=2,
49
- )
69
+ self.headers = Headers(
70
+ {
71
+ "X-Client-Info": (
72
+ f"supabase-py/supabase_functions v{__version__}"
73
+ f"; platform={platform.system()}"
74
+ f"; platform-version={platform.release()}"
75
+ f"; runtime=python"
76
+ f"; runtime-version={platform.python_version()}"
77
+ )
78
+ }
79
+ )
80
+ self.headers.update(headers)
50
81
 
51
82
  if timeout is not None:
52
83
  warn(
@@ -69,7 +100,7 @@ class SyncFunctionsClient:
69
100
 
70
101
  self.verify = bool(verify) if verify is not None else True
71
102
  self.timeout = int(abs(timeout)) if timeout is not None else 60
72
- self._client = http_client or Client(
103
+ self._client = http_client or _RedirectGuardClient(
73
104
  verify=self.verify,
74
105
  timeout=self.timeout,
75
106
  proxy=proxy,
@@ -81,12 +112,11 @@ class SyncFunctionsClient:
81
112
  self,
82
113
  method: HTTPMethod,
83
114
  path: list[str],
84
- headers: Optional[Dict[str, str]] = None,
85
- json: Optional[Union[Dict[Any, Any], str, bytes]] = None,
86
- params: Optional[QueryParams] = None,
115
+ headers: Headers,
116
+ json: dict[Any, Any] | str | bytes | None = None,
117
+ params: QueryParams | None = None,
87
118
  ) -> Response:
88
119
  url = self.url.joinpath(*path)
89
- headers = {**self.headers, **(headers or {})}
90
120
  response = (
91
121
  self._client.request(
92
122
  method, str(url), content=json, headers=headers, params=params
@@ -96,6 +126,9 @@ class SyncFunctionsClient:
96
126
  method, str(url), json=json, headers=headers, params=params
97
127
  )
98
128
  )
129
+ # Relay failures set this header even on non-2xx responses.
130
+ if response.headers.get("x-relay-error") == "true":
131
+ raise FunctionsRelayError(response.text, response.status_code)
99
132
  try:
100
133
  response.raise_for_status()
101
134
  except HTTPError as exc:
@@ -123,13 +156,14 @@ class SyncFunctionsClient:
123
156
  self.headers["Authorization"] = f"Bearer {token}"
124
157
 
125
158
  def invoke(
126
- self, function_name: str, invoke_options: Optional[Dict] = None
127
- ) -> Union[Dict, bytes]:
159
+ self, function_name: str, invoke_options: dict | None = None
160
+ ) -> dict | bytes:
128
161
  """Invokes a function
129
162
 
130
163
  Parameters
131
164
  ----------
132
- function_name : the name of the function to invoke
165
+ function_name : the name of the function to invoke. It may carry a query
166
+ string, as in `hello?name=bob`. A `#fragment` is dropped.
133
167
  invoke_options : object with the following properties
134
168
  `headers`: object representing the headers to send with the request
135
169
  `body`: the body of the request
@@ -138,8 +172,13 @@ class SyncFunctionsClient:
138
172
  """
139
173
  if not is_valid_str_arg(function_name):
140
174
  raise ValueError("function_name must a valid string value.")
141
- headers: Dict[str, str] = {}
142
- params = QueryParams()
175
+ # Like a URL, a name such as "hello?name=bob" carries query params and
176
+ # the fragment is never sent.
177
+ path, _, query = function_name.split("#", 1)[0].partition("?")
178
+ if not is_valid_str_arg(path):
179
+ raise ValueError("function_name must a valid string value.")
180
+ headers = Headers(self.headers)
181
+ params = QueryParams(query)
143
182
  body = None
144
183
  method: HTTPMethod = "POST"
145
184
  response_type = "text/plain"
@@ -161,24 +200,17 @@ class SyncFunctionsClient:
161
200
  params = params.set("forceFunctionRegion", region.value)
162
201
 
163
202
  body = invoke_options.get("body")
164
- if isinstance(body, str):
165
- headers["Content-Type"] = "text/plain"
166
- elif isinstance(body, dict):
167
- headers["Content-Type"] = "application/json"
168
- elif isinstance(body, bytes):
169
- headers["Content-Type"] = "application/octet-stream"
203
+ if headers.get("content-type", None) is None:
204
+ if isinstance(body, str):
205
+ headers["Content-Type"] = "text/plain"
206
+ elif isinstance(body, dict):
207
+ headers["Content-Type"] = "application/json"
208
+ elif isinstance(body, bytes):
209
+ headers["Content-Type"] = "application/octet-stream"
170
210
 
171
211
  response = self._request(
172
- method, [function_name], headers=headers, json=body, params=params
212
+ method, [path], headers=headers, json=body, params=params
173
213
  )
174
- is_relay_error = response.headers.get("x-relay-header")
175
-
176
- if is_relay_error and is_relay_error == "true":
177
- raise FunctionsRelayError(
178
- _error_message_from(response)
179
- or "An error occurred while relaying your edge function request."
180
- )
181
-
182
214
  if response_type == "json":
183
215
  data = response.json()
184
216
  else:
@@ -1,13 +1,7 @@
1
- import sys
1
+ from enum import StrEnum
2
2
  from urllib.parse import urlparse
3
3
 
4
- from httpx import AsyncClient as AsyncClient # noqa: F401
5
-
6
- if sys.version_info >= (3, 11):
7
- from enum import StrEnum
8
- else:
9
- from strenum import StrEnum
10
-
4
+ from httpx import AsyncClient as AsyncClient
11
5
 
12
6
  DEFAULT_FUNCTION_CLIENT_TIMEOUT = 5
13
7
  BASE64URL_REGEX = r"^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$"
@@ -0,0 +1 @@
1
+ __version__ = "2.34.0" # {x-release-please-version}
@@ -1 +0,0 @@
1
- __version__ = "2.32.0" # {x-release-please-version}