o
    SDi                     @   s"  U d dl Zd dlZd dlZd dlZd dlZd dlmZ d dlm	Z	m
Z
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mZmZmZ d d	lmZmZmZ d d
lmZ d dlmZ  d dl!m"Z"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-m.Z.m/Z/ d dl0m1Z1m2Z2 d dl3m4Z4 d dl5m6Z6 d dl7m8Z8 d dl9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@ d dlAmBZB d dlCmDZD d dlEmFZFmGZGmHZH ddlImJZJ ddlKmLZLmMZMmNZN ddlOmPZPmQZQmRZRmSZSmTZTmUZUmVZV ddlWmXZX dd lYmZZZ dd!l[m\Z\m]Z] d"Z^d#Z_e;d$Z`e=d%ZaebZcee\eXeZe]edf Zee<efd&< eeeeNdf  eeN f Zge<efd'< ehZier:e\ZjeZZkeXZlne@e\Zje@eZZke@eXZlG d(d) d)ZmG d*d+ d+emd,d-ZnG d.d/ d/ZoG d0d1 d1Zpd2eqd3eifd4d5ZrG d6d7 d7Zsd8ed9ee"df d:efd;d<Ztd=e	d>ehd?eqfd@dAZudS )B    N)defaultdict)CallableIteratorSequence)AsyncExitStack)
ContextVar)date)Enum)TYPE_CHECKINGClassVarUnioncast)BackgroundTasksHTTPExceptionparams)Request)Response)
ModelField_normalize_errors)run_in_threadpool)	Dependant)solve_dependencies)RequestValidationError)FileResponseJSONResponseStreamingResponse)APIRoute_prepare_response_content)	BaseModel)PydanticUndefined)is_async_callable)Any	ParamSpec	TypeAliasTypeVarassert_never
deprecatedget_args)CURRENT_DEPENDENCY_SOLVER_VAR)classproperty)CadwynError CadwynHeadRequestValidationErrorCadwynStructureError   )Sentinel   )EndpointVersionedModelVersionType)RequestInfoResponseInfo_AlterRequestByPathInstruction _AlterRequestBySchemaInstruction_AlterResponseByPathInstruction!_AlterResponseBySchemaInstruction_BaseAlterResponseInstruction)AlterEndpointSubInstruction)AlterEnumSubInstruction)AlterSchemaSubInstructionSchemaHadInstructioncadwyn_request_paramcadwyn_response_param_P_RPossibleInstructionsAPIVersionVarTypec                       s  e Zd ZU eZee ed< dZe	ed< eZ
eee  ed< eZeeeeef   ed< eZeee  ed< eZeee  ed< eZeeee ee f  ed< eZeeeee f  ed	< eZeeeee f  ed
< eZeeeee  f  ed< ded< eZ!eee"ee f  ed< eZ#eee"ee  f  ed< dde	ddf fddZ$e%dd Z&e%dd Z'e%dd Z(e%dd Z)d ddZ*  Z+S )!VersionChangedescriptionFis_hidden_from_changelog+instructions_to_migrate_to_previous_versionalter_schema_instructionsalter_enum_instructionsalter_endpoint_instructions$alter_request_by_schema_instructions"alter_request_by_path_instructions%alter_response_by_schema_instructions#alter_response_by_path_instructionszUnion[VersionBundle, None]_bound_version_bundle#_route_to_request_migration_mapping$_route_to_response_migration_mapping	_abstractreturnNc                    sP   t    |r	d S |   |   |   |   d | _tt| _	tt| _
d S N)super__init_subclass___validate_subclass2_extract_list_instructions_into_correct_containers2_extract_body_instructions_into_correct_containers_check_no_subclassingrO   r   listrP   rQ   )clsrR   	__class__ R/var/www/Datamplify/venv/lib/python3.10/site-packages/cadwyn/structure/versions.pyrV   \   s   

