o
    h:                     @   s|   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 d dl	m
Z
 G dd deZG dd deZG d	d
 d
e
ZdS )    N)HTTPAdapterRetry)AbstractFileSystem)AbstractBufferedFilec                       s    e Zd ZdZ fddZ  ZS )DatabricksExceptionz<
    Helper class for exceptions raised in this module.
    c                    s   t  | || _|| _dS )z Create a new DatabricksExceptionN)super__init__
error_codemessage)selfr	   r
   	__class__ o/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/fsspec/implementations/dbfs.pyr      s   
zDatabricksException.__init__)__name__
__module____qualname____doc__r   __classcell__r   r   r   r   r      s    r   c                       s   e Zd ZdZ fddZd!ddZd!ddZd!d	d
Zd"ddZ	d#ddZ	d$ddZ
dd Zd!ddZdd Zdd Zdd Zd% fdd 	Z  ZS )&DatabricksFileSystemz
    Get access to the Databricks filesystem implementation over HTTP.
    Can be used inside and outside of a databricks cluster.
    c                    sp   || _ || _t | _tddg dd| _| jdt| jd | jj	
dd| j i t jd
i | d	S )a  
        Create a new DatabricksFileSystem.

        Parameters
        ----------
        instance: str
            The instance URL of the databricks cluster.
            For example for an Azure databricks cluster, this
            has the form adb-<some-number>.<two digits>.azuredatabricks.net.
        token: str
            Your personal token. Find out more
            here: https://docs.databricks.com/dev-tools/api/latest/authentication.html
        
   g?)i  i  i  i  i  i  )totalbackoff_factorstatus_forcelisthttps://)max_retriesAuthorizationzBearer Nr   )instancetokenrequestsSessionsessionr   retriesmountr   headersupdater   r   )r   r   r   kwargsr   r   r   r      s   
zDatabricksFileSystem.__init__Tc              
   K   s   |  |}|s<z| jddd|id}W n ty+ } z|jdkr&t|j| d}~ww |d }dd	 |D }|| j|< |r@|S d
d	 |D S )a"  
        List the contents of the given path.

        Parameters
        ----------
        path: str
            Absolute path
        detail: bool
            Return not only the list of filenames,
            but also additional information on file sizes
            and types.
        getlistpathmethodendpointjsonRESOURCE_DOES_NOT_EXISTNfilesc                 S   s,   g | ]}|d  |d rdnd|d dqS )r)   is_dir	directoryfile	file_size)nametypesizer   .0or   r   r   
