o
    h                     @   s  d dl Z d dlZ d dlZd dlZ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 d dlmZmZ ddlmZ ddlmZ ddlmZmZmZ dd	lmZmZ dd
lmZmZmZ edZ dgZ!dgZ"da#e j$Z$dd Z%dd Z&d6ddZ'ddddZ(d6ddZ)e
dd Z*dd Z+dd Z,e-edrej.e,d erd dl/Z/e/j0Z1nzd dl/Z/W n e2y   dZ/e3Z1Y nw e4e/de3Z1d Z5d!Z6d7d#d$Z7d%e8fd&d'Z9dedd"d"fd(d)Z:g d*Z;G d+d, d,eZ<d-d. Z=G d/d0 d0e>Z?d1d1e?d"fd2d3Z@G d4d5 d5eZAdS )8    N)contextmanager)	has_magic)TYPE_CHECKINGIterable   )DEFAULT_CALLBACK)FSTimeoutError)LocalFileSystemmake_path_posixtrailing_sep)AbstractBufferedFileAbstractFileSystem)glob_translateis_exceptionother_pathsz_[^_]c                   C   s   t st a t S )zAllocate or return a threading lock.

    The lock is allocated on first use to allow setting one lock per forked process.
    )_lock	threadingLock r   r   _/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/fsspec/asyn.pyget_lock   s   r   c                   C   s   dt d< dtd< dadS )zReset the global lock.

    This should be called only on the init of a forked process to reset the lock to
    None, enabling the new forked process to get a new lock.
    Nr   )iothreadloopr   r   r   r   r   
reset_lock&   s   r   c              
      s   |r|nd }|d urt j||d}z.z	|I d H |d< W n ty2 } z
||d< W Y d }~nd }~ww W |   d S W |   d S |   w )Ntimeoutr   )asynciowait_for	Exceptionset)eventcororesultr   exr   r   r   _runner3   s   r$   r   c          
      O   s   |r|nd}| du s|   rtdztj }|| u r tdW n ty)     ty1   Y nw ||i |}dg}t }tt	|||||  	 |
drRn|dur`|d8 }|dk r`tqL|d }	t|	tjrnt|	t|	tru|	|	S )z
    Make loop run coroutine until it returns. Runs in other thread

    Examples
    --------
    >>> fsspec.asyn.sync(fsspec.asyn.get_loop(), func, *args,
                         timeout=timeout, **kwargs)
    NzLoop is not runningz)Calling sync() from within a running loopTr   r   )	is_closedRuntimeErrorr   eventsget_running_loopNotImplementedErrorr   Eventrun_coroutine_threadsafer$   waitr   
isinstanceTimeoutErrorBaseException)
r   funcr   argskwargsloop0r!   r"   r    return_resultr   r   r   sync?   s>   	

	
r5   c                    s   t   fdd}|S )zGiven a function, make so can be called in blocking contexts

    Leave obj=None if defining within a class. Pass the instance if attaching
    as an attribute of the instance.
    c                     s&   p| d }t |j g| R i |S Nr   )r5   r   )r1   r2   selfr0   objr   r   wrappers   s   zsync_wrapper.<locals>.wrapper)	functoolswraps)r0   r9   r:   r   r8   r   sync_wrapperl   s   r=   c               	   c   sP    t  } ztjdkrtt drt t   d V  W t |  d S t |  w )NntWindowsSelectorEventLoopPolicy)r   get_event_loop_policyosnamehasattrset_event_loop_policyr?   )original_policyr   r   r   _selector_policy{   s   rF   c               	   C   s   t d du rZt I t d du rHt  t t d< W d   n1 s$w   Y  tjt d jdd} d| _| 	  | t
d< W d   t d S W d   t d S 1 sUw   Y  t d S )zdCreate or return the default fsspec IO loop

    The loop will be running on a separate thread.
    r   NfsspecIO)targetrB   T)r   r   rF   r   new_event_loopr   Threadrun_foreverdaemonstartr   )thr   r   r   get_loop   s"   





