a
    %Dfp                  	   @  s  U d dl m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
mZ d dlmZmZmZmZmZmZmZmZ erd dlZd dlmZ edZnedZedZedZeeegef ZG d	d
 d
ZG dd deZ G dd deZ!G dd deZ"G dd deZ#G dd deZ$G dd deZ%G dd deZ&G dd deeef Z'G dd deZ(deiZ)de*d< d&d d!d"d#d$d%Z+ee e$e!e#e"e%e&e(f	D ]Z,e+e, qdS )'    )annotationsN)FutureThreadPoolExecutor)TYPE_CHECKINGAnyCallableClassVarGeneric
NamedTupleOrderedDictTypeVar)	ParamSpecPTZfsspecc                   @  sD   e Zd ZU dZdZded< dddddd	d
ZddddddZdS )	BaseCacheag  Pass-though cache: doesn't keep anything, calls every time

    Acts as base class for other cachers

    Parameters
    ----------
    blocksize: int
        How far to read ahead in numbers of bytes
    fetcher: func
        Function of the form f(start, end) which gets bytes from remote as
        specified
    size: int
        How big this file is
    noneClassVar[str]nameintFetcherNone	blocksizefetchersizereturnc                 C  s   || _ || _|| _d S N)r   r   r   selfr   r   r    r   [/nfs/NAS7/SABIOD/METHODE/ermites/ermites_venv/lib/python3.9/site-packages/fsspec/caching.py__init__9   s    zBaseCache.__init__
int | Nonebytesstartstopr   c                 C  s<   |d u rd}|d u r| j }|| j ks,||kr0dS | ||S Nr       )r   r   r   r%   r&   r   r   r    _fetch>   s    zBaseCache._fetchN)__name__
__module____qualname____doc__r   __annotations__r!   r*   r   r   r   r    r   '   s   
r   c                      st   e Zd ZdZdZdddddddd	 fd
dZddddZddddddZddddZdddddZ	  Z
S )	MMapCachezmemory-mapped sparse file cache

    Opens temporary file, which is filled blocks-wise when data is requested.
    Ensure there is enough disc space in the temporary location.

    This cache method might only work on posix
    mmapNr   r   z
str | Nonezset[int] | Noner   )r   r   r   locationblocksr   c                   s8   t  ||| |d u rt n|| _|| _|  | _d S r   )superr!   setr3   r2   	_makefilecache)r   r   r   r   r2   r3   	__class__r   r    r!   S   s    zMMapCache.__init__zmmap.mmap | bytearrayr   c                 C  s   dd l }dd l}| jdkr t S | jd u s8tj| js| jd u rT| }t	 | _
nt| jd}|| jd  |d |  nt| jd}| | | jS )Nr   zwb+      1zr+b)r1   tempfiler   	bytearrayr2   ospathexistsTemporaryFiler5   r3   openseekwriteflushfileno)r   r1   r=   fdr   r   r    r6   `   s    




zMMapCache._makefiler"   r#   r%   endr   c           	        s   t d| d|  |d u r"d}|d u r0 j}| jksB||krFdS | j }| j } fddt||d D }|r|d}| j }t| j  j}t d| d	| d|   || j||<  j	
| qv j|| S )
NzMMap cache fetching -r   r(   c                   s   g | ]}| j vr|qS r   )r3   ).0ir   r   r    
<listcomp>   r(   z$MMapCache._fetch.<locals>.<listcomp>r;   zMMap get block #z ()loggerdebugr   r   rangepopminr   r7   r3   add)	r   r%   rJ   Zstart_blockZ	end_blockZneedrM   Zsstartsendr   rN   r    r*   v   s$    



zMMapCache._fetchdict[str, Any]c                 C  s   | j  }|d= |S )Nr7   )__dict__copyr   stater   r   r    __getstate__   s    
zMMapCache.__getstate__r[   r   c                 C  s   | j | |  | _d S r   )rX   updater6   r7   rZ   r   r   r    __setstate__   s    zMMapCache.__setstate__)NN)r+   r,   r-   r.   r   r!   r6   r*   r\   r_   __classcell__r   r   r8   r    r0   H   s     r0   c                      sB   e Zd ZdZdZddddd fddZd	d	d
dddZ  ZS )ReadAheadCachea!  Cache which reads only when we get beyond a block of data

    This is a much simpler version of BytesCache, and does not attempt to
    fill holes in the cache or keep fragments alive. It is best suited to
    many small reads in a sequential order (e.g., reading lines from a file).
    Z	readaheadr   r   r   r   c                   s&   t  ||| d| _d| _d| _d S )Nr(   r   )r4   r!   r7   r%   rJ   r   r8   r   r    r!      s    zReadAheadCache.__init__r"   r#   rI   c                 C  s  |d u rd}|d u s|| j kr$| j }|| j ks6||kr:dS || }|| jkrp|| jkrp| j|| j || j  S | j|  kr| jk rn n(| j|| j d  }|t|8 }| j}nd}t| j || j }| ||| _|| _| jt| j | _|| jd |  S r'   )r   r%   rJ   r7   lenrT   r   r   )r   r%   rJ   lpartr   r   r    r*      s&    zReadAheadCache._fetchr+   r,   r-   r.   r   r!   r*   r`   r   r   r8   r    ra      s   ra   c                      sB   e Zd ZdZdZddddd fddZd	d	d