zVersionChange.__init_subclass__c                 C   s   | j  D ]G}t|tr|jD ]
}| j| | qqt|tr*| j|j	 | qt|t
r>|jD ]
}| j| | q2qt|trL| j|j	 | qd S rT   )__dict__values
isinstancer6   schemasrK   appendr5   rL   pathr8   rM   r7   rN   )r\   instructionschemar_   r_   r`   rY   i   s   





z@VersionChange._extract_body_instructions_into_correct_containersc                 C   s   g | _ g | _g | _tt| _tt| _tt| _tt| _| j	D ]<}t
|ts,t
|tr3| j | q t
|tr?| j| q t
|trK| j| q t
|trXtd| dt| q d S )N"z/" is an unacceptable version change instruction)rH   rI   rJ   r   r[   rK   rL   rM   rN   rG   rc   r=   _AlterSchemaSubInstructionArgsre   _AlterEnumSubInstructionArgs _AlterEndpointSubInstructionArgsstaticmethodNotImplementedErrorr%   )r\   alter_instructionr_   r_   r`   rX   w   s(   








z@VersionChange._extract_list_instructions_into_correct_containersc              	   C   s   | j tu rtd| j d| jtu rtd| j dt| jts+td| j d| jD ]}t|tts?td| dq.| j	
 D ]"\}}t|ttttfsg|dvrgtd	| d
t| d| j dqEd S )Nz*Version change description is not set on 'z' but is required.zGAttribute 'instructions_to_migrate_to_previous_version' is not set on 'zOAttribute 'instructions_to_migrate_to_previous_version' must be a sequence in ''.zInstruction 'z;' is not allowed. Please, use the correct instruction types>   __doc__
__module__rE   side_effects__firstlineno____static_attributes__rG   zFound: 'z' attribute of type 'z' in 'z^'. Only migration instructions and schema properties are allowed in version change class body.)rE   r.   r,   __name__rG   rc   r   r'   rB   ra   itemsr6   r5   r8   r7   type)r\   rg   	attr_name
attr_valuer_   r_   r`   rW      sB   



	z VersionChange._validate_subclassc                 C   s(   |   | ttgkrtd| j dd S NzCan't subclass z( as it was never meant to be subclassed.)mrorD   object	TypeErrorrv   r\   r_   r_   r`   rZ      s
   z#VersionChange._check_no_subclassingc                 C   s   t d| jj d)NzCan't instantiate z* as it was never meant to be instantiated.)r~   r^   rv   selfr_   r_   r`   __init__   s   zVersionChange.__init__)F)rS   N),rv   rr   __qualname__r.   rE   r   str__annotations__rF   boolrG   r   rB   rH   r[   r   r<   r=   rI   r;   rJ   r:   rK   dictrx   r   r6   rL   r5   rM   r8   rN   r7   rP   _RouteIdrQ   rV   classmethodrY   rX   rW   rZ   r   __classcell__r_   r_   r]   r`   rD   K   s2   
 


*
rD   c                   @   s2   e Zd Zedd Zeded  defddZdS )VersionChangeWithSideEffectsc                 C   s*   |   | tttgkrtd| j dd S r{   )r|   r   rD   r}   r~   rv   r   r_   r_   r`   rZ      s
   z2VersionChangeWithSideEffects._check_no_subclassingr\   rS   c                 C   sP   | j d u s| | j jvrtd| j d| j j }|d u r dS | j j|  |kS )NzYou tried to check whether 'z2' is active but it was never bound to any version.T)rO   #_version_changes_to_version_mappingr*   rv   api_version_varget)r\   api_versionr_   r_   r`   
is_applied   s   
z'VersionChangeWithSideEffects.is_appliedN)	rv   rr   r   r   rZ   r)   rx   r   r   r_   r_   r_   r`   r      s
    
r   T)rR   c                       sX   e Zd Zdeeef dee ddf fddZe	e
ddd	 Zdefd
dZ  ZS )VersionvaluechangesrS   Nc                    s,   t    t|tr| }|| _|| _d S rT   )rU   r   rc   r   	isoformatr   r   )r   r   r   r]   r_   r`   r      s
   


zVersion.__init__e'version_changes' attribute is deprecated and will be removed in Cadwyn 5.x.x. Use 'changes' instead.c                 C      | j S rT   r   r   r_   r_   r`   version_changes      zVersion.version_changesc                 C   s   d| j  dS )Nz	Version('z')r   r   r_   r_   r`   __repr__   s   zVersion.__repr__)rv   rr   r   r   r   r   rx   rD   r   propertyr&   r   r   r   r_   r_   r]   r`   r      s    &r   c                       s>   e Zd Zdee ddf fddZeeddd Z  Z	S )	HeadVersionr   rS   Nc                    sF   t    || _|D ]}t|j|j|j|jgr td| dq
d S )Nz@HeadVersion does not support request or response migrations but z contained one.)	rU   r   r   anyrL   rK   rN   rM   rn   )r   r   version_changer]   r_   r`   r      s   

zHeadVersion.__init__r   c                 C   r   rT   r   r   r_   r_   r`   r     r   zHeadVersion.version_changes)
rv   rr   r   rx   rD   r   r   r&   r   r   r_   r_   r]   r`   r      s
    r   r\   rS   c                 C   s   | j  d| j S )N.)rr   rv   r   r_   r_   r`   get_cls_pythonpath  s   r   c                       s*  e Zd Zdddeeef dedeeeedf  df ddf fddZde	e fd	d