rO   c                   C   s   d t d< d td< d ad S r6   )r   r   lockr   r   r   r   reset_after_fork   s   rQ   register_at_fork)after_in_childerror   i   Fc              
   C   s   ddl m} | rd|v r|d S nd|v r|d S | rtS td u r#tS z
ttj\}}W n ttt	fy;   t Y S w |tj
krCdS |d S )Nr   )confnofiles_gather_batch_sizegather_batch_size   )fsspec.configrV   _NOFILES_DEFAULT_BATCH_SIZEresource_DEFAULT_BATCH_SIZE	getrlimitRLIMIT_NOFILEImportError
ValueErrorResourceErrorRLIM_INFINITY)nofilesrV   
soft_limit_r   r   r   _get_batch_size   s&   
rh   returnc                   C   s$   zt   W dS  ty   Y dS w )z Being executed by an event loop?TF)r   r(   r&   r   r   r   r   running_async   s   rj   c                    s  |du r
t |d}|dkrt| }|dksJ  fdd}d}t| }dg| }	t }
|
s4||k rt|
|k rY||k rY|
t|| | | |d7 }t|
|k rY||k s>|
s^	 |	S tj|
tjdI dH \}}
|r|| I dH \}}||	|< |sm|
s4||k s4|	S )	aS  Run the given coroutines in  chunks.

    Parameters
    ----------
    coros: list of coroutines to run
    batch_size: int or None
        Number of coroutines to submit/wait on simultaneously.
        If -1, then it will not be any throttling. If
        None, it will be inferred from _get_batch_size()
    callback: fsspec.callbacks.Callback instance
        Gets a relative_update when each coroutine completes
    timeout: number or None
        If given, each coroutine times out after this time. Note that, since
        there are multiple batches, the total run time of this function will in
        general be longer
    return_exceptions: bool
        Same meaning as in asyncio.gather
    nofiles: bool
        If inferring the batch_size, does this operation involve local files?
        If yes, you normally expect smaller batches.
    N)re   rY   r   c              
      sv   z3zt j| dI d H |fW W  d S  ty4 } zs  ||fW  Y d }~W  d S d }~ww  d w )Nr   r   )r   r   relative_updater   )r!   iecallbackreturn_exceptionsr   r   r   	_run_coro   s   z'_run_coros_in_chunks.<locals>._run_coror   )return_when)	rh   lenr   addr   ensure_futurer,   FIRST_COMPLETEDpop)coros
batch_sizero   r   rp   re   rq   rl   nresultspendingdoner"   kr   rn   r   _run_coros_in_chunks   s4   


r   )_ls	_cat_file	_get_file	_put_file_rm_file_cp_file
_pipe_file_expand_path_info_isfile_isdir_exists_walk_glob_find_du_size_mkdir	_makedirsc                       sx  e Zd ZdZdZdZdZdddd fdd
Zedd	 Z	d
d Z
dKddZdd Zdd Z				dLddZdMddZdNddZdd ZdNddZ	dOddZ			 dPd!d"ZdMd#d$Zdeddfd%d&Zd'd( Zdedfd)d*Zd+d, Zd-d. Zd/d0 ZdQd1d2Zd3d4 Zd5d6 ZdRd7d8Z dSd:d;Z!dQd<d=Z"dTd>d?Z#dUd@dAZ$dKdBdCZ%dRdDdEZ&dVdFdGZ'dWdIdJZ(  Z)S )XAsyncFileSystemak  Async file operations, default implementations

    Passes bulk operations to asyncio.gather for concurrent operation.

    Implementations that have concurrent batch operations and/or async methods
    should inherit from this class instead of AbstractFileSystem. Docstrings are
    copied from the un-underscored method in AbstractFileSystem, if not given.
    TFN)asynchronousr   ry   c                   sD   || _ t | _|s|pt | _nd | _|| _t j|i | d S N)	r   rA   getpid_pidrO   _loopry   super__init__)r7   r   r   ry   r1   r2   	__class__r   r   r   G  s   