dddZ  ZS )FirstChunkCachezCaches the first block of a file only

    This may be useful for file types where the metadata is stored in the header,
    but is randomly accessed.
    firstr   r   r   r   c                   s   t  ||| d | _d S r   )r4   r!   r7   r   r8   r   r    r!      s    zFirstChunkCache.__init__r"   r#   rI   c                 C  s   |pd}|p| j }|| jk r| jd u rh|| jkrX| d|}|d | j | _||d  S | d| j| _| j|| }|| jkr|| | j|7 }|S | ||S d S Nr   )r   r   r7   r   )r   r%   rJ   datard   r   r   r    r*      s    




zFirstChunkCache._fetchre   r   r   r8   r    rf      s   rf   c                      s   e Zd ZdZdZd!dddddd fdd	Zd
dddZdd ZddddZdddddZ	ddddddZ
ddd fddZdddddddd Z  ZS )"
BlockCachea  
    Cache holding memory as a set of blocks.

    Requests are only ever made ``blocksize`` at a time, and are
    stored in an LRU cache. The least recently accessed block is
    discarded when more than ``maxblocks`` are stored.

    Parameters
    ----------
    blocksize : int
        The number of bytes to store in each block.
        Requests are only ever made for ``blocksize``, so this
        should balance the overhead of making a request against
        the granularity of the blocks.
    fetcher : Callable
    size : int
        The total size of the file being cached.
    maxblocks : int
        The maximum number of blocks to cache for. The maximum memory
        use for this cache is then ``blocksize * maxblocks``.
    Z
blockcache    r   r   r   r   r   r   	maxblocksr   c                   s<   t  ||| t|| | _|| _t|| j| _	d S r   )
r4   r!   mathceilnblocksrm   	functools	lru_cache_fetch_block_fetch_block_cachedr   r   r   r   rm   r8   r   r    r!      s    zBlockCache.__init__strr:   c                 C  s   d| j  d| j d| j dS )Nz<BlockCache blocksize=, size=
, nblocks=>r   r   rp   rN   r   r   r    __repr__  s    
zBlockCache.__repr__c                 C  s
   | j  S z
        The statistics on the block cache.

        Returns
        -------
        NamedTuple
            Returned directly from the LRU Cache used internally.
        rt   
cache_inforN   r   r   r    r~   	  s    	zBlockCache.cache_inforW   c                 C  s   | j }|d= |S )Nrt   rX   rZ   r   r   r    r\     s    zBlockCache.__getstate__r]   c                 C  s&   | j | t|d | j| _d S )Nrm   )rX   r^   rq   rr   rs   rt   rZ   r   r   r    r_     s    zBlockCache.__setstate__r"   r#   rI   c                 C  st   |d u rd}|d u r| j }|| j ks,||kr0dS || j }|| j }t||d D ]}| | qR| j||||dS )Nr   r(   r;   start_block_numberend_block_number)r   r   rR   rt   _read_cache)r   r%   rJ   r   r   block_numberr   r   r    r*     s     