Z
eeddd Zejdeeee f fddZejdeeee f fddZdefddZdeee df dededededededededee df dee!e"f fdd Z#d!e$ded"eee df deedf de$f
d#d$Z%d%eee df d&ee!df d'eded(ed)e!d*ee!df d+e!dd,fd-d.Z&d/e'ded'ed0e!d+e!d1ee!e"f d2ede"fd3d4Z(d%eee df d5ee!df ded)e!d1ee!e"f ded'ededededee df dee!e"f fd6d7Z)  Z*S )8VersionBundleN)r   latest_version_or_head_versionother_versionsr   rS   c                  sV  t    t|tr|| _|| _nt | _|g|R | _tt| j| _|d u r,t	d}tdd | jD | _
tt| j
| _|| _| jg| jR | _dd | jD | _t | _| jD ]4}|j| jvrk| j|j ntdtj d|j d|jD ]}|jd urtd	|j d
| |_q{q[| jstd| jd jrtd| jd j dd S )Ncadwyn_api_versionc                 s   s    | ]}|j V  qd S rT   r   ).0versionr_   r_   r`   	<genexpr>   s    z)VersionBundle.__init__.<locals>.<genexpr>c                 S   s    i | ]}|j D ]}||jqqS r_   )r   r   )r   r   r   r_   r_   r`   
<dictcomp>$  s
    z*VersionBundle.__init__.<locals>.<dictcomp>zAYou tried to define two versions with the same value in the same z: 'rp   z"You tried to bind version change 'z.' to two different versions. It is prohibited.zAYou must define at least one non-head version in a VersionBundle.zThe first version "z" cannot have any version changes. Version changes are defined to migrate to/from a previous version so you cannot define one for the very first version.)rU   r   rc   r   head_versionversionstuplereversedreversed_versionsr   version_valuesreversed_version_valuesr   _all_versionsr   set_version_values_setr   addr,   r   rv   r   rO   )r   r   r   r   r   r   r]   r_   r`   r     sR   




zVersionBundle.__init__c                 c   s    | j E d H  d S rT   )r   r   r_   r_   r`   __iter__A  s   zVersionBundle.__iter__zUse 'version_values' instead.c                 C   r   rT   )r   r   r_   r_   r`   version_datesD  r   zVersionBundle.version_datesc                 C   s(   dd | j D }dd | j D }||B S )Nc                 S   s6   i | ]}|j D ]}t|jD ]	}t|j|jqqqS r_   )r   r[   rH   r   rh   r   r   r   rg   r_   r_   r`   r   K  s    
z3VersionBundle.versioned_schemas.<locals>.<dictcomp>c                 S   s6   i | ]}|j D ]}t|j D ]}t||qqqS r_   )r   r[   rK   keysr   )r   r   r   rh   r_   r_   r`   r   R  s    
r   )r   altered_schemasmigrated_schemasr_   r_   r`   versioned_schemasI  s   zVersionBundle.versioned_schemasc                 C   s   dd | j D S )Nc                 S   s2   i | ]}|j D ]}|jD ]	}t|j|jqqqS r_   )r   rI   r   enumr   r_   r_   r`   r   ]  s    
z1VersionBundle.versioned_enums.<locals>.<dictcomp>r   r   r_   r_   r`   versioned_enums[  s   zVersionBundle.versioned_enumsr   c                 C   s$   | j D ]
}||kr|  S qtd)Nz[You tried to migrate to version that is earlier than the first version which is prohibited.)r   r*   )r   r   defined_versionr_   r_   r`   _get_closest_lesser_versiond  s
   