zAsyncFileSystem.__init__c                 C   s   | j t krtd| jS )NzThis class is not fork-safe)r   rA   r   r&   r   r7   r   r   r   r   Q  s   zAsyncFileSystem.loopc                       t r   r)   r7   pathr2   r   r   r   r   W     zAsyncFileSystem._rm_filec                    sH   |pj }j||dI d H }t fddt|D |ddI d H S )N	recursivec                       g | ]}j |fi  qS r   )r   .0pr2   r7   r   r   
<listcomp>_      z'AsyncFileSystem._rm.<locals>.<listcomp>Try   re   )ry   r   r   reversed)r7   r   r   ry   r2   r   r   r   _rmZ  s   
zAsyncFileSystem._rmc                    r   r   r   )r7   path1path2r2   r   r   r   r   d  r   zAsyncFileSystem._cp_filec                    s(   |  ||I d H  | |I d H  d S r   )r   r   )r7   r   r   r   r   r   _mv_fileg  s   zAsyncFileSystem._mv_filec                    sZ  |d u r
|r
d}n|d u rd}t |trt |tr|}|}	n\t |t}
j|||dI d H }|
rG|r7|d urGfdd|D I d H }|sGd S t|dk}t |to]t|p]|I d H }|
oqt|rf|pqt| oq|oqt| }t||||
 d}	|pj	} fddt
||	D }t||d	d	d
I d H }tt|D ]}|dkrt |trq|d S )Nignoreraise)maxdepthr   c                    *   g | ]}t |s |I d H s|qS r   r   r   r   r   r   r   r         z)AsyncFileSystem._copy.<locals>.<listcomp>r   existsflattenc                    $   g | ]\}}j ||fi  qS r   )r   )r   p1p2r   r   r   r        $ T)ry   rp   re   )r-   liststrr   rs   r   r   r   r   ry   zipr   filterr   FileNotFoundError)r7   r   r   r   on_errorr   ry   r2   paths1paths2source_is_strsource_is_filedest_is_dirr   rx   r"   r#   r   r   r   _copyk  sT   




zAsyncFileSystem._copy	overwritec                    r   r   r   )r7   r   valuemoder2   r   r   r   r     r   zAsyncFileSystem._pipe_filec                    sF   t |tr
||i}|pj}t fdd| D |ddI d H S )Nc                    r   r   )r   r   r~   vr   r   r   r     r   z)AsyncFileSystem._pipe.<locals>.<listcomp>Tr   )r-   r   ry   r   items)r7   r   r   ry   r2   r   r   r   _pipe  s   

zAsyncFileSystem._pipec                    s   d}d}|dur*|dk r*|du r| }d}d}n|p$|  |I dH d }|| }n|du r0d}|s_|durO|dk rO|durN|pI|  |I dH d }|| }n|du rUd}t|tjr_|d8 }d| d	| S )
z"Helper for "Range"-based _cat_fileNFr    Tsizer   zbytes=-)r   r-   numbersIntegral)r7   urlrM   endr   suffr   r   r   _process_limits  s.   
zAsyncFileSystem._process_limitsc                    r   r   r   )r7   r   rM   r   r2   r   r   r   r     r   zAsyncFileSystem._cat_filer   c           
         s   j ||dI d H } fdd|D }|pj}t||dddI d H }dkr5ttt|d}	|	r5|	t|dksIt|tsI|d	 	|krUfd
dt
||D S |d	 S )Nr   c                    r   r   r   )r   r   r   r   r   r     r   z(AsyncFileSystem._cat.<locals>.<listcomp>Try   re   rp   r   Fr   r   c                    s&   i | ]\}} d kst |s||qS )omit)r   r   )r   r   r   
<dictcomp>  s
    z(AsyncFileSystem._cat.<locals>.<dictcomp>)r   ry   r   nextr   r   rs   r-   r   _strip_protocolr   )
r7   r   r   r   ry   r2   pathsrx   outr#   r   )r2   r   r7   r   _cat  s&   

