Package: lpipe
lpipelpipeprovides a simple set of tools for writing clearly defined, multi-function AWS Lambdas in Python.This project was born out of a desire to support directed-graph workflows on FAAS.lpipeis designed to handle batched events from CloudWatch, Kinesis, or SQS.FeaturesBatch message handlingError handling and capture - distinguish exceptions which should poison the queueValidate messages against function signaturesAutomatically handle partial failures in a batch of messages (SQS)Create directed graph workflows with a combination of one or more lambdas (optional)Getting StartedBasic Exampleimportlpipedeftest_func(foo:str,**kwargs):passdeflambda_handler(event,context):returnlpipe.process_event(event=event,context=context,call=test_func,queue_type=lpipe.QueueType.SQS,)This lambda could now be triggered by an SQS queue with the following message.{"foo":"bar",}Optionally, create a directed-graph workflowYou may also split your lambda into reusable chunks by defining paths.deflambda_handler(event,context):returnlpipe.process_event(event=event,context=context,paths={"EXAMPLE":[test_func]},queue_type=lpipe.QueueType.SQS,)Trigger with...{"path":"EXAMPLE","kwargs":{"foo":"bar",}}There are two tools which enable a directed workflow.Actions: A path may be defined as aList[Action]containing any functions, paths, or queuesPayloads: Your function may return aPayloadorList[Payload]which will be sequentially executed before continuingSee the linked sections in "Advanced" for more details.Message StructureThere are two message formats you will encounter.Basiclpipe will expect this structure if you call it via...process_event(call: FunctionType)process_event(paths: dict, default_path: Union[str, Enum]){"foo":"bar",}Directed Graphlpipe will expect this structure if you call it via...process_event(paths: dict){"path":"EXAMPLE","kwargs":{"foo":"bar",}}Batch ProcessingSQSWhen processing messages from an SQS queue, we will wait to raise any errors until all the messages in a batch are tried.Successful Records will be deleted from the invoking queueFailed records will raise an exception which ultimately triggers the SQS redrive policy.Everything else...If you're using any other invocation source, please consider setting your batch size to 1.Handling Errorslpiperelies on exceptions for flow control. Your code must raise exceptions that inherit from one of two classes.FailCatastrophicallyRaise this if you want your lambda to error out. This will result in poisoned records persisting on the queue if you're not careful. Only use it if you have CRITICAL data in the queueorif you hit an error state while setting up. This will trigger your redrive or DLQ policy.ExceptionDescriptionInvalidConfigurationError(FailCatastrophically)Raised automatically if your lambda is misconfigured.FailButContinueRaise this to log an exception and, optionally, send it to sentry, but continue processing more records.This will treat your record as poisoned and will drop it.ExceptionDescriptionInvalidPathError(FailButContinue)Raised automatically if you use a Path that was not defined.InvalidPayloadError(FailButContinue)Raised automatically if your lambda receives a message that is malformed or invalid.Everything else...Any errors that don't inherit from one of the two classes above will be logged and captured at sentry (if initialized.) Your record will then be dropped to prevent a poisoned queue.AdvancedPathsA path is defined by an enumerated name and a list of actions or functions.ExamplefromenumimportEnumfromlpipeimportActionclassPath(Enum):DO_THING=1PATHS={Path.DO_THING:[Action(required_params=[],functions=[],paths=[]),Action(required_params=[],functions=[],paths=[]),],}lpipecan also generate the enumeration for you automatically...PATHS={"DO_THING":[Action(required_params=[],functions=[],paths=[]),Action(required_params=[],functions=[],paths=[]),],}A list of functions is also an acceptable path definition.PATHS={"DO_THING":[my_function,my_second_function],}Actionslpipe.Action(required_params,functions,paths)ArgumentTypeDescriptionrequired_paramslist(optional if functions is set, required if ONLY paths is set) A list of kwarg keys to expect.functionslist(optional if paths is set) A list of functions to run with the provided kwargs.pathslist(optional if functions is set) A list of path names (to be run in the current lambda instance) or Queues to push messages to.include_all_paramsboolIf true, pass all kwargs to every function/path in this Action.ExamplefromlpipeimportActionAction(required_params=["name","email"],functions=[subscribe_to_pewdiepie],paths=[SEND_MERCH])Using this action would first callsubscribe_to_pewdiepie(name, email)then try to run theSEND_MERCHpath.required_paramsis optionalif you define type hints on your function.defsubscribe_to_pewdiepie(name:str,email:str,**kwargs):passAction(functions=[subscribe_to_pewdiepie],paths=[SEND_MERCH])Defining ParametersParameters can be inferred from your function signatures or explicitly set. If you allow parameters to be inferred, default values are permitted, and type hints will be enforced.Exampledeftest_func(foo:str,bar:int=42,**kwargs):passPath.MY_PATH:[Action(functions=[my_func],# IMPLICIT)],ORdeftest_func(foo,bar,**kwargs):passPath.MY_PATH:[Action(required_params=["foo","bar"],# EXPLICITfunctions=[my_func],)],Queueslpipe.Queue(type,name,path)ArgumentTypeDescriptiontypelpipe.QueueTypenamestrName/identifier of the queue (used byQueueType.Kinesis,QueueType.SQS) If you include name instead of url for an SQS queue, the queue URL will fetched automatically.urlstrURL/URI of the queue (used byQueueType.SQS)pathstr(optional) A path name, usually to trigger a path in the lambda feeding off of this queue. If this is set, the sent message will be in the standard lpipe format of{"path": "", "kwargs": {}}.ExamplefromlpipeimportQueue,QueueTypeQueue(type=QueueType.SQS,name="my-queue-name")PayloadsIf you returnPayloadorList[Payload]from a function called by lpipe, the payloads will be sequentially executed before proceeding with other messages. Keep time restrictions in mind when using this feature.lpipe.Payload(kwargs,path,queue,event_source)ArgumentTypeDescriptionkwargsdictpathEnumorstrOptional ifqueueis setqueuelpipe.QueueOptional ifpathis setevent_sourcestr(optional) Set automatically on Payloads generated by lpipeExamplefromlpipeimportPayloadPayload(kwargs={"lorem":"ipsum"},path="MY_PATH",)Advanced ExampleCombining all of the features documented above will allow you to chain messages through a directed graph of local code and remote services.This example demonstrates a lambda with two functions. Both can be triggered directly by a message, but one will trigger the other.importlpipedefmy_func(foo:str,**kwargs):passdefmy_generic_func(foo:str,**kwargs):# pseudo codedata=request.get(os.environ["MY_API_URL"],{"foo":foo})# queue up message with another servicereturnlpipe.Payload(kwargs=data,queue=lpipe.Queue(type=lpipe.QueueType.SQS,name="my-service-queue",),)PATHS={"FIRST_PATH":[Action(functions=[my_func],paths=["GENERIC_REUSABLE_PATH"]),],"GENERIC_REUSABLE_PATH":[my_generic_func],}deflambda_handler(event,context):returnlpipe.process_event(event=event,context=context,paths=PATHS,queue_type=lpipe.QueueType.SQS,)Trigger with...{"path":"FIRST_PATH","kwargs":{"foo":"bar",}}