FAQ | This is a LIVE service | Changelog

Skip to content

Add documentation about cloud event and helpers to parse it

Description

When using @ucam_faas.cloud_event, the message the function receives is:

{
  "message": {
    "attributes": {},
    "data": "...",
  }
}

With data being the base64 encoded data.

This is nowhere documented, and most of the time very confusing for users using this library for the first time. Especially because this library also exposes the ucam_faas.CloudEvent, which is not what the cloud_event is what we get in GCP (or from the emulator).

This task is to document what the cloud_event is, and to add helpers to not having to repeat code to properly parse these messages. Or at least type the cloud_event correctly, so that any type checkers know what to expect.

Further details

There are a couple of application that process/decode the message using pydantic:

class CloudEventData(BaseModel):
    pass


class CloudEventAttributes(BaseModel):
    source: str


class CloudEventMessage(BaseModel):
    attributes: CloudEventAttributes
    data: CloudEventData

    @field_serializer("data")
    def serialize_data(self, value, *args, **kwargs):
        return base64.b64encode(value.model_dump_json().encode("utf-8"))

    @field_validator("data", mode="before")
    def validate_data(cls, value):
        if isinstance(value, str):
            value = value.encode("utf-8")

        if isinstance(value, bytes):
            return json.loads(base64.b64decode(value))

        return value


class CloudEvent(BaseModel):
    message: CloudEventMessage

We could think of moving part of this logic into ucam-faas directly.

Task list

  • Move any shared cloud event code from the function code into the ucam_faas library.
  • Investigate possiblity of using the google cloudevent library, providing helper functions in the ucam_faas library that replicate the functionality currently repeated in the function code.
  • Update ucam_faas README to explain how to handle cloud events.
  • Shared code should be data-payload agnostic!

Acceptance criteria

  • Code handling cloud events in account-selector and account-data-manager repositories is removed, replaced with ucam_faas helper functions or functionality.

Links/references

Edited by Mike Knee