zAsyncFileSystem._catri   c           	         s   |durt t|tstt|ts|gt| }t|ts&|gt| }t|t|ks6t|t|kr8t fddt|||D }|pJj}t	||dddI dH S )aY  Get the contents of byte ranges from one or more files

        Parameters
        ----------
        paths: list
            A list of of filepaths on this filesystems
        starts, ends: int or list
            Bytes limits of the read. If using a single int, the same value will be
            used to read all the specified files.
        Nc                    s*   g | ]\}}}j |f||d  qS ))rM   r   r   )r   r   srm   r   r   r   r     s    z/AsyncFileSystem._cat_ranges.<locals>.<listcomp>Tr   )
r)   r-   r   	TypeErrorr   rs   rb   r   ry   r   )	r7   r   startsendsmax_gapry   r   r2   rx   r   r   r   _cat_ranges  s$   


 

zAsyncFileSystem._cat_rangesc                    r   r   r   )r7   lpathrpathr   r2   r   r   r   r     r   zAsyncFileSystem._put_filec                    s  t |trt |tr|}|}	ndt |t}
|
rt|}t   j|||d}	|
r;|r.|dur; fdd|	D }	|	s;dS t|	dk}t |toQt|pQ|I dH }	|}|
ojt
|r_|pjt
| oj|ojt| }t|	|||
 d}dd |	D fd	dt|	|D }fd
dt|	|D }tjfdd|D  I dH  |pj}g }|t| |D ]\}}|j}||||fi | qt|||dI dH S )a  Copy file(s) from local.

        Copies a specific file or tree of files (if recursive=True). If rpath
        ends with a "/", it will be assumed to be a directory, and target files
        will go within.

        The put_file method will be called concurrently on a batch of files. The
        batch_size option can configure the amount of futures that can be executed
        at the same time. If it is -1, then all the files will be uploaded concurrently.
        The default can be set for this instance by passing "batch_size" in the
        constructor, or for all instances by setting the "gather_batch_size" key
        in ``fsspec.config.conf``, falling back to 1/8th of the system limit .
        r   r   Nc                    s"   g | ]}t |s |s|qS r   )r   isdirr   )fsr   r   r   ;     " z(AsyncFileSystem._put.<locals>.<listcomp>r   r   c                 S   s   i | ]	}|t j|qS r   )rA   r   r   )r   lr   r   r   r   P      z(AsyncFileSystem._put.<locals>.<dictcomp>c                    s   g | ]
\}} | r|qS r   r   r   r   ris_dirr   r   r   Q  s    c                    s    g | ]\}} | s||fqS r   r   r   r   r   r   r   R  s     c                    s   g | ]	} j |d dqS T)exist_ok)r   )r   dr   r   r   r   T  r   ry   ro   )r-   r   r   r
   r	   expand_pathrs   r   r   r   r   r   r   r   gatherry   set_sizebranch_coror   appendr   )r7   r   r   r   ro   ry   r   r2   rpathslpathsr   r   r   r   rdirs
file_pairsrx   lfilerfileput_filer   )r   r   r7   r   _put  sR   



zAsyncFileSystem._putc                    r   r   r   )r7   r   r   r2   r   r   r   r   a  r   zAsyncFileSystem._get_filec                    sh  t |trt |tr|}|}ngt |t}	|	ot| }
 |} j|||dI dH }|	rD|r4|durD fdd|D I dH }|sDdS t|}t|dk}t |to\t|p\t 	|}|	omt
|re|pmt
| om|om|
}t||||	 d}dd |D  |d j}g }|t| t||D ]\}}| j}||||fi | qt|||d	I dH S )
a  Copy file(s) to local.

        Copies a specific file or tree of files (if recursive=True). If lpath
        ends with a "/", it will be assumed to be a directory, and target files
        will go within. Can submit a list of paths, which may be glob-patterns
        and will be expanded.

        The get_file method will be called concurrently on a batch of files. The
        batch_size option can configure the amount of futures that can be executed
        at the same time. If it is -1, then all the files will be uploaded concurrently.
        The default can be set for this instance by passing "batch_size" in the
        constructor, or for all instances by setting the "gather_batch_size" key
        in ``fsspec.config.conf``, falling back to 1/8th of the system limit .
        r   Nc                    r   r   r   r   r   r   r   r     r   z(AsyncFileSystem._get.<locals>.<listcomp>r   r   c                 S   s"   g | ]}t jt j|d dqS r   )rA   makedirsr   dirname)r   lpr   r   r   r     r   ry   r   )r-   r   r   r   r   r   r
   rs   r	   r   r   r   rw   ry   r   r   r   r   r   r   )r7   r   r   r   ro   r   r2   r   r   r   source_not_trailing_sepr   r   r   ry   rx   get_filer   r   r   _getd  sR   



