Ë
    #täiY?  ã                  óž   — d dl m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 d dlmZ  G d„ de«      Z G d	„ d
e«      Z G d„ de«      Zy)é    )ÚannotationsN)ÚHTTPAdapterÚRetry)Úoverride)ÚAbstractFileSystem)ÚAbstractBufferedFilec                  ó$   ‡ — e Zd ZdZdˆ fd„	Zˆ xZS )ÚDatabricksExceptionz<
    Helper class for exceptions raised in this module.
    c                óN   •— t         ‰| �  |«       || _        || _        || _        y)z Create a new DatabricksExceptionN)ÚsuperÚ__init__Ú
error_codeÚmessageÚdetails)Úselfr   r   r   Ú	__class__s       €új/Volumes/fast/ai/experiments/MLX_z-image/.venv/lib/python3.12/site-packages/fsspec/implementations/dbfs.pyr   zDatabricksException.__init__   s%   ø€ ä‰Ñ˜Ô!à$ˆŒØˆŒØˆ�ó    ©N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Ú__classcell__©r   s   @r   r
   r
      s   ø„ ñ÷ñ r   r
   c                  ó’   ‡ — e Zd ZdZˆ fd„Zedd„«       Zdd„Zdd„Zdd„Z	dd„Z
	 dd„Zdd	„Zd
„ Zdd„Zd„ Zd„ Zd„ Zdˆ fd„	Zˆ xZS )ÚDatabricksFileSystemz‡
    Get access to the Databricks filesystem implementation over HTTP.
    Can be used inside and outside of a databricks cluster.
    c                ód  •— || _         || _        t        j                  «       | _        t        ddg d¢¬«      | _        | j                  j                  dt        | j                  ¬«      «       | j                  j                  j                  dd| j                  › �i«       t        ‰| �0  d
i |¤Ž y	)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 N© )ÚinstanceÚtokenÚrequestsÚSessionÚsessionr   ÚretriesÚmountr   ÚheadersÚupdater   r   )r   r'   r(   Úkwargsr   s       €r   r   zDatabricksFileSystem.__init__"   s�   ø€ ð !ˆŒØˆŒ
Ü×'Ñ'Ó)ˆŒÜØØÚ;ô
ˆŒð 	�‰×Ñ˜:¤{¸t¿|¹|Ô'LÔMØ�‰×Ñ×#Ñ# _¸ÀÇ
Á
¸|Ð6LÐ$MÔNä‰ÑÑ"˜6Ó"r   c                ó&  — | j                   j                  |j                  d«      d«       | j                  |«      }|| j                   v rG| j                   |   D ]*  }|d   |j                  d«      k(  sŒ|d   dk7  r|gc S g c S  t	        |«      ‚y)z§Check cache for listing

        Returns listing, if found (may be empty list for a directory that
        exists but contains nothing), None if not in cache.
        Ú/NÚnameÚtypeÚ	directory)ÚdircacheÚpopÚrstripÚ_parentÚFileNotFoundError)r   ÚpathÚparentÚentrys       r   Ú_ls_from_cachez#DatabricksFileSystem._ls_from_cache>   s�   € ð 	�‰×Ñ˜$Ÿ+™+ cÓ*¨DÔ1à—‘˜dÓ#ˆØ�T—]‘]Ñ"ØŸ™ vÔ.�Ø˜‘= D§K¡K°Ó$4Ó4Ø˜V‘}¨Ò3Ø %˜wšØ’Ið	 /ô
 $ DÓ)Ð)ð #r   c                ó  — 	 | j                  |«      }|sX	 | j                  ddd|i¬«      }|j                  dg «      }|D �cg c]  }|d   |d   rd	nd
