
    7Th);                         S SK r S SKrS SKrS SKrS SKJrJr  S SKJr  S SK	J
r
   " S S\5      r " S S\5      r " S	 S
\
5      rg)    N)HTTPAdapterRetry)AbstractFileSystem)AbstractBufferedFilec                   0   ^  \ rS rSrSrSU 4S jjrSrU =r$ )DatabricksException   z4
Helper class for exceptions raised in this module.
c                 H   > [         TU ]  U5        Xl        X l        X0l        g)z Create a new DatabricksExceptionN)super__init__
error_codemessagedetails)selfr   r   r   	__class__s       S/var/www/auris/envauris/lib/python3.13/site-packages/fsspec/implementations/dbfs.pyr   DatabricksException.__init__   s    !$    )r   r   r   N)__name__
__module____qualname____firstlineno____doc__r   __static_attributes____classcell__r   s   @r   r   r      s     r   r   c                      ^  \ rS rSrSrU 4S jrSS jrSS jrSS jrSS jr	 SS jr
SS	 jrS
 rSS jrS rS rS rSU 4S jjrSrU =r$ )DatabricksFileSystem   z{
Get access to the Databricks filesystem implementation over HTTP.
Can be used inside and outside of a databricks cluster.
c                 X  > Xl         X l        [        R                  " 5       U l        [        SS/ SQS9U l        U R                  R                  S[        U R                  S95        U R                  R                  R                  SSU R                   305        [        TU ]0  " S
0 UD6  g	)au  
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   DatabricksFileSystem.__init__    s     !
'');
 	:{t||'LM##_

|6L$MN"6"r   c                    U R                  U5      nU(       d\   U R                  SSSU0S9nUR                  S/ 5      nU Vs/ s H  nUS   US   (       a  S	OS
US   S.PM     nnX@R                  U'   U(       a  U$ U Vs/ s H  oS   PM	     sn$ ! [         a,  nUR                  S:X  a  [	        UR
                  5      Uee SnAff = fs  snf s  snf )z
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filesis_dir	directoryfile	file_size)nametypesizerC   )_ls_from_cache_send_to_apir   r   FileNotFoundErrorr   r6   dircache)	r   r8   detailr3   outrer>   os	            r   lsDatabricksFileSystem.ls<   s     !!$'%% 6 &  EE'2&E  A	 fI+,X;KFkN
    #&MM$J#&'3a&	3''% ' <<#<<+AII6A=	 (s#   B "CC
C	'CC	c                    U(       d#   U R                  SSSU0S9  [        SU S35      e U R                  S	S
SU0S9  U R                  U R                  U5      5        g! [         a  nUR                  S:X  a    SnANUSnAff = f! [         a,  nUR                  S:X  a  [        UR                  5      Uee SnAff = f)z
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)
r6   z
get-statusr8   r9   zPath z already existsr=   NpostmkdirsRESOURCE_ALREADY_EXISTS)rG   FileExistsErrorr   r   r   invalidate_cache_parent)r   r8   exist_okrM   s       r   makedirsDatabricksFileSystem.makedirsc   s     !! <vtn "  &dV?&CDD
	Vhfd^T 	dll401 ' <<#<< # 	||88%aii0a7		s.   "A  B  
B*B  B
B>'B99B>c                 D    U(       d  [         eU R                  " U40 UD6  g)z
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)NotImplementedErrorrS   )r   r8   create_parentsr3   s       r   mkdirDatabricksFileSystem.mkdir   s     %%D#F#r   c                     U R                  SSXS.S9  U R                  U R                  U5      5        g! [         aL  nUR                  S:X  a  U R                  XS9  e UR                  S:X  a  [	        UR
                  5      Uee SnAff = f)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.
rR   delete)r8   	recursiver9   PARTIAL_DELETEIO_ERRORN)rG   r   r   rmOSErrorr   rV   rW   )r   r8   rb   r3   rM   s        r   re   DatabricksFileSystem.rm   s    	!";   	dll401 # 		 ||//T7
 	 +aii(a/		s   6 
B ABBc                    U(       a  [         eU(       a  [         e U R                  SSXS.S9  U R                  U R                  U5      5        U R                  U R                  U5      5        g! [         aR  nUR                  S:X  a  [	        UR
                  5      UeUR                  S:X  a  [        UR
                  5      Uee SnAff = f)ah  
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.
rR   move)source_pathdestination_pathr9   r=   rT   N)	r\   rG   r   r   rH   r   rU   rV   rW   )r   rj   rk   rb   maxdepthr3   rM   s          r   mvDatabricksFileSystem.mv   s    2 %%%%	%0W   	dll;78dll+;<= # 	||88'		29!::%aii0a7	s   A0 0
C:ACCc                     [        X4X#S.UD6$ )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   r8   rp   rq   r3   s        r   _openDatabricksFileSystem._open   s     dUtUfUUr   c                    US:X  a  U R                   R                  nO+US:X  a  U R                   R                  nO[        SU 35      e[        R
                  R                  SU R                   S3U5      nU" XSS9n UR                  5         UR                  5       $ ! [        R                   a>  n UR                  R                  5       nO! [         a    USef = f[        S0 UD6UeSnAff = f)	aF  
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
rR   r6   zDo not understand method r&   z/api/2.0/dbfs/)r<   Nr)   )r.   rR   r6   
ValueErrorurllibparseurljoinr*   raise_for_statusr,   	HTTPErrorresponser<   	Exceptionr   )	r   r:   r;   r<   session_callurlrL   rM   exception_jsons	            r   rG   !DatabricksFileSystem._send_to_api   s     V<<,,Lu_<<++L8ABBll""Xdmm_N#KXV(
	?  vvx !! 	?"!"!2 "T!" &77Q>	?s*   >B C03CC+CC++C0c                      U R                  SSXS.S9nUS   $ ! [         a,  nUR                  S:X  a  [        UR                  5      Uee SnAff = f)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.
rR   create)r8   	overwriter9   handlerT   N)rG   r   r   rU   r   )r   r8   r   rL   rM   s        r   _create_handle#DatabricksFileSystem._create_handle  se    $	!!!"; " A
 X;" 	||88%aii0a7		s    