zAsyncFileSystem._getc                    s*   z|  |I d H d dkW S    Y dS )NtypefileF)r   r7   r   r   r   r   r     s
   zAsyncFileSystem._isfilec                    s2   z|  |I d H d dkW S  ty   Y dS w )Nr  	directoryF)r   OSErrorr  r   r   r   r     s   zAsyncFileSystem._isdirc                    s   |  |I d H dd S )Nr   )r   getr  r   r   r   r     s   zAsyncFileSystem._sizec                    s,   |p j }t fdd|D |dI d H S )Nc                       g | ]}  |qS r   )r   r   r   r   r   r         z*AsyncFileSystem._sizes.<locals>.<listcomp>)ry   )ry   r   )r7   r   ry   r   r   r   _sizes  s
   
zAsyncFileSystem._sizesc                    s6   z| j |fi |I d H  W dS  ty   Y dS w )NTF)r   r   r   r   r   r   r     s   zAsyncFileSystem._existsc                    r   r   r   r   r   r   r   r     r   zAsyncFileSystem._infoc                    r   r   r   )r7   r   detailr2   r   r   r   r     r   zAsyncFileSystem._lsr   c              
   K  s  |d ur|dk rt d| |}i }i }i }|dd}z| j|fddi|I d H }	W n1 ttfy_ }
 z#|dkr= t|rE||
 |rN|i i fV  n|g g fV  W Y d }
~
d S d }
~
ww |	D ]1}|d d}|ddd	 }|d
 dkr||kr|||< |||< qb||kr||d< qb|||< qb|r|||fV  n