zBlockCache._fetch)r   r   c                   sT   || j kr"td| d| j  d|| j }|| j }td| t ||}|S )=
        Fetch the block of data for `block_number`.
        'block_number=(' is greater than the number of blocks ()zBlockCache fetching block %drp   
ValueErrorr   rP   infor4   r*   )r   r   r%   rJ   block_contentsr8   r   r    rs   6  s    


zBlockCache._fetch_blockr%   rJ   r   r   r   c           	      C  s   || j  }|| j  }||kr2| |}||| S | ||d g}|t| jt|d | || |d|  d|S dS z
        Read from our block cache.

        Parameters
        ----------
        start, end : int
            The start and end byte positions.
        start_block_number, end_block_number : int
            The start and end block numbers.
        Nr;   r(   r   rt   extendmaprR   appendjoin	r   r%   rJ   r   r   Z	start_posZend_posblockoutr   r   r    r   F  s    


zBlockCache._read_cache)rk   )r+   r,   r-   r.   r   r!   r{   r~   r\   r_   r*   rs   r   r`   r   r   r8   r    rj      s    rj   c                      s^   e Zd ZU dZdZded< dddddd	d
 fddZddddddZddddZ  Z	S )
BytesCacheaK  Cache which holds data in a in-memory bytes object

    Implements read-ahead by the block size, for semi-random reads progressing
    through the file.

    Parameters
    ----------
    trim: bool
        As we read more data, whether to discard the start of the buffer when
        we are more than a blocksize ahead of it.
    r#   r   r   Tr   r   boolr   )r   r   r   trimr   c                   s,   t  ||| d| _d | _d | _|| _d S )Nr(   )r4   r!   r7   r%   rJ   r   )r   r   r   r   r   r8   r   r    r!   }  s
    zBytesCache.__init__r"   rI   c                 C  s\  |d u rd}|d u r| j }|| j ks,||kr0dS | jd urx|| jkrx| jd urx|| jk rx|| j }| j||| |  S | jrt| j || j }n|}||ks|| j krdS | jd u s|| jk r| jd u s|| jkr| ||| _|| _n| jd usJ | jd usJ || jk rj| jd u s2| j| | jkrH| ||| _|| _n | || j}|| _|| j | _nj| jd ur|| jkr| j| j krnB|| j | jkr| ||| _|| _n| | j|}| j| | _| jt| j | _|| j }| j||| |  }| jrX| j| j | jd  }|dkrX|  j| j| 7  _| j| j| d  | _|S )Nr   r(   r;   )	r   r%   rJ   r7   r   rT   r   rb   r   )r   r%   rJ   offsetZbendnewr   numr   r   r    r*     sl    


zBytesCache._fetchr:   c                 C  s
   t | jS r   )rb   r7   rN   r   r   r    __len__  s    zBytesCache.__len__)T)
r+   r,   r-   r.   r   r/   r!   r*   r   r`   r   r   r8   r    r   n  s   
 	Ar   c                      sP   e Zd ZU dZdZded< dddddd	d
 fddZddddddZ  ZS )AllBytesz!Cache entire contents of the fileallr   r   Nr"   zFetcher | Nonezbytes | Noner   )r   r   r   ri   r   c                   s0   t  ||| |d u r&| d| j}|| _d S rh   )r4   r!   r   r   ri   )r   r   r   r   ri   r8   r   r    r!     s    zAllBytes.__init__r#   r$   c                 C  s   | j || S r   )ri   r)   r   r   r    r*     s    zAllBytes._fetch)NNNN	r+   r,   r-   r.   r   r/   r!   r*   r`   r   r   r8   r    r     s   
    r   c                      sZ   e Zd ZU dZdZded< i dfddddd	d
