Skip to content

Commit 0860f61

Browse files
committed
feat: pubsub triggers
1 parent a66fbe1 commit 0860f61

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

src/firebase_functions/pubsub.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
"""
2+
Cloud functions to handle events from Google Cloud Pub/Sub.
3+
"""
4+
5+
import dataclasses as _dataclasses
6+
import functools as _functools
7+
import typing as _typing
8+
import json as _json
9+
import base64 as _base64
10+
11+
import firebase_functions.options as _options
12+
import firebase_functions.private.util as _util
13+
from firebase_functions.core import CloudEvent, T
14+
15+
16+
@_dataclasses.dataclass(frozen=True)
17+
class Message(_typing.Generic[T]):
18+
"""
19+
Interface representing a Google Cloud Pub/Sub message.
20+
"""
21+
22+
message_id: str
23+
"""
24+
Autogenerated ID that uniquely identifies this message.
25+
"""
26+
27+
publish_time: str
28+
"""
29+
Time the message was published.
30+
"""
31+
32+
attributes: dict[str, str]
33+
"""
34+
User-defined attributes published with the message, if any.
35+
"""
36+
37+
data: str
38+
"""
39+
The data payload of this message object as a base64-encoded string.
40+
"""
41+
42+
ordering_key: str
43+
"""
44+
User-defined key used to ensure ordering amongst messages with the same key.
45+
"""
46+
47+
@property
48+
def json(self) -> _typing.Optional[_core.T]:
49+
try:
50+
if self.data is not None:
51+
return _json.loads(_base64.b64decode(self.data).decode("utf-8"))
52+
else:
53+
return None
54+
except Exception as error:
55+
raise Exception(
56+
f"Unable to parse Pub/Sub message data as JSON: {error}"
57+
) from error
58+
59+
60+
@_dataclasses.dataclass(frozen=True)
61+
class MessagePublishedData(_typing.Generic[_core.T]):
62+
"""
63+
The interface published in a Pub/Sub publish subscription.
64+
65+
'T' Type representing `Message.data`'s JSON format.
66+
"""
67+
message: Message[_core.T]
68+
"""
69+
Google Cloud Pub/Sub message.
70+
"""
71+
72+
subscription: str
73+
"""
74+
A subscription resource.
75+
"""
76+
77+
78+
_E1 = DatabaseEvent[Change[_typing.Any | None]]
79+
_E2 = DatabaseEvent[_typing.Any | None]
80+
_C1 = _typing.Callable[[_E1], None]
81+
_C2 = _typing.Callable[[_E2], None]

0 commit comments

Comments
 (0)