|t	|t	|fV  |d ur|d8 }|dk rd S |D ]}| j
|| f||d|2 z	3 d H W }|V  q6 qd S )Nr   maxdepth must be at least 1r  FTr   rB   /rY   r  r  r   )r   r  )rb   r   rw   r   r   r  callablerstriprsplitr   r   )r7   r   r   r   r2   	full_dirsdirsfilesr  listingrm   infopathnamerB   r   rg   r   r   r   r     s`   
 


zAsyncFileSystem._walkc                    sZ  |d ur|dk rt ddd l}tjjrtjjtjjfntjjf}||}| |}|p9|tdd |D  |	ddkrF|	dnt
|}|	ddkrV|	dnt
|}|	ddkrf|	dnt
|}	t|||	}
|d	d
}t|s| j|fi |I d H r|s|gS || j|fi |I d H iS |sg S i S d|d |
 v r|d |
 d}
|d |
d  }||
d d  dd }nd}||
d d  dd }d|v r|d ur|	d}||d  dd }|| | }nd }| j|f|ddd|I d H }t||rdnd | fddt| D }|r)|S t|S )Nr   r  r   c                 s   s    | ]}|d  V  qdS )**Nr   )r   sepr   r   r   	<genexpr>  s    z(AsyncFileSystem._glob.<locals>.<genexpr>*?[r  Fr  r   r"  T)r   withdirsr  c                    s8   i | ]\}}  r|d  dkr|d n|r||qS )r  r  r  )match)r   r   r   append_slash_to_dirnamepatternr   r   r   ;  s    z)AsyncFileSystem._glob.<locals>.<dictcomp>)rb   rerA   r   altsepr#  endswithr   tuplefindrs   minrw   r   r   r   rindexcountr   r   compilesortedr   r   )r7   r   r   r2   r-  sepsends_with_sepidx_star	idx_qmark	idx_bracemin_idxr  rootdepthidx_double_starsdepth_double_starsallpathsr   r   r*  r   r     sd   "

   



zAsyncFileSystem._globc                    s\   i }| j |fd|i|I d H D ]}| |I d H }|d ||d < q|r,t| S |S )Nr   r   rB   )r   r   sumvalues)r7   r   totalr   r2   sizesfr   r   r   r   r   J  s    zAsyncFileSystem._duc           
         s   |  |}i  |dd}|r&|dkr&| |I d H r&| |I d H  |< | j||fddi|2 z3 d H W \}}}|rB||  dd | D  q26  s^| |I d H r^i  |< t }	|sf|	S  fdd|	D S )Nr  Fr   Tc                 S   s   i | ]	\}}|d  |qS )rB   r   )r   rB   r   r   r   r   r   c  r   z)AsyncFileSystem._find.<locals>.<dictcomp>c                    s   i | ]}| | qS r   r   )r   rB   r   r   r   r   l  r  )	r   rw   r   r   r   updater   r   r6  )
r7   r   r   r(  r2   r  rg   r  r  namesr   rG  r   r   U  s"   
*
zAsyncFileSystem._findc                    s4  |d ur|dk rt dt|tr |g||I d H }nrt } fdd|D }|D ]c}t|rgt j||dI d H }||O }|rf|d urM|dkrMq,|t jt|||d ur]|d nd dI d H O }q,|rzt j||ddI d H }||O }||vr|d	u s 	|I d H r|
| q,|st|t|S )
Nr   r  c                    r  r   )r   r   r   r   r   r   v  r  z0AsyncFileSystem._expand_path.<locals>.<listcomp>)r   r   T)r   r(  F)rb   r-   r   r   r   r   r   r   r   r   rt   r   r6  )r7   r   r   r   r   r   bitrecr   r   r   r   n  s>   

 
zAsyncFileSystem._expand_pathc                       d S r   r   )r7   r   create_parentsr2   r   r   r   r     r   zAsyncFileSystem._mkdirc                    rL  r   r   )r7   r   r   r   r   r   r     r   zAsyncFileSystem._makedirsrbc                    s   d|vs
| drtt)Nbcompression)r  rb   r)   )r7   r   r   r2   r   r   r   
open_async  s   zAsyncFileSystem.open_async)FN)FNNN)r   )NN)Fr   N)NNri   r   )T)Nr   )TN)NFF)rN  )*__name__
__module____qualname____doc__
async_implmirror_sync_methodsdisable_throttlingr   propertyr   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   r   r   r   rQ  __classcell__r   r   r   r   r   6  sj    





<





)
J
I



6
E


%
r   c                 C   s   ddl m} ttt D ]O}|dsq|dd }t|r[t	t
| |d}t
t
| |ddd}|t
||du }|r[|r[tt
| || d	}t| || |js[t
t
||dd
d|_qdS )a,  Populate sync and async methods for obj

    For each method will create a sync version if the name refers to an async method
    (coroutine) and there is no override in the child class; will create an async
    method for the corresponding sync method if there is no implementation.

    Uses the methods specified in
    - async_methods: the set that an implementation is expected to provide
    - default_async_methods: that can be derived from their sync version in
      AbstractFileSystem
    - AsyncFileSystem: async-specific default coroutines
    r   )r   rg   r   NF__func__r   )r9   rV  )fsspecr   async_methodsdirr   
startswithprivater)  inspectiscoroutinefunctiongetattrr=   setattrrV  )r9   r   methodsmethodiscounsync
is_defaultmthr   r   r   rX    s$   

rX  c                   @   s   e Zd ZdS )FSSpecCoroutineCancelN)rS  rT  rU  r   r   r   r   rl    s    rl  Tc              	      s   dd l dd tjtd D }| rdd |D  fdd|D }|r[|D ]2  j}   tjj	 | tjj   fdd|D  z j
| W q( |yZ   Y q(w |S )Nr   c                 S   s   g | ]}|  s|qS r   )r}   )r   tr   r   r   r         z'_dump_running_tasks.<locals>.<listcomp>c                 S   s   g | ]}|  qS r   )print_stackr   taskr   r   r   r     s    c              	      sL   g | ]"}|j jj|j jjj|j jjj|j jj |j jr |nd dqS )N)localsr  	firstlinelinelostackrq  )_corocr_framef_localsf_codeco_filenameco_firstlinenof_linenoformat_stackrp  )	traceback	with_taskr   r   r     s    	


c                    s   g | ]}|d   qS )r   r   )r   cb)rm  r   r   r     rn  )r~  r   tasks	all_tasksr   
_callbackscancelfuturesFutureset_exceptionrv  throw)printoutr  excr  r  r   cbsr   )rm  r~  r  r   _dump_running_tasks  s(   	r  c                   @   sZ   e Zd ZdddZdd Zdd Zdd	d
Zdd Zdd Zdd Z	dd Z
dddZdS )AbstractAsyncStreamedFilerY   c                    s   |du rdnt |}| jdkrtd|dk r| j| j }| jr%td|dkr+dS | | j| j| I dH }|  jt|7  _|S )z
        Return data from cache, or fetch pieces as necessary

        Parameters
        ----------
        length: int (-1)
            Number of bytes to read; if <0, all remaining bytes.
        NrY   rN  zFile not in read moder   I/O operation on closed file.    )intr   rb   r   locclosed_fetch_rangers   )r7   lengthr   r   r   r   read  s   	
zAbstractAsyncStreamedFile.readc                    sl   | j dvr
td| jrtd| jrtd| j|}|  j|7  _| j | jkr4| 	 I dH  |S )z
        Write data to buffer.

        Buffer only sent on flush() or if buffer is greater than
        or equal to blocksize.

        Parameters
        ----------
        data: bytes
            Set of bytes to be written.
        >   abwbzFile not in write moder  z0This file has been force-flushed, can only closeN)
r   rb   r  forcedbufferwriter  tell	blocksizeflush)r7   datar   r   r   r   r    s   
zAbstractAsyncStreamedFile.writec                    s~   t | ddr	dS | jrdS | jdkrd| _n#| js#| jddI dH  | jdur:| j| j | j| j	| j d| _dS )z=Close file

        Finalizes writes, discards cache
        _unclosableFNrN  T)force)
rd  r  r   cacher  r  r   invalidate_cacher   _parentr   r   r   r   close  s   


zAbstractAsyncStreamedFile.closeFc                    s   | j rtd|r| jrtd|rd| _| jdvrd S |s)| j | jk r)d S | jd u rBd| _z	|  I d H  W n   d| _  | j	|dI d H dur`|  j| j
dd7  _t | _d S d S )	NzFlush on closed filez+Force flush cannot be called more than onceT>   r  r  r   )finalF   )r  rb   r  r   r  r  r  offset_initiate_upload_upload_chunkseekioBytesIO)r7   r  r   r   r   r  ,  s,   


