
    5R                     d   d Z ddlmZ ddlmZ ddlmZ ddlmZ ddlZddlmZ ddl	m
Z
 dd	lmZ dd
lmZ ddlmZ ddlmZ ddlZddlmZ dZdZdZdZdZdZdZ G d dej6                        Z G d dej6                        Z G d dej6                        Z G d dej6                        Z G d dej6                        Z d Z!d  Z"d! Z#d" Z$d# Z%d$ Z&d% Z'd& Z(d' Z)d( Z*d) Z+d* Z,d+ Z-d, Z.d- Z/d. Z0d/ Z1d0 Z2d1 Z3d2 Z4d3 Z5d4 Z6d5 Z7d6 Z8d7 Z9d8 Z:d9 Z;d: Z<d; Z=d< Z>d= Z?d> Z@d? ZAd@ ZBdA ZCdCdBZDy)Dz>A library that is used to support Cloud Pub/Sub Lite commands.    )absolute_import)division)print_function)unicode_literalsN)apis)util)
exceptions)log)
properties)
console_io)urlparsez	projects/z
locations/zreservations/ztopics/zsubscriptions/
pubsublitev1c                       e Zd ZdZy)UnexpectedResourceFieldz,Error for having and unknown resource field.N__name__
__module____qualname____doc__     2lib/googlecloudsdk/command_lib/pubsub/lite_util.pyr   r   +       4r   r   c                       e Zd ZdZy)InvalidPythonVersionz$Error for an invalid python version.Nr   r   r   r   r   r   /   s    ,r   r   c                   "     e Zd ZdZ fdZ xZS )NoGrpcInstalledz8Error that occurs when the grpc module is not installed.c                 ,    t         t        |   d       y )NzPlease ensure that the gRPC module is installed and the environment is correctly configured. Run `sudo pip3 install grpcio` and set the environment variable CLOUDSDK_PYTHON_SITEPACKAGES=1.)superr   __init__)self	__class__s    r   r!   zNoGrpcInstalled.__init__6   s    	/4)	?@r   )r   r   r   r   r!   __classcell__)r#   s   @r   r   r   3   s    @@ @r   r   c                       e Zd ZdZy)InvalidSeekTargetz,Error for specifying an invalid seek target.Nr   r   r   r   r&   r&   =   r   r   r&   c                       e Zd ZdZy)InvalidResourcePathz>Error for specifying an invalid fully qualified resource path.Nr   r   r   r   r(   r(   A   s    Fr   r(   c                  >    t        j                  t        t              S )z*Returns the Pub/Sub Lite v1 client module.)r   GetClientInstancePUBSUBLITE_API_NAMEPUBSUBLITE_API_VERSIONr   r   r   PubsubLiteClientr-   E       			 35K	LLr   c                  >    t        j                  t        t              S )z,Returns the Pub/Sub Lite v1 messages module.)r   GetMessagesModuler+   r,   r   r   r   PubsubLiteMessagesr1   J   r.   r   c                 X    t        j                  t        | j                              dz   S )zCConvert Duration object to total seconds for backend compatibility.s)six	text_typeinttotal_seconds)durations    r   DurationToSecondsr9   O   s!    	s8112	3c	99r   c                 L    | j                  d      }dj                  |dd       S )a  Returns the region from a location string.

  Args:
    location: A str of the form `<region>-<zone>` or `<region>`, such as
      `us-central1-a` or `us-central1`. Any other form will cause undefined
      behavior.

  Returns:
    The str region. Example: `us-central1`.
  -N   )splitjoin)locationsplitss     r   DeriveRegionFromLocationrA   T   s'     >>#&	&!*	r   c                     t        |       }|j                  j                  d      }t        |      dkD  r|d   dz   |d   z   S y)aD  Returns the region from a endpoint string.

  Args:
    endpoint: A str of the form `https://<region-><environment->base.url.com/`.
      Example `https://us-central-base.url.com/`,
      `https://us-central-autopush-base.url.com/`, or `https://base.url.com/`.

  Returns:
    The str region if it exists, otherwise None.
  r;   r<   r      N)r   netlocr=   len)endpointparseddash_splitss      r   DeriveRegionFromEndpointrI   c   sJ     H&##C(+q>C+a.00r   c                 P    |j                  d      }|d   }|dz   | z   dz   |d   z   S )zTReturns a new endpoint string with the defined `region` prefixed to the netlocation.z://r   r;   rC   )r=   )regionurl	url_parts