z)VersionBundle._get_closest_lesser_version	body_typehead_dependantrequestresponserequest_infocurrent_version
head_route
exit_stackembed_body_fieldsbackground_tasksc             
      s   | j |}t|}| j|d d  D ].}|jD ](}|d ur0||jv r0|j| D ]}|| q)||jv rA|j| D ]}|| q:qqtdd |j	 D |j
d< |`td t||||j|j||	|
dI d H }|jrxtt|j|j|d|jS )Nr/   c                 s   s$    | ]\}}|  |  fV  qd S rT   )encode)r   keyr   r_   r_   r`   r     s   " z1VersionBundle._migrate_request.<locals>.<genexpr>headerscadwyn)r   r   	dependantbodydependency_overrides_providerasync_exit_stackr   r   )r   r   )r   indexidr   r   rK   rP   r   r   rw   scope_headersr(   r   r   r   r   errorsr+   r   rb   )r   r   r   r   r   r   r   r   r   r   r   starthead_route_idvr   rg   resultr_   r_   r`   _migrate_requestj  s>   





zVersionBundle._migrate_requestresponse_infohead_response_modelc                 C   s   t |}| j|}| jd | D ]7}|jD ]1}g }	|r)||jv r)|	|j|  ||jv r6|	|j|  |	D ]}
|jdk sB|
j	rF|
| q8qq|S )Ni,  )
r   r   r   r   r   rM   extendrQ   status_codemigrate_http_errors)r   r   r   r   r   r   endr   r   migrations_to_apply	migrationr_   r_   r`   _migrate_response  s$   

zVersionBundle._migrate_responsehead_body_fieldmodule_body_field_nameroute dependant_for_request_migrationsrequest_param_namebackground_tasks_param_nameresponse_param_namez.Callable[[Endpoint[_P, _R]], Endpoint[_P, _R]]c          
   
      s"   d f	dd}	|	S )NendpointEndpoint[_P, _R]rS   c                    sb   t  dtdtdtf 	f
dd}tkr%t|tt tkr/t|tt |S )NargskwargsrS   c                     s   | }| }|  }|j}t}t 4 I d H -}	j|||j|dI d H }	|||I d H }W d   I d H  n1 I d H sMw   Y  |tu rZtd|S )Nr   r   r   a}  No response object was returned. There's a high chance that the application code is raising an exception and a dependency with yield has a block with a bare except, or a block with except Exception, and is not raising the exception again. Read more about it in the docs: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except)r   methodr.   r   #_convert_endpoint_kwargs_to_version_embed_body_fields%_convert_endpoint_response_to_versionr*   )r   r   request_paramresponse_paramr   r   r   r   )
r   r   r   r   r   r   r   r   r   r   r_   r`   	decorator  sJ   (z<VersionBundle._versioned.<locals>.wrapper.<locals>.decorator)		functoolswrapsr!   rA   _CADWYN_REQUEST_PARAM_NAME_add_keyword_only_parameterFastapiRequest_CADWYN_RESPONSE_PARAM_NAMEFastapiResponse)r   r   	r   r   r   r   r   r   r   r   r   )r   r`   wrapper  s   .,z)VersionBundle._versioned.<locals>.wrapper)r   r   rS   r   r_   )
r   r   r   r   r   r   r   r   r   r  r_   r  r`   
_versioned  s   5zVersionBundle._versionedfunc_to_get_response_fromr   r   fastapi_response_dependencyc              
      s  d }|t kr|| zt|r|di |I d H }	nt|fi |I d H }	W n1 tyY }
 z%|
}ttd|ji|j	|j
d}	|j
pEi dd u rO|	j
d= W Y d }
~
nd }
~
ww | j }|d u re|	S t|	trt|	ttfrtd }n/|	jrt|	ts|d urt|	jttfrt|	j}nt|	jtr|	j|	j}n|	j}nd }t|	|}n+|j	d ur|j	}n|j	d ur|j	}n|d urtd}||_	t|t|	|j|j|jd}| |||j|}t|	trr|jd ur0t|j dr0t|jtr|j j
ddkr|j!|j j|j _ntj|jd	d	d d
d!d|j _|j
dd ur0tt"|j j|j
d< |d uro|j	dkrot|jt#rNd|jv rN|jd }n|j}|d u r]t$%|j	j&}t't||_t#|j
|_
|j	|_	||j S |jS )Ndetail)contentr   r   zcontent-length   )exclude_unsetexclude_defaultsexclude_noner   content-typezapplication/jsonF),:)ensure_ascii	allow_nanindent
separatorszutf-8  r_   )(r   popr    r   r   r   jsondumpsr  r   r   r   r   rc   r   r   r   r   r   bytesloadsdecodecharsetr4   rn   r   response_model_exclude_unsetresponse_model_exclude_defaultsresponse_model_exclude_noner   response_modelhasattr	_responser   lenr   http
HTTPStatusphraser   )r   r  r   r   r   r   r   r  raised_exceptionresponse_or_response_bodyexcr   r   r   r   r  r_   r_   r`   r     s   


	






z3VersionBundle._convert_endpoint_response_to_versionbody_field_aliasc	                   s   || }|t kr|| | j }|d u r|S t|jjdkrI|d urI|d urI||v rI||}|d u r9d }nt|tsA|}n|j	ddd}n
t
||j|	I d H }t||}| j||||||||	|
|d
I d H }t |v rs|t  |S )Nr/   T)by_aliasr	  r   )r   r  r   r   r!  r   body_paramsrc   r   
model_dump	_get_body
body_fieldr3   r   )r   r   r(  r   r   r   r   r   r   r   r   r   r   r   raw_bodyr   r   
new_kwargsr_   r_   r`   r   w  sD   