|d   dœ‘Œ }}|| j                  |<   |r|S |D �cg c]  }|d   ‘Œ	 c}S # t        $ r0 | j                  j                  | j	                  |«      d«       d}Y Œ©w xY w# t        $ r+}|j                  dk(  rt        |j                  «      |‚‚ d}~ww xY wc c}w c c}w )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.
        NÚgetÚlistr;   ©ÚmethodÚendpointÚjsonÚRESOURCE_DOES_NOT_EXISTÚfilesÚis_dirr5   ÚfileÚ	file_size)r3   r4   Úsizer3   )
r>   r:   r6   r7   r9   Ú_send_to_apir
   r   r   r@   )	r   r;   Údetailr0   ÚoutÚrÚerG   Úos	            r   ÚlszDatabricksFileSystem.lsP   s5  € ð	Ø×%Ñ% dÓ+ˆCñ ðØ×%Ñ%Ø ¨6¸À¸ð &ó �ð —E‘E˜' 2Ó&ˆEñ óñ �Að	 ˜f™IØ+,¨Xª;™K¸FØ˜k™Nóð
 ð ð ð #&ˆD�M‰M˜$ÑáØˆJÙ#&Ó'¡3˜a��&“	 3Ñ'Ð'øô= !ò 	ð �M‰M×Ñ˜dŸl™l¨4Ó0°$Ô7ØŠCð	ûô 'ò Ø—<‘<Ð#<Ò<Ü+¨A¯I©IÓ6¸AÐ=àûð	üòùò (s4   ‚B –C  ÁC7Á5C<Â6B=Â<B=Ã 	C4Ã	&C/Ã/C4c                ó|  — |s&	 | j                  ddd|i¬«       t        d|› d�«      ‚	 | j                  d	d
d|i¬«       | j                  | j                  |«      «       y# t        $ r}|j                  dk(  r	 Y d}~ŒVd}~ww xY w# t        $ r+}|j                  dk(  rt        |j                  «      |‚‚ d}~ww xY w)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;   rB   zPath z already existsrF   NÚpostÚmkdirsÚRESOURCE_ALREADY_EXISTS)rL   ÚFileExistsErrorr
   r   r   Úinvalidate_cacher9   )r   r;   Úexist_okrP   s       r   ÚmakedirszDatabricksFileSystem.makedirs   sÌ   € ñ ðà×!Ñ!Ø ¨<¸vÀt¸nð "ô ô &¨¨d¨V°?Ð&CÓDÐDð
	Ø×Ñ V°hÀfÈdÀ^ÐÔTð 	×Ñ˜dŸl™l¨4Ó0Õ1øô 'ò Ø—<‘<Ð#<Ò<Øÿøðûô #ò 	Ø�|‰|Ð8Ò8Ü% a§i¡iÓ0°aÐ7àûð		ús.   „%A! ªB Á!	BÁ*A?Á?BÂ	B;Â&B6Â6B;c                ó:   — |st         ‚ | j                  |fi |¤Ž y)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)ÚNotImplementedErrorrU   )r   r;   Úcreate_parentsr0   s       r   ÚmkdirzDatabricksFileSystem.mkdir    s    € ñ Ü%Ð%àˆ�‰�DÑ#˜FÓ#r   c                ó(  — 	 | j                  dd||dœ¬«       | j                  | j                  |«      «       y# t        $ rN}|j                  dk(  r| j                  ||¬«       ‚ |j                  dk(  rt	        |j
                  «      |‚‚ d}~ww xY w)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.
        rT   Údelete)r;   Ú	recursiverB   ÚPARTIAL_DELETEÚIO_ERRORN)rL   r
   r   ÚrmÚOSErrorr   rX   r9   )r   r;   ra   r0   rP   s        r   rd   zDatabricksFileSystem.rm±   s™   € ð	Ø×ÑØØ!Ø"°Ñ;ð ô ð 	×Ñ˜dŸl™l¨4Ó0Õ1øô #ò 		ð �|‰|Ð/Ò/Ø—‘˜T¨Y�Ô7ð
 ð	 —‘ Ò+ä˜aŸi™iÓ(¨aÐ/àûð		ús   ‚: º	BÁA	BÂBc                óŒ  — |rt         ‚|rt         ‚	 | j                  dd||dœ¬«       | j                  | j                  |«      «       | j                  | j                  |«      «       y# t        $ rP}|j                  dk(  rt	        |j
                  «      |‚|j                  dk(  rt        |j
                  «      |‚‚ d}~ww xY w)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.
        rT   Úmove)Úsource_pathÚdestination_pathrB   rF   rV   N)	r\   rL   r
   r   r:   r   rW   rX   r9   )r   rh   ri   ra   Úmaxdepthr0   rP   s          r   ÚmvzDatabricksFileSystem.mvÎ   s¿   € ñ2 Ü%Ð%ÙÜ%Ð%ð	Ø×ÑØØØ%0ÐFVÑWð ô ð 	×Ñ˜dŸl™l¨;Ó7Ô8Ø×Ñ˜dŸl™lÐ+;Ó<Õ=øô #ò 	Ø�|‰|Ð8Ò8Ü'¨¯	©	Ó2¸Ð9Ø—‘Ð!:Ò:Ü% a§i¡iÓ0°aÐ7àûð	ús   ’A* Á*	CÁ3AB>Â>Cc                ó"   — 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;   rm   rn   r0   s        r   Ú_openzDatabricksFileSystem._openü   s   € ô ˜d DÐU¨tÀ