url_schemes       r   CreateRegionalEndpointrO   v   s7    ii)|*	e	f	$s	*Yq\	99r   c                 J    t        |       }|r| j                  |dz   d      } | S )zCReturns a new endpoint string stripped of the region if one exists.r;    )rI   replace)rF   rK   s     r   RemoveRegionFromEndpointrS   }   s*    #H-&b1H	/r   c                     d}d}t        | d      r| j                  }d}||fS t        | d      r| j                  }d}||fS t        | d      r| j                  }d}||fS t	        d      )a  Returns a tuple of the resource and resource name from the `request`.

  Args:
    request: A Request object instance.

  Returns:
    A tuple of the resource string path and the resource name.

  Raises:
    UnexpectedResourceField: The `request` had a unsupported resource.
  rQ   parentnamesubscriptionz3The resource specified for this command is unknown!)hasattrrU   rV   rW   r   )requestresourceresource_names      r   GetResourceInfor\      s     (-Wh~~HM 
=	   w||HM 
=	   w'##H"M
 
=	   "=? ?r   c                     ddl m} t        | j                  d            dk(  r|j                  j                  |       S |j                  j                  |       S )Nr   )typesr;      )google.cloud.pubsubliter^   rE   r=   	CloudZoneparseCloudRegion)location_idr^   s     r   LocationToZoneOrRegionre      sI    +		3	 A%??  --"";//r   c                 ~    | | j                  t              t        t              z   d }|j                  d      d   }|S )z,Returns the location from a resource string.N/r   )indexLOCATIONS_RESOURCE_PATHrE   r=   )rZ   r?   s     r   DeriveLocationFromResourcerj      sC    hnn%<=123 4 5(^^C #(	/r   c                 ~    | | j                  t              t        t              z   d }|j                  d      d   }|S )z+Returns the project from a resource string.Nrg   r   )rh   PROJECTS_RESOURCE_PATHrE   r=   )rZ   projects     r   DeriveProjectFromResourcern      sC    X^^$:;/01 2 3'MM#q!'	.r   c                 l    t        |       \  }}||j                  t              d }t        | ||       | S )z;Returns an updated `request` with the resource path parsed.N)r\   rindexrl   setattr)rY   rZ   r[   new_resources       r   ParseResourcers      s9    +G4(M(//*@ABC,	'=,/	.r   c                    t        |       \  }}t        t        |            }t        j                  t
        t              }t        |      }t        ||      }t        j                  j                  j                  j                  |       y)z<Sets the pubsublite endpoint override to include the region.N)r\   rA   rj   r   GetEffectiveApiEndpointr+   r,   rS   rO   r   VALUESapi_endpoint_overridesr   Set)rY   rZ   _rK   rF   regional_endpoints         r   OverrideEndpointWithRegionr{      sq    (+(A#$>x$HI&))*=*@B( &h/(,VX>**5599:KLr   c                     t        j                  dd      }t        j                  dd      }|j                  |       }|j                  j                  |      }|j                  S )zBReturns the Cloud project number associated with the `project_id`.cloudresourcemanagerr   )	projectId)r   r0   r*   &CloudresourcemanagerProjectsGetRequestprojectsGetprojectNumber)
project_idcrm_message_moduleresource_managerreqrm   s        r   ProjectIdToProjectNumberr      se    --.DdK++,BDIAA 	B 	#%%))#.'			r   c           
          t        |       \  }}t        |      }t        |      }t        | ||j	                  |t        j                  |                   | S )z;Returns an updated `request` with the Cloud project number.)r\   rn   r   rq   rR   r4   r5   )rY   rZ   r[   r   project_numbers        r    OverrideProjectIdToProjectNumberr      sR    +G4(M(2*+J7.	'=


:s}}^'D
EG 
.r   c                 L    ~ ~t        |      }t        |      }t        |       |S )zCReturns an updated `request` with values for a valid Admin request.)rs   r   r{   resource_refargsrY   s      r   UpdateAdminRequestr      s*     D'"',W5'W%	.r   c                     ~ ~t        |      }|j                  j                  xj                  dz  c_        t	        |       |S )zAUpdates a CommitCursorRequest by adding 1 to the provided offset.rC   )rs   commitCursorRequestcursoroffsetr{   r   s      r   UpdateCommitCursorRequestr      s?     D'"' 
$$++q0+W%	.r   c                 Z    | j                   yt        | j                   j                        S )z0Returns whether the topic has a reservation set.F)reservationConfigboolthroughputReservationtopics    r   _HasReservationr   	  s(    
$	e%%;;	<<r   c                 $   ~ ~|j                   }t        |      sv|j                  i |_        |j                  j                  i |j                  _        |j                  j                  }|j                  d|_        |j
                  d|_        |S )zHAdds the default values for topic throughput fields with no reservation.      )r   r   partitionConfigcapacitypublishMibPerSecsubscribeMibPerSec)r   r   rY   r   r   s        r   "AddTopicDefaultsWithoutReservationr     s     D