<listcomp>T   s    z+DatabricksFileSystem.ls.<locals>.<listcomp>c                 S   s   g | ]}|d  qS )r4   r   r7   r   r   r   r:   `   s    )_ls_from_cache_send_to_apir   r	   FileNotFoundErrorr
   dircache)r   r)   detailr&   outrer/   r   r   r   ls;   s(   




zDatabricksFileSystem.lsc              
   C   s   |s-z| j ddd|id td| d ty, } z|jdkr"	 W Y d}~nd}~ww z| j d	d
d|id W n tyQ } z|jdkrLt|j| d}~ww | | | dS )aE  
        Create a given absolute path and all of its parents.

        Parameters
        ----------
        path: str
            Absolute path to create
        exist_ok: bool
            If false, checks if the folder
            exists before creating it (and raises an
            Exception if this is the case)
        r'   z
get-statusr)   r*   zPath z already existsr.   NpostmkdirsRESOURCE_ALREADY_EXISTS)r<   FileExistsErrorr   r	   r
   invalidate_cache_parent)r   r)   exist_okrB   r   r   r   makedirsb   s(   


zDatabricksFileSystem.makedirsc                 K   s   |st | j|fi | dS )a!  
        Create a given absolute path and all of its parents.

        Parameters
        ----------
        path: str
            Absolute path to create
        create_parents: bool
            Whether to create all parents or not.
            "False" is not implemented so far.
        N)NotImplementedErrorrE   )r   r)   create_parentsr&   r   r   r   mkdir   s   zDatabricksFileSystem.mkdirFc              
   K   sz   z| j dd||dd W n% ty2 } z|jdkr"| j||d  |jdkr-t|j| d}~ww | | | dS )z
        Remove the file or folder at the given absolute path.

        Parameters
        ----------
        path: str
            Absolute path what to remove
        recursive: bool
            Recursively delete all files in a folder.
        rD   delete)r)   	recursiver*   PARTIAL_DELETEIO_ERRORN)r<   r   r	   rmOSErrorr
   rH   rI   )r   r)   rP   r&   rB   r   r   r   rS      s    



zDatabricksFileSystem.rmNc              
   K   s   |rt |rt z| jdd||dd W n# ty8 } z|jdkr(t|j||jdkr3t|j| d}~ww | | | | | | dS )a  
        Move a source to a destination path.

        A note from the original [databricks API manual]
        (https://docs.databricks.com/dev-tools/api/latest/dbfs.html#move).

        When moving a large number of files the API call will time out after
        approximately 60s, potentially resulting in partially moved data.
        Therefore, for operations that move more than 10k files, we strongly
        discourage using the DBFS REST API.

        Parameters
        ----------
        source_path: str
            From where to move (absolute path)
        destination_path: str
            To where to move (absolute path)
        recursive: bool
            Not implemented to far.
        maxdepth:
            Not implemented to far.
        rD   move)source_pathdestination_pathr*   r.   rF   N)	rL   r<   r   r	   r=   r
   rG   rH   rI   )r   rV   rW   rP   maxdepthr&   rB   r   r   r   mv   s(   


zDatabricksFileSystem.mvrbdefaultc                 K   s   t | |f||d|S )z
        Overwrite the base class method to make sure to create a DBFile.
        All arguments are copied from the base method.

        Only the default blocksize is allowed.
        )mode
block_size)DatabricksFile)r   r)   r\   r]   r&   r   r   r   _open   s   zDatabricksFileSystem._openc           	      C   s   |dkr	| j j}n|dkr| j j}ntd| tjd| j d|}|||d}z	|  W | S  t	j
y[ } zz|j }W n
 tyN   |dw tdi ||d}~ww )	a  
        Send the given json to the DBFS API
        using a get or post request (specified by the argument `method`).

        Parameters
        ----------
        method: str
            Which http method to use for communication; "get" or "post".
        endpoint: str
            Where to send the request to (last part of the API URL)
        json: dict
            Dictionary of information to send
        rD   r'   zDo not understand method r   z/api/2.0/dbfs/)r-   Nr   )r!   rD   r'   
ValueErrorurllibparseurljoinr   raise_for_statusr   	HTTPErrorresponser-   	Exceptionr   )	r   r+   r,   r-   session_callurlrA   rB   exception_jsonr   r   r   r<      s&   


z!DatabricksFileSystem._send_to_apic              
   C   sR   z| j dd||dd}|d W S  ty( } z|jdkr#t|j| d}~ww )a{  
        Internal function to create a handle, which can be used to
        write blocks of a file to DBFS.
        A handle has a unique identifier which needs to be passed
        whenever written during this transaction.
        The handle is active for 10 minutes - after that a new
        write transaction needs to be created.
        Make sure to close the handle after you are finished.

        Parameters
        ----------
        path: str
            Absolute path for this file.
        overwrite: bool
            If a file already exist at this location, either overwrite
            it or raise an exception.
        rD   create)r)   	overwriter*   handlerF   N)r<   r   r	   rG   r
   )r   r)   rl   rA   rB   r   r   r   _create_handle  s   

z#DatabricksFileSystem._create_handlec              
   C   sL   z| j ddd|id W dS  ty% } z|jdkr t|j| d}~ww )z
        Close a handle, which was opened by :func:`_create_handle`.

        Parameters
        ----------
        handle: str
            Which handle to close.
        rD   closerm   r*   r.   N)r<   r   r	   r=   r
   )r   rm   rB   r   r   r   _close_handle0  s   	
z"DatabricksFileSystem._close_handlec              
   C   sr   t | }z| jdd||dd W dS  ty8 } z|jdkr(t|j||jdkr3t|j| d}~ww )a  
        Upload data to an already opened file handle
        (opened by :func:`_create_handle`).
        The maximal allowed data size is 1MB after
        conversion to base64.
        Remember to close the handle when you are finished.

        Parameters
        ----------
        handle: str
            Which handle to upload data to.
        data: bytes
            Block of data to add to the handle.
        rD   z	add-blockrm   datar*   r.   MAX_BLOCK_SIZE_EXCEEDEDN)	base64	b64encodedecoder<   r   r	   r=   r
   r`   )r   rm   rr   rB   r   r   r   	_add_dataA  s   

