1- """Integration of Dispatch programmable endpoints for FastAPI.
1+ """Integration of Dispatch functions with FastAPI.
22
33Example:
44
@@ -18,7 +18,6 @@ def read_root():
1818 """
1919
2020import asyncio
21- import base64
2221import logging
2322import os
2423from datetime import timedelta
@@ -36,8 +35,7 @@ def read_root():
3635 CaseInsensitiveDict ,
3736 Ed25519PublicKey ,
3837 Request ,
39- public_key_from_bytes ,
40- public_key_from_pem ,
38+ parse_verification_key ,
4139 verify_request ,
4240)
4341from dispatch .status import Status
@@ -46,9 +44,7 @@ def read_root():
4644
4745
4846class Dispatch (Registry ):
49- """A Dispatch programmable endpoint, powered by FastAPI."""
50-
51- __slots__ = ("client" ,)
47+ """A Dispatch instance, powered by FastAPI."""
5248
5349 def __init__ (
5450 self ,
@@ -65,9 +61,9 @@ def __init__(
6561 Args:
6662 app: The FastAPI app to configure.
6763
68- endpoint: Full URL of the application the Dispatch programmable
69- endpoint will be running on. Uses the value of the
70- DISPATCH_ENDPOINT_URL environment variable by default.
64+ endpoint: Full URL of the application the Dispatch instance will
65+ be running on. Uses the value of the DISPATCH_ENDPOINT_URL
66+ environment variable by default.
7167
7268 verification_key: Key to use when verifying signed requests. Uses
7369 the value of the DISPATCH_VERIFICATION_KEY environment variable
@@ -108,55 +104,13 @@ def __init__(
108104 f"{ endpoint_from } must be a full URL with protocol and domain (e.g., https://example.com)"
109105 )
110106
111- verification_key = parse_verification_key (verification_key )
112- if verification_key :
113- base64_key = base64 .b64encode (verification_key .public_bytes_raw ()).decode ()
114- logger .info ("verifying request signatures using key %s" , base64_key )
115- elif parsed_url .scheme != "bridge" :
116- logger .warning (
117- "request verification is disabled because DISPATCH_VERIFICATION_KEY is not set"
118- )
119-
120107 super ().__init__ (endpoint , api_key = api_key , api_url = api_url )
121108
109+ verification_key = parse_verification_key (verification_key , url_scheme = parsed_url .scheme )
122110 function_service = _new_app (self , verification_key )
123111 app .mount ("/dispatch.sdk.v1.FunctionService" , function_service )
124112
125113
126- def parse_verification_key (
127- verification_key : Optional [Union [Ed25519PublicKey , str , bytes ]],
128- ) -> Optional [Ed25519PublicKey ]:
129- if isinstance (verification_key , Ed25519PublicKey ):
130- return verification_key
131-
132- from_env = False
133- if not verification_key :
134- try :
135- verification_key = os .environ ["DISPATCH_VERIFICATION_KEY" ]
136- except KeyError :
137- return None
138- from_env = True
139-
140- if isinstance (verification_key , bytes ):
141- verification_key = verification_key .decode ()
142-
143- # Be forgiving when accepting keys in PEM format, which may span
144- # multiple lines. Users attempting to pass a PEM key via an environment
145- # variable may accidentally include literal "\n" bytes rather than a
146- # newline char (0xA).
147- try :
148- return public_key_from_pem (verification_key .replace ("\\ n" , "\n " ))
149- except ValueError :
150- pass
151-
152- try :
153- return public_key_from_bytes (base64 .b64decode (verification_key .encode ()))
154- except ValueError :
155- if from_env :
156- raise ValueError (f"invalid DISPATCH_VERIFICATION_KEY '{ verification_key } '" )
157- raise ValueError (f"invalid verification key '{ verification_key } '" )
158-
159-
160114class _ConnectResponse (fastapi .Response ):
161115 media_type = "application/grpc+proto"
162116
0 commit comments