--%		$ e%%-')e$$$--H  ("#h""*$%h!	.r   c                 8   ~ ~|j                   }t        |      s|S t        |      \  }}t        |      }t	        t        |            }|j                  j                  }dj                  t        |t        |t        |      |j                   j                  _        |S )zEReturns an updated `request` with a resource path on the reservation.{}{}/{}{}/{}{})r   r   r\   rn   rA   rj   r   r   formatrl   ri   RESERVATIONS_RESOURCE_PATH)	r   r   rY   r   rZ   ry   rm   rK   reservations	            r   AddTopicReservationResourcer   $  s     D
--%		N(+(A%h/'#$>x$HI&''==+
 '+BF
$k3 
--!!7
 
.r   c                     ~ ~t        |      \  }}dj                  |t        |j                  j                        |j                  _        |S )z?Returns an updated `request` with a resource path on the topic.z{}/{}{})r\   r   TOPICS_RESOURCE_PATHrW   r   )r   r   rY   rZ   ry   s        r   AddSubscriptionTopicResourcer   9  sL     D(+(A(//:N070D0D0J0J L' 
.r   c                 \    ~ d|vs|j                   s|S t        j                  ddd       |S )z:Prompts to confirm an update to a topic's partition count.
partitionszWarning: The number of partitions in a topic can be increased but not decreased. Additionally message order is not guaranteed across a topic resize. See https://cloud.google.com/pubsub/lite/docs/topics#scaling_capacity for more detailsT)messagedefaultcancel_on_no)r   r   PromptContinuer   s      r   ConfirmPartitionsUpdater   E  s:    T__N
  
.r   c                 H    ~ t        |d      r|j                  dk(  |_        |S )Nstarting_offsetend)rX   r   skipBacklogr   s      r   UpdateSkipBacklogFieldr   V  s(    T$%//58G	.r   c                 6    | j                   xs | j                  S )z"Returns the raw location argument.)r?   zone)r   s    r   GetLocationValuer   `  s    		#$))#r   c                 ~    t        |       }t        |vr|S t        |      }|st        dj	                  |            |S )zReturns the resource location (zone or region) extracted from arguments.

  Args:
    args: argparse.Namespace, the parsed commandline arguments.

  Raises:
    InvalidResourcePath: if the location component in a fully qualified path is
    invalid.
  zGThe location component in the specified location path is invalid: `{}`.)r   ri   rj   r(   r   )r   r?   parsed_locations      r   GetLocationr   e  sJ     d#(H,O.x8/	
Q		  
r   c                    t        |       }|j                  t              s@| j                  xs2 t        j
                  j                  j                  j                         S t        |      }|st        dj                  |            |S )zReturns the project from either arguments or attributes.

  Args:
    args: argparse.Namespace, the parsed commandline arguments.

  Raises:
    InvalidResourcePath: if the project component in a fully qualified path is
    invalid.
  zFThe project component in the specified location path is invalid: `{}`.)r   
