diff --git a/google/cloud/pubsublite/types/location.py b/google/cloud/pubsublite/types/location.py index 0ad7ae98..83a43432 100644 --- a/google/cloud/pubsublite/types/location.py +++ b/google/cloud/pubsublite/types/location.py @@ -30,6 +30,10 @@ def parse(to_parse: str): raise InvalidArgument("Invalid region name: " + to_parse) return CloudRegion(name=splits[0] + "-" + splits[1]) + @property + def region(self): + return self + class CloudZone(NamedTuple): region: CloudRegion diff --git a/google/cloud/pubsublite/types/paths.py b/google/cloud/pubsublite/types/paths.py index eaa52fdf..9adf5ccc 100644 --- a/google/cloud/pubsublite/types/paths.py +++ b/google/cloud/pubsublite/types/paths.py @@ -19,6 +19,18 @@ from google.cloud.pubsublite.types.location import CloudZone, CloudRegion +def _parse_location(to_parse: str) -> Union[CloudRegion, CloudZone]: + try: + return CloudZone.parse(to_parse) + except InvalidArgument: + pass + try: + return CloudRegion.parse(to_parse) + except InvalidArgument: + pass + raise InvalidArgument("Invalid location name: " + to_parse) + + class LocationPath(NamedTuple): project: Union[int, str] location: Union[CloudRegion, CloudZone] @@ -26,10 +38,20 @@ class LocationPath(NamedTuple): def __str__(self): return f"projects/{self.project}/locations/{self.location}" + @staticmethod + def parse(to_parse: str) -> "LocationPath": + splits = to_parse.split("/") + if len(splits) != 6 or splits[0] != "projects" or splits[2] != "locations": + raise InvalidArgument( + "Location path must be formatted like projects/{project_number}/locations/{location} but was instead " + + to_parse + ) + return LocationPath(splits[1], _parse_location(splits[3])) + class TopicPath(NamedTuple): project: Union[int, str] - location: CloudZone + location: Union[CloudRegion, CloudZone] name: str def __str__(self): @@ -51,12 +73,12 @@ def parse(to_parse: str) -> "TopicPath": "Topic path must be formatted like projects/{project_number}/locations/{location}/topics/{name} but was instead " + to_parse ) - return TopicPath(splits[1], CloudZone.parse(splits[3]), splits[5]) + return TopicPath(splits[1], _parse_location(splits[3]), splits[5]) class SubscriptionPath(NamedTuple): project: Union[int, str] - location: CloudZone + location: Union[CloudRegion, CloudZone] name: str def __str__(self): @@ -78,7 +100,7 @@ def parse(to_parse: str) -> "SubscriptionPath": "Subscription path must be formatted like projects/{project_number}/locations/{location}/subscriptions/{name} but was instead " + to_parse ) - return SubscriptionPath(splits[1], CloudZone.parse(splits[3]), splits[5]) + return SubscriptionPath(splits[1], _parse_location(splits[3]), splits[5]) class ReservationPath(NamedTuple):