zDatabricksFileSystem._add_datac              
   C   st   z| j dd|||| dd}t|d W S  ty9 } z|jdkr)t|j||jdv r4t|j| d}~ww )	a  
        Download data in bytes from a given absolute path in a block
        from [start, start+length].
        The maximum number of allowed bytes to read is 1MB.

        Parameters
        ----------
        path: str
            Absolute path to download data from
        start: int
            Start position of the block
        end: int
            End position of the block
        r'   read)r)   offsetlengthr*   rr   r.   )INVALID_PARAMETER_VALUEMAX_READ_SIZE_EXCEEDEDN)r<   rt   	b64decoder   r	   r=   r
   r`   )r   r)   startendrA   rB   r   r   r   	_get_data_  s   

zDatabricksFileSystem._get_datac                    s2   |d u r
| j   n| j |d  t | d S N)r>   clearpopr   rH   )r   r)   r   r   r   rH   }  s   z%DatabricksFileSystem.invalidate_cache)TF)FN)rZ   r[   r   )r   r   r   r   r   rC   rK   rN   rS   rY   r_   r<   rn   rp   rw   r   rH   r   r   r   r   r   r      s     

'
!


.	
)r   c                       sT   e Zd ZdZdZ					d fdd		Zd
d ZdddZdd ZdddZ	  Z
S )r^   zH
    Helper class for files referenced in the DatabricksFileSystem.
    i   rZ   r[   T	readaheadNc           	         sX   |du s|dkr| j }|| j ksJ d| t j||f|||||p$i d| dS )zr
        Create a new instance of the DatabricksFile.

        The blocksize needs to be the default one.
        Nr[   z,Only the default block size is allowed, not )r\   r]   
autocommit
cache_typecache_options)DEFAULT_BLOCK_SIZEr   r   )	r   fsr)   r\   r]   r   r   r   r&   r   r   r   r     s"   
zDatabricksFile.__init__c                 C   s   | j | j| _dS )z(Internal function to start a file uploadN)r   rn   r)   rm   )r   r   r   r   _initiate_upload  s   zDatabricksFile._initiate_uploadFc                    sj   | j d | j    fdd| t D }|D ]}| jj| j|d q|r3| jj| jd dS dS )z<Internal function to add a chunk of data to a started uploadr   c                    s   g | ]
\}} || qS r   r   )r8   r~   r   rr   r   r   r:     s    z0DatabricksFile._upload_chunk.<locals>.<listcomp>rq   )rm   TN)	bufferseekgetvalue_to_sized_blockslenr   rw   rm   rp   )r   finaldata_chunks
data_chunkr   r   r   _upload_chunk  s   

zDatabricksFile._upload_chunkc                 C   s>   d}|| }|  ||D ]\}}|| jj| j||d7 }q|S )z-Internal function to download a block of data    )r)   r~   r   )r   r   r   r)   )r   r~   r   return_bufferrz   chunk_start	chunk_endr   r   r   _fetch_range  s   
zDatabricksFile._fetch_ranger   c                 c   s@    || }t ||| jD ]}|}t||| j }||fV  qdS )zFHelper function to split a range from 0 to total_length into bloksizesN)range	blocksizemin)r   rz   r~   r   r   
data_startdata_endr   r   r   r     s   zDatabricksFile._to_sized_blocks)rZ   r[   Tr   Nr   )r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r^     s    "
r^   )rt   ra   r   requests.exceptionsrequests.adaptersr   r   fsspecr   fsspec.specr   rg   r   r   r^   r   r   r   r   <module>   s      n