ÑUÈfÑUÐUr   c                óæ  — |dk(  r| j                   j                  }n*|dk(  r| j                   j                  }nt        d|› �«      ‚t        j
                  j                  d| j                  › d�|«      } |||¬«      }	 |j                  «        |j                  «       S # t        j                  $ r=}	 |j                  j                  «       }n# t        $ r |d‚w xY wt        di |¤Ž|‚d}~ww xY 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
        rT   r@   zDo not understand method r#   z/api/2.0/dbfs/)rE   Nr&   )r+   rT   r@   Ú
ValueErrorÚurllibÚparseÚurljoinr'   Úraise_for_statusr)   Ú	HTTPErrorÚresponserE   Ú	Exceptionr
   )	r   rC   rD   rE   Úsession_callÚurlrO   rP   Úexception_jsons	            r   rL   z!DatabricksFileSystem._send_to_api  sç   € ð �VÒØŸ<™<×,Ñ,‰LØ�uŠ_ØŸ<™<×+Ñ+‰LäÐ8¸¸ÐAÓBÐBä�l‰l×"Ñ" X¨d¯m©m¨_¸NÐ#KÈXÓVˆá˜ 4Ô(ˆð
	?Ø×ÑÔ ð �v‰v‹xˆøô ×!Ñ!ò 	?ð"Ø!"§¡§¡Ó!2‘øÜò "Ø˜TÐ!ð"úô &Ñ7¨Ñ7¸QÐ>ûð	?ús*   Â B  Â C0Â4CÃC+ÃCÃC+Ã+C0c                óª   — 	 | j                  dd||dœ¬«      }|d   S # t        $ r+}|j                  dk(  rt        |j                  «      |‚‚ d}~ww xY 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.
        rT   Úcreate)r;   Ú	overwriterB   ÚhandlerV   N)rL   r
   r   rW   r   )r   r;   r   rO   rP   s        r   Ú_create_handlez#DatabricksFileSystem._create_handle.  sg   € ð$	Ø×!Ñ!ØØ!Ø"°Ñ;ð "ó ˆAð
 �X‘;ÐøÜ"ò 	Ø�|‰|Ð8Ò8Ü% a§i¡iÓ0°aÐ7àûð		ús   ‚ ž	A§&AÁAc                ó    — 	 | j                  ddd|i¬«       y# t        $ r+}|j                  dk(  rt        |j                  «      |‚‚ d}~ww xY w)z«
        Close a handle, which was opened by :func:`_create_handle`.

        Parameters
        ----------
        handle: str
            Which handle to close.
        rT   Úcloser€   rB   rF   N)rL   r
   r   r:   r   )r   r€   rP   s      r   Ú_close_handlez"DatabricksFileSystem._close_handleM  sR   € ð	Ø×Ñ V°gÀXÈvÐDVÐÕWøÜ"ò 	Ø�|‰|Ð8Ò8Ü'¨¯	©	Ó2¸Ð9àûð		ús   ‚ ™	A¢&AÁAc                ó2  — t        j                  |«      j                  «       }	 | j                  dd||dœ¬«       y# t        $ rP}|j
                  dk(  rt        |j                  «      |‚|j
                  dk(  rt        |j                  «      |‚‚ d}~ww xY 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.
        rT   z	add-block©r€   ÚdatarB   rF   ÚMAX_BLOCK_SIZE_EXCEEDEDN)	Úbase64Ú	b64encodeÚdecoderL   r
   r   r:   r   rr   )r   r€   r‡   rP   s       r   Ú	_add_datazDatabricksFileSystem._add_data^  s”   € ô ×Ñ Ó%×,Ñ,Ó.ˆð	Ø×ÑØØ$Ø &°Ñ5ð õ øô
 #ò 	Ø�|‰|Ð8Ò8Ü'¨¯	©	Ó2¸Ð9Ø—‘Ð!:Ò:Ü  §¡Ó+°Ð2àûð	ús   ¥= ½	BÁABÂBc                ó   — 	 | j                  dd||||z
  dœ¬«      }t        j                  |d   «      S # t        $ rO}|j                  dk(  rt        |j                  «      |‚|j                  dv rt        |j                  «      |‚‚ d}~ww xY 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ÚlengthrB   r‡   rF   )ÚINVALID_PARAMETER_VALUEÚMAX_READ_SIZE_EXCEEDEDN)rL   r‰   Ú	b64decoder
   r   r:   r   rr   )r   r;   ÚstartÚendrO   rP   s         r   Ú	_get_datazDatabricksFileSystem._get_data|  s–   € ð	Ø×!Ñ!ØØØ"¨e¸sÀU¹{ÑKð "ó ˆAô
 ×#Ñ# A f¡IÓ.Ð.øÜ"ò 	Ø�|‰|Ð8Ò8Ü'¨¯	©	Ó2¸Ð9Ø—‘Ð!VÑVÜ  §¡Ó+°Ð2àûð	ús   ‚25 µ	B¾A