zAbstractAsyncStreamedFile.flushc                    s   | S r   r   r   r   r   r   
__aenter__I  r   z$AbstractAsyncStreamedFile.__aenter__c                    s   |   I d H  d S r   )r  )r7   exc_typeexc_valexc_tbr   r   r   	__aexit__L  s   z#AbstractAsyncStreamedFile.__aexit__c                    r   r   r   )r7   rM   r   r   r   r   r  O  r   z&AbstractAsyncStreamedFile._fetch_rangec                    rL  r   r   r   r   r   r   r  R  r   z*AbstractAsyncStreamedFile._initiate_uploadc                    r   r   r   )r7   r  r   r   r   r  U  r   z'AbstractAsyncStreamedFile._upload_chunkN)rY   rR  )rS  rT  rU  r  r  r  r  r  r  r  r  r  r   r   r   r   r    s    

r  r   rR  )Br   asyncio.eventsr;   rb  r  r   rA   r-  r   
contextlibr   globr   typingr   r   	callbacksr   
exceptionsr   implementations.localr	   r
   r   specr   r   utilsr   r   r   r5  ra  r   r   r   r(   r   r   r$   r5   r=   rF   rO   rQ   rC   rR   r]   rT   rc   ra   r  rd  r^   r\   rh   boolrj   r   r^  r   rX  r   rl  r  r  r   r   r   r   <module>   s    


-



F    m 
!