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:
- https://gitlab.developers.cam.ac.uk/uis/devops/iam/activate-account/account-data-manager/-/blob/main/account_data_manager/main.py?ref_type=heads#L104
- https://gitlab.developers.cam.ac.uk/uis/devops/iam/activate-account/account-selector/-/blob/main/account_selector/main.py?ref_type=heads#L228
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_faaslibrary. - Investigate possiblity of using the google
cloudeventlibrary, providing helper functions in theucam_faaslibrary that replicate the functionality currently repeated in the function code. - Update
ucam_faasREADME to explain how to handle cloud events. - Shared code should be data-payload agnostic!
Acceptance criteria
-
Code handling cloud events in account-selectorandaccount-data-managerrepositories is removed, replaced withucam_faashelper functions or functionality.