z1VersionBundle._convert_endpoint_kwargs_to_version)+rv   rr   r   r   r   r   r   r2   r   r   r   r   r&   r   r   cached_propertyr   IdentifierPythonPathrx   r1   r   r	   r   r   r   r   r   r   r3   r   r   r   r   r   r!   r   r4   r   r  r0   r   r   r   r_   r_   r]   r`   r     s    
5



.



	

D
	
 

	

r   r   r-  r   c              
      s\  |o	t |jtj}zhd }|rm|r!|  I d H }||j W |S |  I d H }|rpt}| j	
d}|s<|  I d H }n#tj }||d< | dkr_| }	|	dksX|	dr_|  I d H }|tkrh|}W |S |}W |S W |S W |S  tjy }
 ztdd|
jfdi d|
jid	g|
jd
|
d }
~
w ty     ty }
 ztddd|
d }
~
ww )Nr  applicationr  z+jsonjson_invalidr   zJSON decode errorerror)rx   locmsginputctx)r   r  z#There was an error parsing the body)r   r  )rc   
field_infor   Formformpush_async_callbackcloser   r   r   r   r  emailmessageMessageget_content_maintypeget_content_subtypeendswithJSONDecodeErrorr   posr6  docr   	Exception)r   r-  r   is_body_formr   
body_bytes	json_bodycontent_type_valuer?  subtypeer_   r_   r`   r,    sd   $
'!	r,  func
param_nameparam_annotationc                 C   s>   t | }|jg t|j t j|t jj|dd| _	d S )N)kind
annotation)
parameters)
inspect	signaturereplacer[   rS  rb   	Parameter_ParameterKindKEYWORD_ONLY__signature__)rN  rO  rP  rU  r_   r_   r`   r     s   
r   )vemail.messager>  r   r"  rT  r  collectionsr   collections.abcr   r   r   
contextlibr   contextvarsr   datetimer   r   r	   typingr
   r   r   r   fastapir   r   r   r   r   r   r   fastapi._compatr   r   fastapi.concurrencyr   fastapi.dependencies.modelsr   fastapi.dependencies.utilsr   fastapi.exceptionsr   fastapi.responsesr   r   r   fastapi.routingr   r   pydanticr   pydantic_corer   starlette._utilsr    typing_extensionsr!   r"   r#   r$   r%   r&   r'   cadwyn._internal.context_varsr(   cadwyn._utilsr)   cadwyn.exceptionsr*   r+   r,   _utilsr.   commonr0   r1   r2   datar3   r4   r5   r6   r7   r8   r9   	endpointsr:   enumsr;   rd   r<   r=   r   r   r@   rA   intr   rm   rB   r   rC   r   r1  rj   rk   rl   rD   r   r   r   rx   r   r   r,  r   r_   r_   r_   r`   <module>   s   
 $$	${   /

0