|
| 1 | +"""Integration of Dispatch programmable endpoints for FastAPI. |
| 2 | +
|
| 3 | +Example: |
| 4 | +
|
| 5 | + from dispatch.experimental.lambda_handler import Dispatch |
| 6 | +
|
| 7 | + dispatch = Dispatch(api_key="test-key") |
| 8 | +
|
| 9 | + @dispatch.function |
| 10 | + def my_function(): |
| 11 | + return "Hello World!" |
| 12 | +
|
| 13 | + @dispatch.entrypoint |
| 14 | + def entrypoint(): |
| 15 | + my_function() |
| 16 | +
|
| 17 | + def handler(event, context): |
| 18 | + dispatch.handle(event, context) |
| 19 | + """ |
| 20 | + |
| 21 | +import base64 |
| 22 | +import logging |
| 23 | +import json |
| 24 | + |
| 25 | +from dispatch.function import Registry |
| 26 | +from dispatch.proto import Input |
| 27 | +from dispatch.sdk.v1 import function_pb2 as function_pb |
| 28 | +from dispatch.status import Status |
| 29 | + |
| 30 | +logger = logging.getLogger(__name__) |
| 31 | + |
| 32 | + |
| 33 | +class Dispatch(Registry): |
| 34 | + def __init__( |
| 35 | + self, |
| 36 | + api_key: str | None = None, |
| 37 | + api_url: str | None = None, |
| 38 | + ): |
| 39 | + """Initializes a Dispatch Lambda handler. |
| 40 | +
|
| 41 | + Args: |
| 42 | + api_key: Dispatch API key to use for authentication. Uses the value of |
| 43 | + the DISPATCH_API_KEY environment variable by default. |
| 44 | +
|
| 45 | + api_url: The URL of the Dispatch API to use. Uses the value of the |
| 46 | + DISPATCH_API_URL environment variable if set, otherwise |
| 47 | + defaults to the public Dispatch API (DEFAULT_API_URL). |
| 48 | +
|
| 49 | + """ |
| 50 | + |
| 51 | + # The endpoint (AWS Lambda ARN) is set when handling the first request. |
| 52 | + super().__init__(endpoint=None, api_key=api_key, api_url=api_url) |
| 53 | + |
| 54 | + def handle(self, event, context): |
| 55 | + # Use the context to determine the ARN of the Lambda function. |
| 56 | + self.endpoint = context.invoked_function_arn |
| 57 | + |
| 58 | + logger.debug("Dispatch handler invoked for %s with event: %s", self.endpoint, event) |
| 59 | + |
| 60 | + if not event: |
| 61 | + raise ValueError("event is required") |
| 62 | + |
| 63 | + try: |
| 64 | + raw = base64.b64decode(event) |
| 65 | + except Exception as e: |
| 66 | + raise ValueError(f"event is not base64 encoded: {e}") |
| 67 | + |
| 68 | + req = function_pb.RunRequest.FromString(raw) |
| 69 | + print(req) |
| 70 | + if not req.function: |
| 71 | + req.function = "entrypoint" |
| 72 | + # FIXME raise ValueError("function is required") |
| 73 | + |
| 74 | + try: |
| 75 | + func = self.functions[req.function] |
| 76 | + except KeyError: |
| 77 | + raise ValueError(f"function {req.function} not found") |
| 78 | + |
| 79 | + input = Input(req) |
| 80 | + try: |
| 81 | + output = func._primitive_call(input) |
| 82 | + except Exception: |
| 83 | + logger.error("function '%s' fatal error", req.function, exc_info=True) |
| 84 | + raise # FIXME |
| 85 | + else: |
| 86 | + response = output._message |
| 87 | + status = Status(response.status) |
| 88 | + |
| 89 | + if response.HasField("poll"): |
| 90 | + logger.debug( |
| 91 | + "function '%s' polling with %d call(s)", |
| 92 | + req.function, |
| 93 | + len(response.poll.calls), |
| 94 | + ) |
| 95 | + elif response.HasField("exit"): |
| 96 | + exit = response.exit |
| 97 | + if not exit.HasField("result"): |
| 98 | + logger.debug("function '%s' exiting with no result", req.function) |
| 99 | + else: |
| 100 | + result = exit.result |
| 101 | + if result.HasField("output"): |
| 102 | + logger.debug( |
| 103 | + "function '%s' exiting with output value", req.function |
| 104 | + ) |
| 105 | + elif result.HasField("error"): |
| 106 | + err = result.error |
| 107 | + logger.debug( |
| 108 | + "function '%s' exiting with error: %s (%s)", |
| 109 | + req.function, |
| 110 | + err.message, |
| 111 | + err.type, |
| 112 | + ) |
| 113 | + if exit.HasField("tail_call"): |
| 114 | + logger.debug( |
| 115 | + "function '%s' tail calling function '%s'", |
| 116 | + exit.tail_call.function, |
| 117 | + ) |
| 118 | + |
| 119 | + logger.debug("finished handling run request with status %s", status.name) |
| 120 | + resp = response.SerializeToString() |
| 121 | + resp = base64.b64encode(resp).decode("utf-8") |
| 122 | + return bytes(json.dumps(resp), "utf-8") |
0 commit comments