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