|
| 1 | +"""Helpers for Google Cloud connector steps.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from collections.abc import Mapping |
| 6 | +from datetime import timedelta |
| 7 | +from typing import Any, TypeVar |
| 8 | + |
| 9 | +from pydantic import BaseModel |
| 10 | + |
| 11 | +from fastapi_cloudflow.core.arg import Arg, ArgExpr |
| 12 | +from fastapi_cloudflow.core.step import ConnectorStep |
| 13 | +from fastapi_cloudflow.core.types import ConnectorCall, RetryPolicy |
| 14 | + |
| 15 | +InT = TypeVar("InT", bound=BaseModel) |
| 16 | +OutT = TypeVar("OutT", bound=BaseModel) |
| 17 | + |
| 18 | + |
| 19 | +_PUBSUB_TOPIC_PREFIX = "projects/" |
| 20 | + |
| 21 | + |
| 22 | +def _validate_topic_path(topic: str) -> None: |
| 23 | + if not topic.startswith(_PUBSUB_TOPIC_PREFIX): |
| 24 | + raise ValueError("Pub/Sub topic must be fully qualified: 'projects/<project>/topics/<topic_id>'") |
| 25 | + parts = topic.split("/") |
| 26 | + if len(parts) != 4: |
| 27 | + raise ValueError("Pub/Sub topic must follow 'projects/<project>/topics/<topic_id>' format") |
| 28 | + _, project, resource, topic_id = parts |
| 29 | + if not project or resource != "topics" or not topic_id: |
| 30 | + raise ValueError("Pub/Sub topic must include non-empty project and topic id") |
| 31 | + |
| 32 | + |
| 33 | +def pubsub_message( |
| 34 | + *, |
| 35 | + data: str | ArgExpr, |
| 36 | + attributes: Mapping[str, str | ArgExpr] | ArgExpr | None = None, |
| 37 | + ordering_key: str | ArgExpr | None = None, |
| 38 | +) -> dict[str, Any]: |
| 39 | + """Build a Pub/Sub message payload for the publish API.""" |
| 40 | + |
| 41 | + message: dict[str, Any] = {"data": Arg.base64(data)} |
| 42 | + |
| 43 | + if attributes is not None: |
| 44 | + if isinstance(attributes, ArgExpr): |
| 45 | + message["attributes"] = attributes |
| 46 | + else: |
| 47 | + message["attributes"] = attributes.copy() |
| 48 | + |
| 49 | + if ordering_key is not None: |
| 50 | + message["orderingKey"] = ordering_key |
| 51 | + |
| 52 | + return message |
| 53 | + |
| 54 | + |
| 55 | +def pubsub_publish( |
| 56 | + *, |
| 57 | + topic: str | ArgExpr, |
| 58 | + data: str | ArgExpr | None = None, |
| 59 | + attributes: Mapping[str, str | ArgExpr] | ArgExpr | None = None, |
| 60 | + ordering_key: str | ArgExpr | None = None, |
| 61 | + messages: list[dict[str, Any]] | None = None, |
| 62 | +) -> ConnectorCall: |
| 63 | + """Create a ConnectorCall for the Pub/Sub publish API.""" |
| 64 | + |
| 65 | + if isinstance(topic, str): |
| 66 | + _validate_topic_path(topic) |
| 67 | + |
| 68 | + if messages is None: |
| 69 | + if data is None: |
| 70 | + raise ValueError("Provide either `data` or `messages` when publishing to Pub/Sub") |
| 71 | + messages = [pubsub_message(data=data, attributes=attributes, ordering_key=ordering_key)] |
| 72 | + |
| 73 | + request: dict[str, Any] = { |
| 74 | + "topic": topic, |
| 75 | + "messages": messages, |
| 76 | + } |
| 77 | + |
| 78 | + args: dict[str, Any] = { |
| 79 | + "connector": "googleapis.pubsub.v1", |
| 80 | + "operation": "projects.topics.publish", |
| 81 | + "request": request, |
| 82 | + } |
| 83 | + |
| 84 | + return ConnectorCall(call="connectors.googleapis.pubsub.v1.projects.topics.publish", args=args) |
| 85 | + |
| 86 | + |
| 87 | +class PubSubPublishResult(BaseModel): |
| 88 | + message_ids: list[str] |
| 89 | + |
| 90 | + |
| 91 | +def pubsub_publish_step( |
| 92 | + *, |
| 93 | + name: str, |
| 94 | + topic: str, |
| 95 | + input_model: type[InT], |
| 96 | + output_model: type[OutT] | None = None, |
| 97 | + data: str | ArgExpr | None = None, |
| 98 | + data_field: str | None = "payload", |
| 99 | + attributes: Mapping[str, str | ArgExpr] | ArgExpr | None = None, |
| 100 | + attributes_field: str | None = None, |
| 101 | + ordering_key: str | ArgExpr | None = None, |
| 102 | + ordering_key_field: str | None = None, |
| 103 | + retry: RetryPolicy | None = None, |
| 104 | + timeout: timedelta | None = None, |
| 105 | +) -> ConnectorStep[InT, OutT]: |
| 106 | + """High-level helper that returns a ConnectorStep publishing to Pub/Sub.""" |
| 107 | + |
| 108 | + if isinstance(topic, str): |
| 109 | + _validate_topic_path(topic) |
| 110 | + |
| 111 | + data_expr: str | ArgExpr | None = data |
| 112 | + if data_expr is None: |
| 113 | + if not data_field: |
| 114 | + raise ValueError("Provide either `data` or `data_field` for pubsub_publish_step") |
| 115 | + data_expr = Arg.param(data_field) |
| 116 | + |
| 117 | + attributes_expr = attributes |
| 118 | + if attributes_expr is None and attributes_field is not None: |
| 119 | + attributes_expr = Arg.param(attributes_field) |
| 120 | + |
| 121 | + ordering_expr = ordering_key |
| 122 | + if ordering_expr is None and ordering_key_field is not None: |
| 123 | + ordering_expr = Arg.param(ordering_key_field) |
| 124 | + |
| 125 | + call = pubsub_publish( |
| 126 | + topic=topic, |
| 127 | + data=data_expr, |
| 128 | + attributes=attributes_expr, |
| 129 | + ordering_key=ordering_expr, |
| 130 | + ) |
| 131 | + |
| 132 | + result_model = output_model or PubSubPublishResult # type: ignore[assignment] |
| 133 | + |
| 134 | + return ConnectorStep( |
| 135 | + name=name, |
| 136 | + input_model=input_model, |
| 137 | + output_model=result_model, |
| 138 | + call=call, |
| 139 | + retry=retry, |
| 140 | + timeout=timeout, |
| 141 | + ) |
| 142 | + |
| 143 | + |
| 144 | +__all__ = ["pubsub_publish", "pubsub_message", "pubsub_publish_step", "PubSubPublishResult"] |
0 commit comments