d fddZdddd fddZ  ZS )KnownPartsOfAFilea  
    Cache holding known file parts.

    Parameters
    ----------
    blocksize: int
        How far to read ahead in numbers of bytes
    fetcher: func
        Function of the form f(start, end) which gets bytes from remote as
        specified
    size: int
        How big this file is
    data: dict
        A dictionary mapping explicit `(start, stop)` file-offset tuples
        with known bytes.
    strict: bool, default True
        Whether to fetch reads that go beyond a known byte-range boundary.
        If `False`, any read that ends outside a known part will be zero
        padded. Note that zero padding will not be used for reads that
        begin outside a known byte-range.
    partsr   r   Tr   r   zdict[tuple[int, int], bytes]r   r   )r   r   r   ri   strict_c                   s   t  ||| || _|rt| }|d g}||d g}	|dd  D ]f\}
}|d \}}|
|kr||f|d< |	d  ||
|f7  < qL||
|f |	||
|f qLtt||	| _	n|| _	d S )Nr   r;   )
r4   r!   r   sortedkeysrS   r   dictzipri   )r   r   r   r   ri   r   r   Zold_offsetsoffsetsr3   r%   r&   Zstart0Zstop0r8   r   r    r!     s    	
zKnownPartsOfAFile.__init__r"   r#   r$   c                   s  |d u rd}|d u r| j }d}| j D ]\\}}}||  krH|k r(n q(|| }|||| |  }| jr||  kr|krn n |d|| t|  7 }|  S |} qq(| jd u rtd||f dtd||f d t	
d| d|  |t || S )	Nr   r(       z&Read is outside the known file parts: z. z%. IO/caching performance may be poor!z!KnownPartsOfAFile cache fetching rK   )r   ri   itemsr   rb   r   r   warningswarnrP   rQ   r4   r*   )r   r%   r&   r   Zloc0loc1ri   offr8   r   r    r*     s*    
zKnownPartsOfAFile._fetchr   r   r   r8   r    r     s   
r   c                   @  sv   e Zd ZdZG dd deZdddddd	d
ZddddddZdddddZddddddZ	ddddZ
dS )UpdatableLRUzg
    Custom implementation of LRU cache that allows updating keys

    Used by BackgroudBlockCache
    c                   @  s.   e Zd ZU ded< ded< ded< ded< dS )UpdatableLRU.CacheInfor   hitsmissesmaxsizecurrsizeN)r+   r,   r-   r/   r   r   r   r    	CacheInfoI  s   
r      zCallable[P, T]r   r   )funcmax_sizer   c                 C  s0   t  | _|| _|| _d| _d| _t | _	d S rh   )
collectionsr   _cache_func	_max_size_hits_misses	threadingLock_lock)r   r   r   r   r   r    r!   O  s    
zUpdatableLRU.__init__zP.argszP.kwargsr   )argskwargsr   c                 O  s   |rt d|  | jL || jv rZ| j| |  jd7  _| j| W  d    S W d    n1 sn0    Y  | j|i |}| jF || j|< |  jd7  _t| j| j	kr| jj
dd W d    n1 s0    Y  |S )Nz Got unexpected keyword argument r;   Flast)	TypeErrorr   r   r   move_to_endr   r   r   rb   r   popitem)r   r   r   resultr   r   r    __call__W  s    
6
,zUpdatableLRU.__call__r   r   )r   r   c                 G  s4   | j  || jv W  d    S 1 s&0    Y  d S r   )r   r   )r   r   r   r   r    is_key_cachedj  s    zUpdatableLRU.is_key_cached)r   r   r   c                 G  sR   | j 8 || j|< t| j| jkr0| jjdd W d    n1 sD0    Y  d S )NFr   )r   r   rb   r   r   )r   r   r   r   r   r    add_keyn  s    
zUpdatableLRU.add_keyr   r:   c                 C  sH   | j . | j| jt| j| j| jdW  d    S 1 s:0    Y  d S )N)r   r   r   r   )r   r   r   rb   r   r   r   rN   r   r   r    r~   t  s    zUpdatableLRU.cache_infoN)r   )r+   r,   r-   r.   r
   r   r!   r   r   r   r~   r   r   r   r    r   B  s   r   c                      s   e Zd ZU dZdZded< d$dddddd	 fd
dZddddZddddZddddZ	ddddZ
ddddddZd%dddd fdd Zdddddd!d"d#Z  ZS )&BackgroundBlockCachea  
    Cache holding memory as a set of blocks with pre-loading of
    the next block in the background.

    Requests are only ever made ``blocksize`` at a time, and are
    stored in an LRU cache. The least recently accessed block is
    discarded when more than ``maxblocks`` are stored. If the
    next block is not in cache, it is loaded in a separate thread
    in non-blocking way.

    Parameters
    ----------
    blocksize : int
        The number of bytes to store in each block.
        Requests are only ever made for ``blocksize``, so this
        should balance the overhead of making a request against
        the granularity of the blocks.
    fetcher : Callable
    size : int
        The total size of the file being cached.
    maxblocks : int
        The maximum number of blocks to cache for. The maximum memory
        use for this cache is then ``blocksize * maxblocks``.
    Z