A'AAc                      U R                  SSSU0S9  g! [         a,  nUR                  S:X  a  [        UR                  5      Uee SnAff = f)z{
Close a handle, which was opened by :func:`_create_handle`.

Parameters
----------
handle: str
    Which handle to close.
rR   closer   r9   r=   N)rG   r   r   rH   r   )r   r   rM   s      r   _close_handle"DatabricksFileSystem._close_handle1  sR    	VgXvDVW" 	||88'		29		s    
A'AAc                 2   [         R                  " U5      R                  5       n U R                  SSXS.S9  g! [         aR  nUR
                  S:X  a  [        UR                  5      UeUR
                  S:X  a  [        UR                  5      Uee SnAff = f)aB  
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.
rR   z	add-blockr   datar9   r=   MAX_BLOCK_SIZE_EXCEEDEDN)	base64	b64encodedecoderG   r   r   rH   r   rv   )r   r   r   rM   s       r   	_add_dataDatabricksFileSystem._add_dataB  s     %,,.	$ &5  
 # 	||88'		29!:: +2	s   : 
BABBc                      U R                  SSXX2-
  S.S9n[        R                  " US   5      $ ! [         aR  nUR                  S:X  a  [        UR                  5      UeUR                  S;   a  [        UR                  5      Uee SnAff = f)	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
r6   read)r8   offsetlengthr9   r   r=   )INVALID_PARAMETER_VALUEMAX_READ_SIZE_EXCEEDEDN)rG   r   	b64decoder   r   rH   r   rv   )r   r8   startendrL   rM   s         r   	_get_dataDatabricksFileSystem._get_data`  s    	!!"s{K " A
 ##AfI.." 	||88'		29!VV +2	s   .1 
BABBc                    > Uc  U R                   R                  5         OU R                   R                  US 5        [        TU ]  U5        g r   )rI   clearpopr   rV   )r   r8   r   s     r   rV   %DatabricksFileSystem.invalidate_cache~  s9    <MM!MMdD) &r   )r*   r/   r.   r+   )TF)FN)rbdefaultr   )r   r   r   r   r   r   rO   rY   r^   re   rm   rs   rG   r   r   r   r   rV   r   r   r   s   @r   r   r      sZ    
#8%(N2B$"2< HL,>\V'R>"<<' 'r   r   c                   ^   ^  \ rS rSrSrSr     S
U 4S jjrS rSS jrS r	SS jr
S	rU =r$ )rr   i  z@
Helper class for files referenced in the DatabricksFileSystem.
i   c           	         > Ub  US:X  a  U R                   nX@R                   :X  d
   SU 35       e[        T	U ]  " UU4UUUUU=(       d    0 S.UD6  g)zZ
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 )rp   rq   
autocommit
cache_typecache_options)DEFAULT_BLOCK_SIZEr   r   )
r   fsr8   rp   rq   r   r   r   r3   r   s
            r   r   DatabricksFile.__init__  sz      y!800J444 	
::,G	
4 			
 !!!'-2		
 		
r   c                 X    U R                   R                  U R                  5      U l        g)z(Internal function to start a file uploadN)r   r   r8   r   )r   s    r   _initiate_uploadDatabricksFile._initiate_upload  s    gg,,TYY7r   c                    U R                   R                  S5        U R                   R                  5       nU R                  [	        U5      5       VVs/ s H	  u  p4X#U PM     nnnU H'  nU R
                  R                  U R                  US9  M)     U(       a$  U R
                  R                  U R                  S9  ggs  snnf )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_chunkDatabricksFile._upload_chunk  s    {{##% /3.C.CCI.N
.N
DsO.N 	 
 &JGGT[[zB & GG!!!5 
s   B?c                     SnX!-
  nU R                  XA5       H+  u  pVX0R                  R                  U R                  XVS9-  nM-     U$ )z-Internal function to download a block of datar   )r8   r   r   )r   r   r   r8   )r   r   r   return_bufferr   chunk_start	chunk_ends          r   _fetch_rangeDatabricksFile._fetch_range  sV    &*&;&;F&J"KWW..YYk /  M 'K
 r   c              #      #    X!-   n[        X#U R                  5       H"  nUn[        X4U R                  -   5      nXV4v   M$     g7f)zFHelper function to split a range from 0 to total_length into bloksizesN)range	blocksizemin)r   r   r   r   r   
data_startdata_ends          r   r   DatabricksFile._to_sized_blocks  sB     nDNN;J#J3T^^ ;<H&& <s   AAr   )r   r   T	readaheadNr   )r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   s   @r   rr   rr     s@     #  
D8 	' 'r   rr   )r   rw   r,   requests.exceptionsrequests.adaptersr   r   fsspecr   fsspec.specr   r}   r   r   rr   r)   r   r   <module>r      sE        0 % ,) i'- i'XN') N'r   