supabase_functions 2.34.0__tar.gz → 3.0.0a1__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,15 +1,17 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: supabase-functions
3
- Version: 2.34.0
3
+ Version: 3.0.0a1
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
- Requires-Dist: httpx[http2]>=0.26,<0.29
8
+ Requires-Dist: pydantic>=2.12.2
9
+ Requires-Dist: strenum>=0.4.15
10
+ Requires-Dist: supabase-utils==3.0.0a1
9
11
  Requires-Dist: yarl>=1.20.1
10
12
  Maintainer: Leonardo Santiago
11
13
  Maintainer-email: Leonardo Santiago <leonardo.santiago@supabase.io>
12
- Requires-Python: >=3.11
14
+ Requires-Python: >=3.10
13
15
  Project-URL: changelog, https://github.com/supabase/supabase-py/tree/main/CHANGELOG.md
14
16
  Project-URL: homepage, https://github.com/supabase/supabase-py/tree/main/src/functions
15
17
  Project-URL: repository, https://github.com/supabase/supabase-py
@@ -32,12 +34,6 @@ uv add supabase_functions
32
34
  poetry add supabase_functions
33
35
  ```
34
36
 
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
-
41
37
  ## Usage
42
38
 
43
39
  Deploy your Edge Function following the [Supabase Functions documentation](https://supabase.com/docs/guides/functions).
@@ -52,7 +48,7 @@ from supabase_functions import AsyncFunctionsClient
52
48
  async def run_func():
53
49
  # Initialize the client with your project URL and optional headers
54
50
  headers = {
55
- "Authorization": "Bearer your-publishable-key",
51
+ "Authorization": "Bearer your-anon-key",
56
52
  # Add any other headers you might need
57
53
  }
58
54
 
@@ -76,7 +72,7 @@ if __name__ == "__main__":
76
72
  from supabase_functions import SyncFunctionsClient
77
73
 
78
74
  # Initialize the client
79
- headers = {"Authorization": "Bearer your-publishable-key"}
75
+ headers = {"Authorization": "Bearer your-anon-key"}
80
76
  fc = SyncFunctionsClient("https://<project_ref>.functions.supabase.co", headers)
81
77
 
82
78
  # Invoke your Edge Function
@@ -15,12 +15,6 @@ 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
-
24
18
  ## Usage
25
19
 
26
20
  Deploy your Edge Function following the [Supabase Functions documentation](https://supabase.com/docs/guides/functions).
@@ -35,7 +29,7 @@ from supabase_functions import AsyncFunctionsClient
35
29
  async def run_func():
36
30
  # Initialize the client with your project URL and optional headers
37
31
  headers = {
38
- "Authorization": "Bearer your-publishable-key",
32
+ "Authorization": "Bearer your-anon-key",
39
33
  # Add any other headers you might need
40
34
  }
41
35
 
@@ -59,7 +53,7 @@ if __name__ == "__main__":
59
53
  from supabase_functions import SyncFunctionsClient
60
54
 
61
55
  # Initialize the client
62
- headers = {"Authorization": "Bearer your-publishable-key"}
56
+ headers = {"Authorization": "Bearer your-anon-key"}
63
57
  fc = SyncFunctionsClient("https://<project_ref>.functions.supabase.co", headers)
64
58
 
65
59
  # Invoke your Edge Function
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "supabase_functions"
3
- version = "2.34.0" # {x-release-please-version}
3
+ version = "3.0.0a1" # {x-release-please-version}
4
4
  description = "Library for Supabase Functions"
5
5
  authors = [
6
6
  { name = "Joel Lee", email = "joel@joellee.org" },
@@ -11,9 +11,11 @@ maintainers = [
11
11
  ]
12
12
  license = "MIT"
13
13
  readme = "README.md"
14
- requires-python = ">=3.11"
14
+ requires-python = ">=3.10"
15
15
  dependencies = [
16
- "httpx[http2] >=0.26,<0.29",
16
+ "pydantic>=2.12.2",
17
+ "strenum >=0.4.15",
18
+ "supabase-utils==3.0.0a1", # x-release-please-version
17
19
  "yarl>=1.20.1",
18
20
  ]
19
21
 
@@ -25,13 +27,13 @@ changelog = "https://github.com/supabase/supabase-py/tree/main/CHANGELOG.md"
25
27
 
26
28
  [dependency-groups]
27
29
  tests = [
28
- "pyjwt>=2.15.1",
29
- "pytest >=9.0.3",
30
+ "pyjwt >=2.8.0",
31
+ "pytest >=7.4.2,<9.0.0",
30
32
  "pytest-cov >=4,<7",
31
- "pytest-asyncio >=1.3.0",
33
+ "pytest-asyncio >=0.21.1,<1.2.0",
34
+ "supabase_utils[all]",
32
35
  ]
33
36
  lints = [
34
- "unasync>=0.6.0",
35
37
  "ruff >=0.12.1",
36
38
  "python-lsp-server (>=1.12.2,<2.0.0)",
37
39
  "pylsp-mypy (>=0.7.0,<0.8.0)",
@@ -42,6 +44,9 @@ dev = [{ include-group = "lints" }, {include-group = "tests" }]
42
44
  [tool.uv]
43
45
  default-groups = [ "dev" ]
44
46
 
47
+ [tool.uv.sources]
48
+ supabase-utils = { workspace = true }
49
+
45
50
  [tool.pytest.ini_options]
46
51
  asyncio_mode = "auto"
47
52
  addopts = "tests"
@@ -49,6 +54,32 @@ filterwarnings = [
49
54
  "ignore::DeprecationWarning", # ignore deprecation warnings globally
50
55
  ]
51
56
 
57
+ [tool.ruff.lint]
58
+ select = [
59
+ # pycodestyle
60
+ "E",
61
+ # Pyflakes
62
+ "F",
63
+ # pyupgrade
64
+ "UP",
65
+ # flake8-bugbear
66
+ # "B",
67
+ # flake8-simplify
68
+ # "SIM",
69
+ # isort
70
+ "I",
71
+ ]
72
+ ignore = ["E712", "E501", "E402", "UP006", "UP035"]
73
+
52
74
  [build-system]
53
75
  requires = ["uv_build>=0.8.3,<0.9.0"]
54
76
  build-backend = "uv_build"
77
+
78
+ [tool.mypy]
79
+ strict = true
80
+ allow_redefinition = true
81
+
82
+ no_warn_no_return = true
83
+ warn_return_any = true
84
+ warn_unused_configs = true
85
+ warn_redundant_casts = true
@@ -0,0 +1,11 @@
1
+ from __future__ import annotations
2
+
3
+ from .client import AsyncFunctionsClient, SyncFunctionsClient, create_client
4
+ from .utils import FunctionRegion
5
+
6
+ __all__ = [
7
+ "create_client",
8
+ "FunctionRegion",
9
+ "AsyncFunctionsClient",
10
+ "SyncFunctionsClient",
11
+ ]
@@ -0,0 +1,198 @@
1
+ import platform
2
+ from typing import Dict, Generic, Literal, overload
3
+
4
+ from httpx import AsyncClient, Client
5
+ from supabase_utils.http.adapters.httpx import AsyncHttpxSession, HttpxSession
6
+ from supabase_utils.http.headers import Headers
7
+ from supabase_utils.http.io import (
8
+ AsyncHttpIO,
9
+ HttpIO,
10
+ HttpMethod,
11
+ SyncHttpIO,
12
+ handle_http_io,
13
+ )
14
+ from supabase_utils.http.query import URLQuery
15
+ from supabase_utils.http.request import (
16
+ BytesRequest,
17
+ EmptyRequest,
18
+ HTTPRequestMethod,
19
+ JSONRequest,
20
+ Response,
21
+ TextRequest,
22
+ ToRequest,
23
+ )
24
+ from supabase_utils.types import JSON
25
+ from yarl import URL
26
+
27
+ from .errors import on_error_response
28
+ from .utils import (
29
+ FunctionRegion,
30
+ is_valid_str_arg,
31
+ )
32
+ from .version import __version__
33
+
34
+
35
+ class FunctionsClient(Generic[HttpIO]):
36
+ def __init__(self, url: URL, headers: Dict[str, str], executor: HttpIO) -> None:
37
+ if not (url.scheme == "http" or url.scheme == "https"):
38
+ raise ValueError("url must be a valid HTTP URL string")
39
+ self.default_headers = Headers.from_mapping(
40
+ {
41
+ "X-Client-Info": f"supabase-py/supabase_functions v{__version__}",
42
+ "X-Supabase-Client-Platform": platform.system(),
43
+ "X-Supabase-Client-Platform-Version": platform.release(),
44
+ "X-Supabase-Client-Runtime": "python",
45
+ "X-Supabase-Client-Runtime-Version": platform.python_version(),
46
+ **headers,
47
+ }
48
+ )
49
+
50
+ self.executor: HttpIO = executor
51
+ self.base_url = url
52
+
53
+ def set_auth(self, token: str) -> None:
54
+ """Updates the authorization header
55
+
56
+ Parameters
57
+ ----------
58
+ token : str
59
+ the new jwt token sent in the authorization header
60
+ """
61
+
62
+ self.default_headers = self.default_headers.override(
63
+ "Authorization", f"Bearer {token}"
64
+ )
65
+
66
+ def _invoke_options_to_request(
67
+ self,
68
+ function_name: str,
69
+ body: bytes | str | Dict[str, JSON] | None,
70
+ region: FunctionRegion | None,
71
+ headers: Dict[str, str] | None,
72
+ method: HTTPRequestMethod,
73
+ ) -> ToRequest:
74
+ if not is_valid_str_arg(function_name):
75
+ raise ValueError("function_name must a valid string value.")
76
+
77
+ path = [function_name]
78
+ new_headers = Headers.from_mapping(headers) if headers else Headers.empty()
79
+ query_params = URLQuery.empty()
80
+
81
+ if region and region != FunctionRegion.Any:
82
+ new_headers = new_headers.set("x-region", region.value)
83
+ # Add region as query parameter
84
+ query_params = query_params.set("forceFunctionRegion", region.value)
85
+ if isinstance(body, str):
86
+ return TextRequest(
87
+ text=body,
88
+ method=method,
89
+ path=path,
90
+ headers=new_headers,
91
+ query=query_params,
92
+ )
93
+ elif isinstance(body, dict):
94
+ return JSONRequest(
95
+ body=body,
96
+ method=method,
97
+ path=path,
98
+ headers=new_headers,
99
+ query=query_params,
100
+ exclude_none=False,
101
+ )
102
+ elif isinstance(body, bytes):
103
+ return BytesRequest(
104
+ body=body,
105
+ method=method,
106
+ path=path,
107
+ headers=new_headers,
108
+ query=query_params,
109
+ )
110
+ else:
111
+ return EmptyRequest(
112
+ method=method, path=path, headers=new_headers, query=query_params
113
+ )
114
+
115
+ @handle_http_io
116
+ def invoke(
117
+ self,
118
+ function_name: str,
119
+ body: bytes | str | Dict[str, JSON] | None = None,
120
+ region: FunctionRegion | None = None,
121
+ headers: Dict[str, str] | None = None,
122
+ method: HTTPRequestMethod = "POST",
123
+ ) -> HttpMethod[Response]:
124
+ """Invokes a function
125
+
126
+ Parameters
127
+ ----------
128
+ function_name : the name of the function to invoke
129
+ invoke_options : object with the following properties
130
+ `headers`: object representing the headers to send with the request
131
+ `body`: the body of the request
132
+ `responseType`: how the response should be parsed. The default is `json`
133
+ """
134
+ response = yield self._invoke_options_to_request(
135
+ function_name, body, region, headers, method
136
+ )
137
+ if not response.is_success:
138
+ raise on_error_response(response)
139
+ return response
140
+
141
+
142
+ class AsyncFunctionsClient(FunctionsClient[AsyncHttpIO]):
143
+ def __init__(
144
+ self,
145
+ url: str,
146
+ headers: Dict[str, str],
147
+ http_client: AsyncClient | None = None,
148
+ ) -> None:
149
+ http_client = http_client or AsyncClient(
150
+ follow_redirects=True,
151
+ http2=True,
152
+ )
153
+ FunctionsClient.__init__(
154
+ self,
155
+ url=URL(url),
156
+ executor=AsyncHttpIO(session=AsyncHttpxSession(client=http_client)),
157
+ headers=headers,
158
+ )
159
+
160
+
161
+ class SyncFunctionsClient(FunctionsClient[SyncHttpIO]):
162
+ def __init__(
163
+ self,
164
+ url: str,
165
+ headers: Dict[str, str],
166
+ http_client: Client | None = None,
167
+ ) -> None:
168
+ http_client = http_client or Client(
169
+ follow_redirects=True,
170
+ http2=True,
171
+ )
172
+ FunctionsClient.__init__(
173
+ self,
174
+ url=URL(url),
175
+ executor=SyncHttpIO(session=HttpxSession(client=http_client)),
176
+ headers=headers,
177
+ )
178
+
179
+
180
+ @overload
181
+ def create_client(
182
+ url: str, headers: dict[str, str], *, is_async: Literal[True]
183
+ ) -> AsyncFunctionsClient: ...
184
+
185
+
186
+ @overload
187
+ def create_client(
188
+ url: str, headers: dict[str, str], *, is_async: Literal[False]
189
+ ) -> SyncFunctionsClient: ...
190
+
191
+
192
+ def create_client(
193
+ url: str, headers: dict[str, str], *, is_async: bool
194
+ ) -> AsyncFunctionsClient | SyncFunctionsClient:
195
+ if is_async:
196
+ return AsyncFunctionsClient(url, headers)
197
+ else:
198
+ return SyncFunctionsClient(url, headers)
@@ -1,9 +1,8 @@
1
1
  from __future__ import annotations
2
2
 
3
- from typing import TYPE_CHECKING, TypedDict
3
+ from typing import TypedDict
4
4
 
5
- if TYPE_CHECKING:
6
- from httpx import Response
5
+ from supabase_utils.http.request import Response
7
6
 
8
7
 
9
8
  class FunctionsApiErrorDict(TypedDict):
@@ -36,6 +35,15 @@ class FunctionsHttpError(FunctionsError):
36
35
  )
37
36
 
38
37
 
38
+ def on_error_response(response: Response) -> FunctionsHttpError | FunctionsRelayError:
39
+ is_relay_error = response.headers.get("x-relay-header")
40
+ if is_relay_error == "true":
41
+ return FunctionsRelayError(
42
+ response.content.decode("utf-8"), code=response.status
43
+ )
44
+ return FunctionsHttpError(response.content.decode("utf-8"), response.status)
45
+
46
+
39
47
  class FunctionsRelayError(FunctionsError):
40
48
  """Base exception for relay errors."""
41
49
 
@@ -45,18 +53,3 @@ class FunctionsRelayError(FunctionsError):
45
53
  "FunctionsRelayError",
46
54
  400 if code is None else code,
47
55
  )
48
-
49
-
50
- def _error_message_from(response: Response) -> str | None:
51
- """Best-effort extraction of an error message from an edge function response.
52
-
53
- An edge function may reply with a plain-text or empty body, so a failed JSON
54
- decode must not mask the underlying HTTP error.
55
- """
56
- try:
57
- body = response.json()
58
- except ValueError:
59
- return response.text or None
60
- if isinstance(body, dict):
61
- return body.get("error")
62
- return response.text or None
@@ -1,10 +1,14 @@
1
- from enum import StrEnum
2
- from urllib.parse import urlparse
1
+ import sys
2
+
3
+ from httpx import AsyncClient as AsyncClient # noqa: F401
4
+
5
+ if sys.version_info >= (3, 11):
6
+ from enum import StrEnum
7
+ else:
8
+ from strenum import StrEnum
3
9
 
4
- from httpx import AsyncClient as AsyncClient
5
10
 
6
11
  DEFAULT_FUNCTION_CLIENT_TIMEOUT = 5
7
- BASE64URL_REGEX = r"^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$"
8
12
 
9
13
 
10
14
  class FunctionRegion(StrEnum):
@@ -27,7 +31,3 @@ class FunctionRegion(StrEnum):
27
31
 
28
32
  def is_valid_str_arg(target: str) -> bool:
29
33
  return isinstance(target, str) and len(target.strip()) > 0
30
-
31
-
32
- def is_http_url(url: str) -> bool:
33
- return urlparse(url).scheme in {"https", "http"}
@@ -0,0 +1 @@
1
+ __version__ = "2.28.3" # {x-release-please-version}
@@ -1,47 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from typing import Literal, overload
4
-
5
- from ._async.functions_client import AsyncFunctionsClient
6
- from ._sync.functions_client import SyncFunctionsClient
7
- from .utils import FunctionRegion
8
-
9
- __all__ = [
10
- "create_client",
11
- "FunctionRegion",
12
- "AsyncFunctionsClient",
13
- "SyncFunctionsClient",
14
- ]
15
-
16
-
17
- @overload
18
- def create_client(
19
- url: str,
20
- headers: dict[str, str],
21
- *,
22
- is_async: Literal[True],
23
- verify: bool = ...,
24
- ) -> AsyncFunctionsClient: ...
25
-
26
-
27
- @overload
28
- def create_client(
29
- url: str,
30
- headers: dict[str, str],
31
- *,
32
- is_async: Literal[False],
33
- verify: bool = ...,
34
- ) -> SyncFunctionsClient: ...
35
-
36
-
37
- def create_client(
38
- url: str,
39
- headers: dict[str, str],
40
- *,
41
- is_async: bool,
42
- verify: bool = True,
43
- ) -> AsyncFunctionsClient | SyncFunctionsClient:
44
- if is_async:
45
- return AsyncFunctionsClient(url, headers, verify=verify)
46
- else:
47
- return SyncFunctionsClient(url, headers, verify=verify)
@@ -1 +0,0 @@
1
- from __future__ import annotations
@@ -1,218 +0,0 @@
1
- import platform
2
- from typing import Any, Literal
3
- from warnings import warn
4
-
5
- from httpx import URL as HttpxURL
6
- from httpx import AsyncClient, Headers, HTTPError, QueryParams, Request, Response
7
- from yarl import URL
8
-
9
- from ..errors import FunctionsHttpError, FunctionsRelayError, _error_message_from
10
- from ..utils import (
11
- FunctionRegion,
12
- is_http_url,
13
- is_valid_str_arg,
14
- )
15
- from ..version import __version__
16
-
17
- HTTPMethod = Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"]
18
-
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
-
56
- class AsyncFunctionsClient:
57
- def __init__(
58
- self,
59
- url: str,
60
- headers: dict,
61
- timeout: int | None = None,
62
- verify: bool | None = None,
63
- proxy: str | None = None,
64
- http_client: AsyncClient | None = None,
65
- ) -> None:
66
- if not is_http_url(url):
67
- raise ValueError("url must be a valid HTTP URL string")
68
- self.url = URL(url)
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)
81
-
82
- if timeout is not None:
83
- warn(
84
- "The 'timeout' parameter is deprecated. Please configure it in the http client instead.",
85
- DeprecationWarning,
86
- stacklevel=2,
87
- )
88
- if verify is not None:
89
- warn(
90
- "The 'verify' parameter is deprecated. Please configure it in the http client instead.",
91
- DeprecationWarning,
92
- stacklevel=2,
93
- )
94
- if proxy is not None:
95
- warn(
96
- "The 'proxy' parameter is deprecated. Please configure it in the http client instead.",
97
- DeprecationWarning,
98
- stacklevel=2,
99
- )
100
-
101
- self.verify = bool(verify) if verify is not None else True
102
- self.timeout = int(abs(timeout)) if timeout is not None else 60
103
- self._client = http_client or _RedirectGuardClient(
104
- verify=self.verify,
105
- timeout=self.timeout,
106
- proxy=proxy,
107
- follow_redirects=True,
108
- http2=True,
109
- )
110
-
111
- async def _request(
112
- self,
113
- method: HTTPMethod,
114
- path: list[str],
115
- headers: Headers,
116
- json: dict[Any, Any] | str | bytes | None = None,
117
- params: QueryParams | None = None,
118
- ) -> Response:
119
- url = self.url.joinpath(*path)
120
- response = (
121
- await self._client.request(
122
- method, str(url), content=json, headers=headers, params=params
123
- )
124
- if isinstance(json, (str, bytes))
125
- else await self._client.request(
126
- method, str(url), json=json, headers=headers, params=params
127
- )
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)
132
- try:
133
- response.raise_for_status()
134
- except HTTPError as exc:
135
- status_code = None
136
- if hasattr(response, "status_code"):
137
- status_code = response.status_code
138
-
139
- raise FunctionsHttpError(
140
- _error_message_from(response)
141
- or f"An error occurred while requesting your edge function at {exc.request.url!r}.",
142
- status_code,
143
- ) from exc
144
-
145
- return response
146
-
147
- def set_auth(self, token: str) -> None:
148
- """Updates the authorization header
149
-
150
- Parameters
151
- ----------
152
- token : str
153
- the new jwt token sent in the authorization header
154
- """
155
-
156
- self.headers["Authorization"] = f"Bearer {token}"
157
-
158
- async def invoke(
159
- self, function_name: str, invoke_options: dict | None = None
160
- ) -> dict | bytes:
161
- """Invokes a function
162
-
163
- Parameters
164
- ----------
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.
167
- invoke_options : object with the following properties
168
- `headers`: object representing the headers to send with the request
169
- `body`: the body of the request
170
- `method`: the HTTP method to invoke the function with. The default is `POST`
171
- `responseType`: how the response should be parsed. The default is `json`
172
- """
173
- if not is_valid_str_arg(function_name):
174
- raise ValueError("function_name must a valid string value.")
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)
182
- body = None
183
- method: HTTPMethod = "POST"
184
- response_type = "text/plain"
185
-
186
- if invoke_options is not None:
187
- headers.update(invoke_options.get("headers", {}))
188
- method = invoke_options.get("method", "POST")
189
- response_type = invoke_options.get("responseType", "text/plain")
190
-
191
- region = invoke_options.get("region")
192
- if region:
193
- if not isinstance(region, FunctionRegion):
194
- warn(f"Use FunctionRegion({region})", stacklevel=2)
195
- region = FunctionRegion(region)
196
-
197
- if region.value != "any":
198
- headers["x-region"] = region.value
199
- # Add region as query parameter
200
- params = params.set("forceFunctionRegion", region.value)
201
-
202
- body = invoke_options.get("body")
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"
210
-
211
- response = await self._request(
212
- method, [path], headers=headers, json=body, params=params
213
- )
214
- if response_type == "json":
215
- data = response.json()
216
- else:
217
- data = response.content
218
- return data
@@ -1 +0,0 @@
1
- from __future__ import annotations
@@ -1,218 +0,0 @@
1
- import platform
2
- from typing import Any, Literal
3
- from warnings import warn
4
-
5
- from httpx import URL as HttpxURL
6
- from httpx import Client, Headers, HTTPError, QueryParams, Request, Response
7
- from yarl import URL
8
-
9
- from ..errors import FunctionsHttpError, FunctionsRelayError, _error_message_from
10
- from ..utils import (
11
- FunctionRegion,
12
- is_http_url,
13
- is_valid_str_arg,
14
- )
15
- from ..version import __version__
16
-
17
- HTTPMethod = Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"]
18
-
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
-
56
- class SyncFunctionsClient:
57
- def __init__(
58
- self,
59
- url: str,
60
- headers: dict,
61
- timeout: int | None = None,
62
- verify: bool | None = None,
63
- proxy: str | None = None,
64
- http_client: Client | None = None,
65
- ) -> None:
66
- if not is_http_url(url):
67
- raise ValueError("url must be a valid HTTP URL string")
68
- self.url = URL(url)
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)
81
-
82
- if timeout is not None:
83
- warn(
84
- "The 'timeout' parameter is deprecated. Please configure it in the http client instead.",
85
- DeprecationWarning,
86
- stacklevel=2,
87
- )
88
- if verify is not None:
89
- warn(
90
- "The 'verify' parameter is deprecated. Please configure it in the http client instead.",
91
- DeprecationWarning,
92
- stacklevel=2,
93
- )
94
- if proxy is not None:
95
- warn(
96
- "The 'proxy' parameter is deprecated. Please configure it in the http client instead.",
97
- DeprecationWarning,
98
- stacklevel=2,
99
- )
100
-
101
- self.verify = bool(verify) if verify is not None else True
102
- self.timeout = int(abs(timeout)) if timeout is not None else 60
103
- self._client = http_client or _RedirectGuardClient(
104
- verify=self.verify,
105
- timeout=self.timeout,
106
- proxy=proxy,
107
- follow_redirects=True,
108
- http2=True,
109
- )
110
-
111
- def _request(
112
- self,
113
- method: HTTPMethod,
114
- path: list[str],
115
- headers: Headers,
116
- json: dict[Any, Any] | str | bytes | None = None,
117
- params: QueryParams | None = None,
118
- ) -> Response:
119
- url = self.url.joinpath(*path)
120
- response = (
121
- self._client.request(
122
- method, str(url), content=json, headers=headers, params=params
123
- )
124
- if isinstance(json, (str, bytes))
125
- else self._client.request(
126
- method, str(url), json=json, headers=headers, params=params
127
- )
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)
132
- try:
133
- response.raise_for_status()
134
- except HTTPError as exc:
135
- status_code = None
136
- if hasattr(response, "status_code"):
137
- status_code = response.status_code
138
-
139
- raise FunctionsHttpError(
140
- _error_message_from(response)
141
- or f"An error occurred while requesting your edge function at {exc.request.url!r}.",
142
- status_code,
143
- ) from exc
144
-
145
- return response
146
-
147
- def set_auth(self, token: str) -> None:
148
- """Updates the authorization header
149
-
150
- Parameters
151
- ----------
152
- token : str
153
- the new jwt token sent in the authorization header
154
- """
155
-
156
- self.headers["Authorization"] = f"Bearer {token}"
157
-
158
- def invoke(
159
- self, function_name: str, invoke_options: dict | None = None
160
- ) -> dict | bytes:
161
- """Invokes a function
162
-
163
- Parameters
164
- ----------
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.
167
- invoke_options : object with the following properties
168
- `headers`: object representing the headers to send with the request
169
- `body`: the body of the request
170
- `method`: the HTTP method to invoke the function with. The default is `POST`
171
- `responseType`: how the response should be parsed. The default is `json`
172
- """
173
- if not is_valid_str_arg(function_name):
174
- raise ValueError("function_name must a valid string value.")
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)
182
- body = None
183
- method: HTTPMethod = "POST"
184
- response_type = "text/plain"
185
-
186
- if invoke_options is not None:
187
- headers.update(invoke_options.get("headers", {}))
188
- method = invoke_options.get("method", "POST")
189
- response_type = invoke_options.get("responseType", "text/plain")
190
-
191
- region = invoke_options.get("region")
192
- if region:
193
- if not isinstance(region, FunctionRegion):
194
- warn(f"Use FunctionRegion({region})", stacklevel=2)
195
- region = FunctionRegion(region)
196
-
197
- if region.value != "any":
198
- headers["x-region"] = region.value
199
- # Add region as query parameter
200
- params = params.set("forceFunctionRegion", region.value)
201
-
202
- body = invoke_options.get("body")
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"
210
-
211
- response = self._request(
212
- method, [path], headers=headers, json=body, params=params
213
- )
214
- if response_type == "json":
215
- data = response.json()
216
- else:
217
- data = response.content
218
- return data
@@ -1 +0,0 @@
1
- __version__ = "2.34.0" # {x-release-please-version}