startswithrl   rm   r   rv   core	GetOrFailrn   r(   r   )r   r?   parsed_projects      r   
GetProjectr   {  sv     d#(			3	4<<E:,,1199CCEE,X6.	
P		  
r   c                     | j                   dk(  r |j                  j                  j                  S |j                  j                  j                  S )z4Returns the DeliveryRequirement enum from arguments.zdeliver-after-stored)delivery_requirementDeliveryConfig"DeliveryRequirementValueValuesEnumDELIVER_AFTER_STOREDDELIVER_IMMEDIATELYr   psls     r   GetDeliveryRequirementr     sA    	"88@@UUU				>	>	R	RRr   c                     | j                   dk(  r |j                  j                  j                  S |j                  j                  j                  S )z4Returns the export DesiredState enum from arguments.paused)export_desired_stateExportConfigDesiredStateValueValuesEnumPAUSEDACTIVEr   s     r   GetDesiredExportStater     s@    	(*77>>>				5	5	<	<<r   c                 n   | j                   r?|j                  |j                  t        j                  | j                                     S | j
                  r?|j                  |j                  t        j                  | j
                                    S | j                  r| j                  dk(  r0|j                  |j                  j                  j                        S | j                  dk(  r0|j                  |j                  j                  j                        S t        d      t        d      )	z1Returns a SeekSubscriptionRequest from arguments.)publishTime)
