Ë
    ¼vëj�'  ã                  ó
  — d Z ddlmZ ddlZddlZddlZddlmZ ddlmZ ddl	m
Z
mZmZ ddl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mZmZ  ej:                  d«      Zdd„Z G d„ de «      Z! G d„ d«      Z"y)a8  The one object a product holds. It never raises for a billing reason except Refused, and it fails open: when
the platform or the tenant's database cannot be reached the model call goes ahead, the usage is kept and settled
when they are back, and one line is logged. A billing fault must not stop a campaign; only a pool known to be
used up does.

Two databases: the platform's master DB for the rates and the subscription (what the organisation may spend),
the tenant's own schema for the pool and the ledger (what it has spent), beside the product's own usage table.
é    )ÚannotationsN)Úcontextmanager)Údatetime)ÚCallableÚListÚOptionalé   )Úpool)ÚEntitlementÚread_entitlement)Útell_members_in_the_bell)Úrate_for)Úensure_tenant_tables)ÚChargeÚDecisionÚRatezgalaxiq.ai_creditsc                óH   — t        | «      } | j                  d«      r| S d| › �S )zaThe platform's schema for a tenant's data: org_<tenantId>, however the product spells the tenant.Úorg_)ÚstrÚ
startswith)Ú	tenant_ids    ú`/var/www/html/strategist-ai/venv/lib/python3.12/site-packages/galaxiq_utils/ai_credits/client.pyÚ
org_schemar      s*   € ä�I“€IØ!×,Ñ,¨VÔ4ˆ9ÐL¸DÀÀÐ:LÐLó    c                  ó$   ‡ — e Zd ZdZdˆ fd„Zˆ xZS )ÚRefusedzUThe pool cannot cover this call. `decision` says how much is left and when it renews.c                ó”   •— |j                   dk(  rd}n|j                  rd|j                  d›�}nd}t        ‰| �  |«       || _        y )NÚno_ratezSAI work with this model is not priced yet, so it cannot be charged to your credits.z"AI credits used up; they renew on z%d %bzAI credits used up)ÚreasonÚ	renews_atÚsuperÚ__init__Údecision)Úselfr#   ÚmessageÚ	__class__s      €r   r"   zRefused.__init__'   sK   ø€ Ø�?‰?˜iÒ'Øk‰GØ×ÒØ:¸8×;MÑ;MÈeÐ:TÐU‰Gà*ˆGÜ‰Ñ˜Ô!Ø ˆ�r   )r#   r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r"   Ú__classcell__)r&   s   @r   r   r   $   s   ø„ Ù_÷!ñ !r   r   c                  óÂ   — e Zd Zdeddf	 	 	 	 	 	 	 dd„Zd„ Zedd„«       Zdd„Zdd„Z		 d	 	 	 	 	 dd„Z
	 d	 	 	 	 	 	 	 	 	 dd	„Zdd
„Zdd„Zedd„«       Zdd„Zdd„Zdd„Zy)ÚCreditsNé
   c                ó¶   ‡— || _         || _        || _        || _        || _        ‰| _        |xs ˆfd„| _        g | _        t        j                  «       | _
        y)aÝ  `tell_owners(tenant_id, mark, used, limit, renews_at)` is called once per mark per period; without one the
        every member is told in the platform bell (notices.py).
        `schema_of(tenant_id)` names the tenant's schema; org_<tenantId> unless the product says otherwise.
        `connect(dsn)` gives a connection to use in a with-block, such as a pool's; without it each check opens its own,
        which from a server far from the database costs seconds a model call.c                ó2   •— t        j                  | ‰¬«      S )N)Úconnect_timeout)ÚpsycopgÚconnect)Údsnr1   s    €r   ú<lambda>z"Credits.__init__.<locals>.<lambda>B   s   ø€ ´·±ÀÐUdÔ0e€ r   N)Ú_platform_dsnÚ_tenant_dsnÚproductÚ_tell_ownersÚ
_schema_ofÚ_timeoutÚ_connectÚ_pendingÚ	threadingÚLockÚ_lock)r$   Úplatform_dsnÚ
tenant_dsnr8   Útell_ownersÚ	schema_ofr1   r3   s         ` r   r"   zCredits.__init__3   sT   ø€ ð *ˆÔØ%ˆÔØˆŒØ'ˆÔØ#ˆŒØ'ˆŒØÒfÓ$eˆŒØ$&ˆŒÜ—^‘^Ó%ˆ�
r   c                ó8   — | j                  | j                  «      S ©N)r<   r6   ©r$   s    r   Ú	_platformzCredits._platformF   s   € Ø�}‰}˜T×/Ñ/Ó0Ð0r   c              #  óŒ   K  — | j                  | j                  «      5 }t        ||«       |–— d d d «       y # 1 sw Y   y xY w­wrF   )r<   r7   r   )r$   ÚschemaÚconns      r   Ú_tenantzCredits._tenantI   s=   è ø€ à�]‰]˜4×+Ñ+Ó,ð 	°Ü   vÔ.ØŠJ÷	÷ 	ñ 	üs   ‚Až8¯	A¸A½Ac                óf   — | j                  «       5 }t        ||«      cd d d «       S # 1 sw Y   y xY wrF   )rH   r   )r$   r   rK   s      r   ÚentitlementzCredits.entitlementO   s-   € Ø�^‰^Óð 	5 Ü# D¨)Ó4÷	5÷ 	5ò 	5ús   ‘'§0c                ó  — | j                  «       5 }t        ||«      }ddd«       €y| j                  |«      }| j                  |«      5 }t	        j
                  |||«      cddd«       S # 1 sw Y   ŒOxY w# 1 sw Y   yxY w)zfAllowance, purchased, used, reserved, remaining and the split by type, or None without a subscription.N)rH   r   r:   rL   r
   Úsummary)r$   r   ÚplatformrN   rJ   Útenants         r   rP   zCredits.summaryS   s‚   € à�^‰^Óð 	@ Ü*¨8°YÓ?ˆK÷	@àÐØØ—‘ Ó+ˆØ�\‰\˜&Ó!ð 	= VÜ—<‘< ¨°Ó<÷	=ñ 	=÷	@ð 	@ú÷
	=ð 	=ús   ‘A,ÁA8Á,A5Á8Bc                óz  — 	 | j                  «       5 }| j                  «        t        ||«      }|€t        dd«      cddd«       S t	        |||«      }	ddd«       | j                  |«      }