BÂBc                ó–   •— |€| j                   j                  «        n| j                   j                  |d «       t        ‰| �  |«       y r   )r6   Úclearr7   r   rX   )r   r;   r   s     €r   rX   z%DatabricksFileSystem.invalidate_cacheš  s9   ø€ Øˆ<Ø�M‰M×ÑÕ!à�M‰M×Ñ˜d DÔ)Ü‰Ñ  Õ&r   )Úreturnz!list[dict[str, str | int]] | None)T©F)FN)ÚrbÚdefaultr   )r   r   r   r   r   r   r>   rR   rZ   r^   rd   rk   rp   rL   r�   r„   rŒ   r–   rX   r   r   s   @r   r   r      sn   ø„ ñô
#ð8 ò*ó ð*ó"-(ó^2óB$ó"2ð< HLó,>ó\Vò'óRò>ò"ò<÷<'ñ 'r   r   c                  óN   ‡ — e Zd ZdZdZ	 	 	 	 	 dˆ fd„	Zd„ Zd	d„Zd„ Zd
d„Z	ˆ xZ
S )ro   zH
    Helper class for files referenced in the DatabricksFileSystem.
    i   c           	     ó”   •— |�|dk(  r| j                   }|| j                   k(  s
J d|› �«       ‚t        ‰	| �  ||f|||||xs i dœ|¤Ž y)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 )rm   rn   Ú
autocommitÚ
cache_typeÚcache_options)ÚDEFAULT_BLOCK_SIZEr   r   )
r   Úfsr;   rm   rn   rŸ   r    r¡   r0   r   s
            €r   r   zDatabricksFile.__init__©  s|   ø€ ð  Ð ¨yÒ!8Ø×0Ñ0ˆJà˜T×4Ñ4Ò4ð 	