timeTarget)	eventTime	beginning)namedTargetr   z@Invalid starting offset value! Must be one of: [beginning, end].zSeek target must be specified!)publish_timeSeekSubscriptionRequest
TimeTargetr   FormatSeekTime
event_timer   NamedTargetValueValuesEnumTAILHEADr&   r   s     r   GetSeekRequestr     s0   	&&>>++D,=,=> " @ ' A A &&>>))$//: " < ' = = {*((S5P5P*D*DTT ) K K				&((S5P5P*D*DTT ) K K 
LN N <
==r   c                 r   | j                   rT| j                   }|j                  t              sdj                  t        |t        |      }|j                  |      |_        | j                  rK| j                  }|j                  t              s"dj                  t        |t        |t        |      }||_	        yy)z8Sets fully qualified resource paths for an ExportConfig.	{}{}/{}{}r   r   N)
export_pubsub_topicr   rl   r   r   PubSubConfigpubsubConfigexport_dead_letter_topicri   deadLetterTopic)r   r   rm   r?   export_configr   s         r   SetExportConfigResourcesr     s    	$$E23!!"8'"6?e!$!1!1!1!>M	""))E23&&'=w'>';UDe %*M! #r   c                     | j                   yt        | |      }|r |j                  j                  j                  }|j                  |      }t        | ||||       |S )z'Returns an ExportConfig from arguments.NdesiredState)r   r   r   r   r   r   )r   r   rm   r?   requires_seekdesired_stater   s          r   GetExportConfigr     s`    	%'c2-$$@@GGM""">-4gxG	r   c                    t               }t        |      }t        |      }t        j                  t        |            }|j                  xs |j                  }|j                  dj                  t        |t        |      |j                  |j                  |j                  t        ||            t!        |||||            |j"                        }t%        |       t'        | ||       |st)        | ||       t+               }|j,                  j/                  |      }	|rB|j1                  |	j2                  t5        ||            }
|j,                  j7                  |
       |r|j"                  j8                  r|j:                  dk(  rw|j=                  |	j2                  d|j                  |j?                  |j>                  j@                  jB                        	      
      }|j,                  jE                  |      }	|	S )a,  Issues a CreateSubscriptionRequest and potentially other requests.

  Args:
    resource_ref: resources.Resource, the resource reference for the resource
      being operated on.
    args: argparse.Namespace, the parsed commandline arguments.

  Returns:
    The created Pub/Sub Lite Subscription.
  r   )deliveryRequirement)r   deliveryConfigexportConfig)rU   rW   subscriptionId)rV   seekSubscriptionRequestactivezexport_config.desired_stater   )r   )rV   
updateMaskrW   )#r1   r   r   r4   r5   r   r   r   :PubsubliteAdminProjectsLocationsSubscriptionsCreateRequestr   rl   ri   Subscriptionr   r   r   r   rW   r{   r   r   r-   &admin_projects_locations_subscriptionsCreate8PubsubliteAdminProjectsLocationsSubscriptionsSeekRequestrV   r   Seekr   r   9PubsubliteAdminProjectsLocationsSubscriptionsPatchRequestr   r   r   Patch)r   r   r   r?   r   r   r   create_requestclientresponseseek_requestupdate_requests               r    ExecuteCreateSubscriptionRequestr	    s    	#($*==!9*!EF.##6t- QQ  !7!8(D##

++"8s"C , E&tS.('46	 $ 7 && R 	(. ^,|T>B	<~>&::AA( OO]]N44M P OL
1166|D ~22??DD]D]aiDiRR]]0%%))s7G7G+F+Fvv * O & P S QN <<BBH 
/r   c                     ~ |j                   j                  |S t        |      \  }}t        |      }t	        |      }t               }t        |||||j                   j                         |S )aI  Sets export resource paths for an UpdateSubscriptionRequest.

  Args:
    resource_ref: resources.Resource, the resource reference for the resource
      being operated on.
    args: argparse.Namespace, the parsed commandline arguments.
    request: An UpdateSubscriptionRequest.

  Returns:
    The UpdateSubscriptionRequest.
  )rW   r   r\   rn   rj   r1   r   )r   r   rY   rZ   ry   rm   r?   r   s           r   AddExportResourcesr    sl     &&.N(+(A%h/''1(#4gx"//<<>	.r   c                 h    ~ t               }t        ||      |_        t        j                  d       |S )z.Sets the target for a SeekSubscriptionRequest.zThe seek operation will complete once subscribers react to the seek. If subscribers are offline, `pubsub lite-operations describe` can be used to check the operation status later.)r1   r   r   r
   warning)r   r   rY   r   s       r   SetSeekTargetr  .  s6     #$24$='!++23 
.r   c                 b   ~ |j                   r|S |j                  r0dj                  |j                  t        |j                        |_         |j
                  rW|j                   r|xj                   dz  c_         nd|_         |xj                   dj                  |j
                        z  c_         |S )z/Updates the filter for a ListOperationsRequest.ztarget={}/{}{}z AND rQ   zdone={})filterrW   r   rV   SUBSCRIPTIONS_RESOURCE_PATHdoner   s      r   UpdateListOperationsFilterr  <  s      
[[N 
 &,,W\\-H-1->->@GN 
YY~~nnngnNNi&&tyy11N	.r   c                     t         j                  j                  dk  s:t         j                  j                  dk(  r8t         j                  j                  dk  rt	        dj                  |             yy)zVerifies that the python version is 3.6+.

  Args:
    cmd: The string command that requires python 3.6+.

  Raises:
    InvalidPythonVersion: if the python version is not 3.6+.
  r_      znThe `{}` command requires python 3.6 or greater. Please update the
        python version to use this command.N)sysversion_infomajorminorr   r   )cmds    r   RequirePython36r  V  se     	aC$4$4$:$:a$?$'$4$4$:$:Q$>
	//5vc{< < %? %@r   )gcloud)Er   
__future__r   r   r   r   r  googlecloudsdk.api_lib.utilr   !googlecloudsdk.command_lib.pubsubr   googlecloudsdk.corer	   r
   r   googlecloudsdk.core.consoler   r4   six.moves.urllib.parser   rl   ri   r   r   r  r+   r,   Errorr   r   r   r&   r(   r-   r1   r9   rA   rI   rO   rS   r\   re   rj   rn   rs   r{   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r	  r  r  r  r  r   r   r   <module>r$     su   E &  % ' 
 , 2 * # * 2 
 + % & ,   . "  5j.. 5-:++ -@j&& @5
(( 5G*** GM
M
:
&:!>0M"		=(*	"$
,,S=>4*$6r64<r   