| j                  |
«      5 }t        j                  ||
	| j                  |||||«
      \  }}}}|dk(  xr" t        j                  ||
|j                  d«      }ddd«       r@| j                  |dj                  |j                  |j                  z   |j                   «       dv r$t        d|dj"                  |j                   «      S t        ddj"                  |j                   «      S # 1 sw Y   �ŒxY w# 1 sw Y   Œ¤xY w# t$        $ r.}t&        j)                  d	|||«       t        dd
«      cY d}~S d}~ww xY w)zŸAsk before the model runs. Allowed with a hold, allowed unverified when the databases are unreachable,
        or refused with the reason and the renewal date.NTÚno_subscriptionÚused_upéd   )rU   r   FÚ zEai credits: could not check %s for %s (%s); letting the call go aheadÚ
unverified)rH   Ú_drainr   r   r   r:   rL   r
   Úreserver8   Ú	tell_onceÚidÚ_tellÚusedÚ	allowanceÚ	purchasedÚendÚ	remainingÚ	ExceptionÚlogÚwarning)r$   r   ÚfeatureÚtypeÚ	model_keyÚinput_estimateÚoutput_estimaterQ   rN   ÚraterJ   rR   ÚholdÚestimateÚperiodr   Útold_nowÚexcs                     r   Ú	may_spendzCredits.may_spend]   s°  € ð	0Ø—‘Ó!ð ; XØ—‘”Ü.¨x¸ÓC�ØÐ&Ü# DÐ*;Ó<÷	;ñ ;ô
   ¨)°TÓ:�÷;ð —_‘_ YÓ/ˆFØ—‘˜fÓ%ð b¨Ü15·±¸fÀfÈkÐ[_Ðae×amÑamÐovÐx|Ø>GÈÐYhó2jÑ.��h ¨à! YÑ.Òa´4·>±>À&È&ÐRX×R[ÑR[Ð]`Ó3a�÷bñ Ø—
‘
˜9 c¨6¯;©;¸×8HÑ8HÈ6×K[ÑK[Ñ8[Ð]c×]gÑ]gÔhØÐ/Ñ/Ü  v¨t°X¸v×?OÑ?OÐQW×Q[ÑQ[Ó\Ð\Ü˜D " d¨H°f×6FÑ6FÈÏ
É
ÓSÐS÷;ñ ;ú÷bð bûô ò 	0Ü�K‰KÐ_ÐahÐjsÐuxÔyÜ˜D ,Ó/Õ/ûð	0ús_   ‚F ’*E*¼	F ÁE*Á*F Á=AE7ÃA1F Å#F Å*E4Å/F Å7F Å<F Æ	F:Æ#F5Æ/F:Æ5F:c
                óê  — |xs t        t        j                  «       «      }t        |||||||||	¬«	      }
	 | j	                  «        | j                  |
«      xs t        ddd«      S # t        $ r‚}| j                  5  | j                  j                  |
«       ddd«       n# 1 sw Y   nxY wt        j                  d|||t        | j                  «      «       t        dddd¬«      cY d}~S d}~ww xY w)zdReport what ran. Priced and taken off the pool; kept and settled later if a database is unreachable.)	Úreservation_idÚcall_idr   rf   rg   rh   Úinput_unitsÚcached_input_unitsÚoutput_unitsr   NzNai credits: could not record %s for %s (%s); kept to settle later (%d pending)T)Údeferred)r   ÚuuidÚuuid4ÚdictrY   Ú_settler   rc   r@   r=   Úappendrd   re   Úlen)r$   rs   rt   r   rf   rg   rh   ru   rv   rw   Úentryrp   s               r   ÚrecordzCredits.recordv   sÖ   € ð Ò.œS¤§¡£Ó.ˆÜ N¸GÈyÐbiÐptØ(°kÐVhØ".ô0ˆð	8Ø�K‰KŒMØ—<‘< Ó&Ò?¬&°°D¸$Ó*?Ð?øÜò 	8Ø—‘ñ ,Ø—‘×$Ñ$ UÔ+÷,÷ ,ñ ,úä�K‰KÐhØ ¨C´°T·]±]Ó1CôEä˜!˜T 4°$Ô7Õ7ûð	8ús6   ·/A' Á'	C2Á0C-Á<B!Â	C-Â!B*	Â&AC-Ã'C2Ã-C2c                ó  — |sy	 | j                  |«      }| j                  |«      5 }t        j                  |||«       ddd«       y# 1 sw Y   yxY w# t        $ r!}t
        j                  d||«       Y d}~yd}~ww xY w)zNothing ran: let the hold go.NzAai credits: could not release hold %s (%s); it expires on its own)r:   rL   r
   Úreleaserc   rd   re   )r$   r   rs   rJ   rR   rp   s         r   r‚   zCredits.release‡   sv   € áØð	rØ—_‘_ YÓ/ˆFØ—‘˜fÓ%ð =¨Ü—‘˜V V¨^Ô<÷=÷ =ñ =ûäò 	rÜ�K‰KÐ[Ð]kÐmp×qÑqûð	rús3   …"A §A¿A ÁAÁA ÁA Á	A>ÁA9Á9A>c                óž   — | j                  |«      }| j                  |«      5 }t        j                  ||«      cd d d «       S # 1 sw Y   y xY wrF   )r:   rL   r
   Úexpire_holds)r$   r   rJ   rR   s       r   r„   zCredits.expire_holds’   sC   € Ø—‘ Ó+ˆØ�\‰\˜&Ó!ð 	5 VÜ×$Ñ$ V¨VÓ4÷	5÷ 	5ò 	5ús   £AÁAc                ó,   — t        | j                  «      S rF   )r~   r=   rG   s    r   ÚpendingzCredits.pending—   s   € ä�4—=‘=Ó!Ð!r   c                óÐ  — | j                  «       5 }t        ||d   «      }|€'t        j                  d|d   |d   «       	 d d d «       y t	        ||d   |d   «      }d d d «       | j                  |d   «      }| j                  |«      5 }t        j                  |||d   |d   | j                  |d   |d   |d   |d   |d	   |d
   «      }|j                  rkt        j                  |||«      }|j                  D ]E  }	| j                  |d   |	|j                  |j                  |j                  z   |j                   «       ŒG d d d «       |S # 1 sw Y   ŒóxY w# 1 sw Y   S xY w)Nr   z7ai credits: %s has no subscription; %s recorded nowhererf   rh   rg   rs   rt   ru   rv   rw   )rH   r   rd   Úinfor   r:   rL   r
   Úsettler8   Úmarks_crossedÚopen_periodr]   r^   r_   r`   ra   )
r$   r   rQ   rN   rk   rJ   rR   Úchargern   Úmarks
             r   r|   zCredits._settle›   s•  € Ø�^‰^Óð 	Y Ü*¨8°U¸;Ñ5GÓHˆKØÐ"Ü—‘ÐRÐTYÐZeÑTfÐhmÐnwÑhxÔyØ÷		Yð 	Yô
 $,¨H°e¸KÑ6HÈ%ÐPVÉ-Ó#XˆD÷	Yð —‘  {Ñ!3Ó4ˆØ�\‰\˜&Ó!ð 	w VÜ—[‘[ ¨°¸dÀEÐJZÑD[Ð]bÐclÑ]mÐos×o{Ño{Ø!& yÑ!1°5¸±=À%ÈÑBTÐV[Ð\iÑVjØ!&Ð';Ñ!<¸eÀNÑ>SóUˆFð ×#Ò#Ü×)Ñ)¨&°&¸+ÓF�Ø"×0Ñ0ò w�DØ—J‘J˜u [Ñ1°4¸¿¹Àf×FVÑFVÐY_×YiÑYiÑFiÐkq×kuÑkuÕvðw÷	wð ˆ÷	Yð 	Yú÷	wð ˆús   ‘0EÁ
EÂ
B;EÅEÅE%c           	     ó  — 	 | j                   r| j                  |||||«       y| j                  «       5 }t        ||||||«       ddd«       y# 1 sw Y   yxY w# t        $ r"}t        j                  d|||«       Y d}~yd}~ww xY w)z�The product's own notifier when it gave one, else the platform bell for every owner. The charge stands
        whether or not it was announced.Nz;ai credits: could not tell the owners of %s about %s%% (%s))r9   rH   r   rc   rd   re   )r$   r   r�   r^   Úlimitr    rQ   rp   s           r   r]   zCredits._tell­   s‰   € ð	mØ× Ò Ø×!Ñ! )¨T°4¸À	ÕJà—^‘^Ó%ð `¨Ü,¨X°yÀ$ÈÈeÐU^Ô_÷`÷ `ñ `ûäò 	mÜ�K‰KÐUÐW`ÐbfÐhk×lÑlûð	mús9   ‚!A ¤A ´AÁA ÁAÁA ÁA Á	BÁ#B Â Bc                ó~  — | j                   5  | j                  g c}| _        ddd«       D ]  }	 | j                  |«       Œ y# 1 sw Y   Œ#xY w# t        $ rc}| j                   5  | j                  j	                  d|«       ddd«       n# 1 sw Y   nxY wt
        j                  d|d   |«       Y d}~ yd}~ww xY w)zUSettles what could not be recorded earlier, oldest first; stops at the first failure.Nr   z'ai credits: still cannot settle %s (%s)rt   )r@   r=   r|   rc   Úinsertrd   re   )r$   Úwaitingr   rp   s       r   rY   zCredits._drain¹   s«   € à�Z‰Zñ 	7Ø%)§]¡]°BÐ"ˆG�T”]÷	7àò 	ˆEðØ—‘˜UÕ#ñ	÷	7ð 	7ûô
 ò Ø—Z‘Zñ 3Ø—M‘M×(Ñ(¨¨EÔ2÷3÷ 3ñ 3úä—‘ÐEÀuÈYÑGWÐY\Ô]Ýûð	ús:   �A°AÁAÁ	B<ÁB7Á%BÂ	B7ÂBÂ!B7Â7B<)rA   r   rB   r   r8   r   rC   z8Optional[Callable[[str, int, int, int, datetime], None]]rD   zCallable[[str], str]r1   Úintr3   z!Optional[Callable[[str], object]])rJ   r   )r   r   ÚreturnzOptional[Entitlement])r   r   r”   zOptional[dict])r   r   )r   r   rf   r   rg   r   rh   r   ri   r“   rj   r“   r”   r   )r   r   r   )rs   úOptional[str]rt   r•   r   r   rf   r   rg   r   rh   r   ru   r“   rv   r“   rw   r“   r”   r   )r   r   rs   r•   r”   ÚNone)r   r   r”   r“   )r”   r“   )r   r{   r”   zOptional[Charge])r   r   r�   r“   r^   r“   r�   r“   r    r   r”   r–   )r”   r–   )r'   r(   r)   r   r"   rH   r   rL   rN   rP   rq   r€   r‚   r„   Úpropertyr†   r|   r]   rY   © r   r   r-   r-   2   sß   „ àY]Ø3=ÐVXØ>Bð&ØVð&à0ð&àPSð&ð <ó&ò&1ð òó ðó
5ó=ð CDð0Ø"%ð0Ø<?ð0ØHPó0ð4 ghð8Øð8Ø,/ð8ØILð8Ø`cð8Ølró8ó"	ró5ð
 ò"ó ð"óó$
môr   r-   )r   r   r”   r   )#r*   Ú
__future__r   Úloggingr>   ry   Ú
contextlibr   r   Útypingr   r   r   r2   rW   r
   r_   r   r   Únoticesr   Úratesr   rJ   r   Útypesr   r   r   Ú	getLoggerrd   r   rc   r   r-   r˜   r   r   ú<module>r¡      sm   ðñõ #ã Û Û Ý %Ý ß +Ñ +ã å ß 4Ý -Ý Ý (ß )Ñ )à€g×ÑÐ,Ó-€óMô!ˆiô !÷Rò Rr   