Ø:¸:¸,ÐGó	
Ð4ô 	‰ÑØØð		
ð Ø!Ø!Ø!Ø'Ò-¨2ñ		
ð ó		
r   c                óX   — | j                   j                  | j                  «      | _        y)z(Internal function to start a file uploadN)r£   r�   r;   r€   )r   s    r   Ú_initiate_uploadzDatabricksFile._initiate_uploadË  s   € à—g‘g×,Ñ,¨T¯Y©YÓ7ˆ�r   c                ó†  — | j                   j                  d«       | j                   j                  «       }| j                  t	        |«      «      D ��cg c]
  \  }}||| ‘Œ }}}|D ])  }| j
                  j                  | j                  |¬«       Œ+ |r'| j
                  j                  | j                  ¬«       yyc c}}w )z<Internal function to add a chunk of data to a started uploadr   r†   )r€   TN)	ÚbufferÚseekÚgetvalueÚ_to_sized_blocksÚlenr£   rŒ   r€   r„   )r   Úfinalr‡   r”   r•   Údata_chunksÚ
data_chunks          r   Ú_upload_chunkzDatabricksFile._upload_chunkÏ  s°   € à�‰×Ñ˜ÔØ�{‰{×#Ñ#Ó%ˆð /3×.CÑ.CÄCÈÃIÔ.Nô
Ù.N¡
  sˆD��sŠOÐ.Nð 	ñ 
ó &ˆJØ�G‰G×Ñ T§[¡[°zÐÕBð &ñ Ø�G‰G×!Ñ!¨¯©Ð!Ô5Øð ùó
s   ÁB=c                óž   — d}||z
  }| j                  ||«      D ]0  \  }}|| j                  j                  | j                  ||¬«      z  }Œ2 |S )z-Internal function to download a block of datar   )r;   r”   r•   )rª   r£   r–   r;   )r   r”   r•   Úreturn_bufferr�   Úchunk_startÚ	chunk_ends          r   Ú_fetch_rangezDatabricksFile._fetch_rangeß  s`   € àˆØ�u‘ˆØ&*×&;Ñ&;¸FÀEÖ&JÑ"ˆK˜Ø˜TŸW™W×.Ñ.Ø—Y‘Y k°yð /ó ñ ‰Mð 'Kð
 Ðr   c              #  ó�   K  — ||z   }t        ||| j                  «      D ]#  }|}t        ||| j                  z   «      }||f–— Œ% y­w)zGHelper function to split a range from 0 to total_length into blocksizesN)ÚrangeÚ	blocksizeÚmin)r   r�   r”   r•   r®   Ú
data_startÚdata_ends          r   rª   zDatabricksFile._to_sized_blocksê  sK   è ø€ à�f‰nˆÜ  s¨D¯N©NÖ;ˆJØ#ˆJÜ˜3 
¨T¯^©^Ñ ;Ó<ˆHØ˜hÐ&Ó&ñ <ùs   ‚AA)r›   rœ   TÚ	readaheadNrš   )r   )r   r   r   r   r¢   r   r¥   r¯   r´   rª   r   r   s   @r   ro   ro   ¢  s;   ø„ ñð #Ðð ØØØØõ 
òD8óò 	÷'r   ro   )Ú
__future__r   r‰   rs   r)   Úrequests.adaptersr   r   Útyping_extensionsr   Úfsspecr   Úfsspec.specr   ry   r
   r   ro   r&   r   r   Ú<module>rÁ      sH   ðÝ "ã Û ã ß 0Ý &å %Ý ,ô˜)ô ôC'Ð-ô C'ôLN'Ð)õ N'r   