backgroundr   r   rk   r   r   r   rl   c                   sZ   t  ||| t|| | _|| _t| j|| _t	dd| _
d | _d | _t | _d S )Nr;   max_workers)r4   r!   rn   ro   rp   rm   r   rs   rt   r   _thread_executor_fetch_future_block_number_fetch_futurer   r   _fetch_future_lockru   r8   r   r    r!     s    zBackgroundBlockCache.__init__rv   r:   c                 C  s   d| j  d| j d| j dS )Nz <BackgroundBlockCache blocksize=rw   rx   ry   rz   rN   r   r   r    r{     s    
zBackgroundBlockCache.__repr__r   c                 C  s
   | j  S r|   r}   rN   r   r   r    r~     s    	zBackgroundBlockCache.cache_inforW   c                 C  s(   | j }|d= |d= |d= |d= |d= |S )Nrt   r   r   r   r   r   rZ   r   r   r    r\     s    z!BackgroundBlockCache.__getstate__c                 C  sD   | j | t| j|d | _tdd| _d | _d | _t	
 | _d S )Nrm   r;   r   )rX   r^   r   rs   rt   r   r   r   r   r   r   r   rZ   r   r   r    r_     s    z!BackgroundBlockCache.__setstate__r"   r#   rI   c           
      C  s  |d u rd}|d u r| j }|| j ks,||kr0dS || j }|| j }d }d }| j | jd ur| jd uslJ | j rtd | j	| j
 | j d | _d | _n:t|| j  ko|kn  }|r| j}| j}d | _d | _W d    n1 s0    Y  |d ur"td | j	|
 | t||d D ]}| | q0|d }	| jP | jd u r|	| jkr| j|	s|	| _| j| j|	d| _W d    n1 s0    Y  | j||||dS )Nr   r(   z3BlockCache joined background fetch without waiting.z(BlockCache waiting for background fetch.r;   asyncr   )r   r   r   r   r   donerP   r   rt   r   r   r   rR   rp   r   r   Zsubmitrs   r   )
r   r%   rJ   r   r   Zfetch_future_block_numberZfetch_futureZ	must_joinr   Zend_block_plus_1r   r   r    r*     sr    




$


&zBackgroundBlockCache._fetchsync)r   log_infor   c                   sV   || j kr"td| d| j  d|| j }|| j }td|| t ||}|S )r   r   r   r   z!BlockCache fetching block (%s) %dr   )r   r   r   r%   rJ   r   r8   r   r    rs     s    


z!BackgroundBlockCache._fetch_blockr   c           	      C  s   || j  }|| j  }||kr2| |}||| S | ||d g}|t| jt|d | || |d|  d|S dS r   r   r   r   r   r    r   %  s    


z BackgroundBlockCache._read_cache)rk   )r   )r+   r,   r-   r.   r   r/   r!   r{   r~   r\   r_   r*   rs   r   r`   r   r   r8   r    r   ~  s   
 	Lr   z!dict[str | None, type[BaseCache]]cachesFztype[BaseCache]r   r   )clsclobberr   c                 C  s6   | j }|s*|tv r*td|dt|  | t|< dS )z'Register' cache implementation.

    Parameters
    ----------
    clobber: bool, optional
        If set to True (default is False) - allow to overwrite existing
        entry.

    Raises
    ------
    ValueError
    zCache with name z is already known: N)r   r   r   )r   r   r   r   r   r    register_cacheS  s    r   )F)-
__future__r   r   rq   loggingrn   r?   r   r   concurrent.futuresr   r   typingr   r   r   r   r	   r
   r   r   r1   Ztyping_extensionsr   r   r   	getLoggerrP   r   r#   r   r   r0   ra   rf   rj   r   r   r   r   r   r   r/   r   cr   r   r   r    <module>   sV   (

!Q* ]b< R