
    l hR+                   $   d Z ddlm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
mZmZmZ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mZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& dd
l'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z> ddl?m@Z@ ddlAmBZBmCZC dZDd$dZE G d d      ZF G d d      ZG G d d      ZHeDrej                  neJZK G d deK      ZL G d d      ZM G d  d!      ZN G d" d#e1      ZOy)%z.Tools for representing files stored in GridFS.    )annotationsN)abc)AnyIterableMappingNoReturnOptionalcast)Int64)ObjectId)CorruptGridFile
FileExistsNoFile)_C_INDEX_CHUNK_OVERHEAD_F_INDEX	_SEEK_CUR	_SEEK_END	_SEEK_SET_UPLOAD_BUFFER_CHUNKS_UPLOAD_BUFFER_SIZEDEFAULT_CHUNK_SIZEEMPTYNEWLN_a_grid_in_property_a_grid_out_property_clear_entity_type_registry)	ASCENDING
DESCENDINGWriteConcern_csot)AsyncClientSession)AsyncCollection)AsyncCursor)AsyncDatabase)anext)validate_string)BulkWriteErrorConfigurationErrorCursorNotFoundDuplicateKeyErrorInvalidOperationOperationFailure)_check_write_command_response)ReadPreference_ServerModeFc                8    | r| j                   rt        d      y y )Nz3GridFS does not support multi-document transactions)in_transactionr,   sessions    /var/www/html/SchoolMeal/SchoolMeal/pds_admin_SchoolMeal/Backend/venv/lib/python3.12/site-packages/gridfs/asynchronous/grid_file.py_disallow_transactionsr6   A   s     7))TUU *w    c                      e Zd ZdZdddZddZ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y)AsyncGridFS2An instance of GridFS on top of a single Database.c                *   t        |t              st        dt        |             t	        |      }|j
                  j                  st        d      ||   | _        | j                  j                  | _
        | j                  j                  | _        y)a  Create a new instance of :class:`GridFS`.

        Raises :class:`TypeError` if `database` is not an instance of
        :class:`~pymongo.database.Database`.

        :param database: database to use
        :param collection: root collection to use

        .. versionchanged:: 4.0
           Removed the `disable_md5` parameter. See
           :ref:`removed-gridfs-checksum` for details.

        .. versionchanged:: 3.11
           Running a GridFS operation in a transaction now always raises an
           error. GridFS does not support multi-document transactions.

        .. versionchanged:: 3.7
           Added the `disable_md5` parameter.

        .. versionchanged:: 3.1
           Indexes are only ensured on the first write to the DB.

        .. versionchanged:: 3.0
           `database` must use an acknowledged
           :attr:`~pymongo.database.Database.write_concern`

        .. seealso:: The MongoDB documentation on `gridfs <https://dochub.mongodb.org/core/gridfs>`_.
        z.database must be an instance of Database, not z,database must use acknowledged write_concernN)
isinstancer%   	TypeErrortyper   write_concernacknowledgedr)   _collectionfiles_fileschunks_chunks)selfdatabase
collections      r5   __init__zAsyncGridFS.__init__I   s    : (M2LTRZ^L\]^^.x8%%22$%STT#J/&&,,''..r7   c                .    t        | j                  fi |S )a  Create a new file in GridFS.

        Returns a new :class:`~gridfs.grid_file.GridIn` instance to
        which data can be written. Any keyword arguments will be
        passed through to :meth:`~gridfs.grid_file.GridIn`.

        If the ``"_id"`` of the file is manually specified, it must
        not already exist in GridFS. Otherwise
        :class:`~gridfs.errors.FileExists` is raised.

        :param kwargs: keyword arguments for file creation
        )AsyncGridInrA   )rF   kwargss     r5   new_filezAsyncGridFS.new_filer   s     4++6v66r7   c                   K   t        | j                  fi |4 d{   }|j                  |       d{    |j                  cddd      d{    S 7 :7 #7 	# 1 d{  7  sw Y   yxY ww)a  Put data in GridFS as a new file.

        Equivalent to doing::

          with fs.new_file(**kwargs) as f:
              f.write(data)

        `data` can be either an instance of :class:`bytes` or a file-like
        object providing a :meth:`read` method. If an `encoding` keyword
        argument is passed, `data` can also be a :class:`str` instance, which
        will be encoded as `encoding` before being written. Any keyword
        arguments will be passed through to the created file - see
        :meth:`~gridfs.grid_file.GridIn` for possible arguments. Returns the
        ``"_id"`` of the created file.

        If the ``"_id"`` of the file is manually specified, it must
        not already exist in GridFS. Otherwise
        :class:`~gridfs.errors.FileExists` is raised.

        :param data: data to be written as a file.
        :param kwargs: keyword arguments for file creation

        .. versionchanged:: 3.0
           w=0 writes to GridFS are now prohibited.
        N)rK   rA   write_id)rF   datarL   	grid_files       r5   putzAsyncGridFS.put   si     4 t//:6: 	! 	!i//$'''==	! 	! 	!'	! 	! 	! 	!sT   A3AA3AAAA3AA3AA3A0$A'%A0,A3Nc                r   K   t        | j                  ||      }|j                          d{    |S 7 w)a  Get a file from GridFS by ``"_id"``.

        Returns an instance of :class:`~gridfs.grid_file.GridOut`,
        which provides a file-like interface for reading.

        :param file_id: ``"_id"`` of the file to get
        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r3   NAsyncGridOutrA   openrF   file_idr4   gouts       r5   getzAsyncGridFS.get   s7      D,,gwG iik 	   ,757c                  K   |}|||d<   t        |       | j                  j                  ||      }|d}|dk  rCt        |      dz
  }|j	                  d      j                  |      j                  dt               n4|j	                  d      j                  |      j                  dt               	 t        |       d{   }t        | j                  ||      S 7 # t        $ r t        d	||fz        dw xY ww)
a  Get a file from GridFS by ``"filename"`` or metadata fields.

        Returns a version of the file in GridFS whose filename matches
        `filename` and whose metadata fields match the supplied keyword
        arguments, as an instance of :class:`~gridfs.grid_file.GridOut`.

        Version numbering is a convenience atop the GridFS API provided
        by MongoDB. If more than one file matches the query (either by
        `filename` alone, by metadata fields, or by a combination of
        both), then version ``-1`` will be the most recently uploaded
        matching file, ``-2`` the second most recently
        uploaded, etc. Version ``0`` will be the first version
        uploaded, ``1`` the second version, etc. So if three versions
        have been uploaded, then version ``0`` is the same as version
        ``-3``, version ``1`` is the same as version ``-2``, and
        version ``2`` is the same as version ``-1``.

        Raises :class:`~gridfs.errors.NoFile` if no such version of
        that file exists.

        :param filename: ``"filename"`` of the file to get, or `None`
        :param version: version of the file to get (defaults
            to -1, the most recent version uploaded)
        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession`
        :param kwargs: find files by custom metadata.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.1
           ``get_version`` no longer ensures indexes.
        Nfilenamer3   r      
uploadDatefile_documentr4   no version %d for filename %r)r6   rC   findabslimitskipsortr   r   r&   rV   rA   StopAsyncIterationr   )	rF   r^   versionr4   rL   querycursorrh   docs	            r5   get_versionzAsyncGridFS.get_version   s     P  (E*w'!!%!9?GQ;w<!#DLL!!$',,\:FLL!!'*//iH	Zf%C 0 0WUU &! 	Z8GX;NNOUYY	Zs0   B2D 5C" C C" D  C" "C==D c                H   K    | j                   d||d| d{   S 7 w)a  Get the most recent version of a file in GridFS by ``"filename"``
        or metadata fields.

        Equivalent to calling :meth:`get_version` with the default
        `version` (``-1``).

        :param filename: ``"filename"`` of the file to get, or `None`
        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession`
        :param kwargs: find files by custom metadata.

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        )r^   r4   N )ro   )rF   r^   r4   rL   s       r5   get_last_versionzAsyncGridFS.get_last_version   s+     ( &T%%SxSFSSSSs   " "c                   K   t        |       | j                  j                  d|i|       d{    | j                  j	                  d|i|       d{    y7 ,7 w)aG  Delete a file from GridFS by ``"_id"``.

        Deletes all data belonging to the file with ``"_id"``:
        `file_id`.

        .. warning:: Any processes/threads reading from the file while
           this method is executing will likely see an invalid/corrupt
           file. Care should be taken to avoid concurrent reads to a file
           while it is being deleted.

        .. note:: Deletes of non-existent files are considered successful
           since the end result is the same: no file with that _id remains.

        :param file_id: ``"_id"`` of the file to delete
        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.1
           ``delete`` no longer ensures indexes.
        rP   r3   Nfiles_id)r6   rC   
delete_onerE   delete_many)rF   rY   r4   s      r5   deletezAsyncGridFS.delete  s^     0 	w'kk$$eW%5w$GGGll&&
G'<g&NNN 	HNs!   .A!A&A!AA!A!c                   K   t        |       | j                  j                  d|       d{   D cg c]  }|| c}S 7 c c}w w)aL  List the names of all files stored in this instance of
        :class:`GridFS`.

        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.1
           ``list`` no longer ensures indexes.
        r^   r3   N)r6   rC   distinct)rF   r4   names      r5   listzAsyncGridFS.list   sR      	w'
 #kk22:w2OO
 
 	
O
s    ,A
AA
A A
A
c                   K   |t        |t        j                        sd|i}t        |        | j                  |g|d|i|2 3 d{   }|c S 7 6 yw)a  Get a single file from gridfs.

        All arguments to :meth:`find` are also valid arguments for
        :meth:`find_one`, although any `limit` argument will be
        ignored. Returns a single :class:`~gridfs.grid_file.GridOut`,
        or ``None`` if no matching file is found. For example:

        .. code-block: python

            file = fs.find_one({"filename": "lisa.txt"})

        :param filter: a dictionary specifying
            the query to be performing OR any other type to be used as
            the value for a query for ``"_id"`` in the file collection.
        :param args: any additional positional arguments are
            the same as the arguments to :meth:`find`.
        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession`
        :param kwargs: any additional keyword arguments
            are the same as the arguments to :meth:`find`.

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        NrP   r4   )r<   r   r   r6   re   )rF   filterr4   argsrL   fs         r5   find_onezAsyncGridFS.find_one6  sh     > j&EV_Fw' tyyJ$JJ6J 	 	!H	J s*   AAA
AAAAAc                4    t        | j                  g|i |S )a	  Query GridFS for files.

        Returns a cursor that iterates across files matching
        arbitrary queries on the files collection. Can be combined
        with other modifiers for additional control. For example::

          for grid_out in fs.find({"filename": "lisa.txt"},
                                  no_cursor_timeout=True):
              data = grid_out.read()

        would iterate through all versions of "lisa.txt" stored in GridFS.
        Note that setting no_cursor_timeout to True may be important to
        prevent the cursor from timing out during long multi-file processing
        work.

        As another example, the call::

          most_recent_three = fs.find().sort("uploadDate", -1).limit(3)

        would return a cursor to the three most recently uploaded files
        in GridFS.

        Follows a similar interface to
        :meth:`~pymongo.collection.Collection.find`
        in :class:`~pymongo.collection.Collection`.

        If a :class:`~pymongo.client_session.AsyncClientSession` is passed to
        :meth:`find`, all returned :class:`~gridfs.grid_file.GridOut` instances
        are associated with that session.

        :param filter: A query document that selects which files
            to include in the result set. Can be an empty document to include
            all files.
        :param skip: the number of files to omit (from
            the start of the result set) when returning the results
        :param limit: the maximum number of results to
            return
        :param no_cursor_timeout: if False (the default), any
            returned cursor is closed by the server after 10 minutes of
            inactivity. If set to True, the returned cursor will never
            time out on the server. Care should be taken to ensure that
            cursors with no_cursor_timeout turned on are properly closed.
        :param sort: a list of (key, direction) pairs
            specifying the sort order for this query. See
            :meth:`~pymongo.cursor.Cursor.sort` for details.

        Raises :class:`TypeError` if any of the arguments are of
        improper type. Returns an instance of
        :class:`~gridfs.grid_file.GridOutCursor`
        corresponding to this query.

        .. versionchanged:: 3.0
           Removed the read_preference, tag_sets, and
           secondary_acceptable_latency_ms options.
        .. versionadded:: 2.7
        .. seealso:: The MongoDB documentation on `find <https://dochub.mongodb.org/core/find>`_.
        AsyncGridOutCursorrA   rF   r~   rL   s      r5   re   zAsyncGridFS.find^  s     t "$"2"2DTDVDDr7   c                   K   t        |       |r+| j                  j                  |dg|       d{   }|duS | j                  j                  |dg|       d{   }|duS 7 37 
w)a!  Check if a file exists in this instance of :class:`GridFS`.

        The file to check for can be specified by the value of its
        ``_id`` key, or by passing in a query document. A query
        document can be passed in as dictionary, or by using keyword
        arguments. Thus, the following three calls are equivalent:

        >>> fs.exists(file_id)
        >>> fs.exists({"_id": file_id})
        >>> fs.exists(_id=file_id)

        As are the following two calls:

        >>> fs.exists({"filename": "mike.txt"})
        >>> fs.exists(filename="mike.txt")

        And the following two:

        >>> fs.exists({"foo": {"$gt": 12}})
        >>> fs.exists(foo={"$gt": 12})

        Returns ``True`` if a matching file exists, ``False``
        otherwise. Calls to :meth:`exists` will not automatically
        create appropriate indexes; application developers should be
        sure to create indexes if needed and as appropriate.

        :param document_or_id: query document, or _id of the
            document to check for
        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession`
        :param kwargs: keyword arguments are used as a
            query document, if they're present.

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        rP   r3   N)r6   rC   r   )rF   document_or_idr4   rL   r   s        r5   existszAsyncGridFS.exists  sv     T 	w'kk**6E7G*LLA } kk**>E7G*TTA}	 MTs!   0A*A&*A*A(	A*(A*)fs)rG   r%   rH   str)rL   r   returnrK   )rQ   r   rL   r   r   r   NrY   r   r4   Optional[AsyncClientSession]r   rV   )Nr_   N)
r^   Optional[str]rk   Optional[int]r4   r   rL   r   r   rV   )NN)r^   r   r4   r   rL   r   r   rV   rY   r   r4   r   r   None)r4   r   r   z	list[str])
r}   Optional[Any]r4   r   r~   r   rL   r   r   zOptional[AsyncGridOut]r~   r   rL   r   r   r   )r   r   r4   r   rL   r   r   bool)__name__
__module____qualname____doc__rI   rM   rS   r[   ro   rr   rw   r{   r   re   r   rq   r7   r5   r9   r9   F   s   <'/R7!<* #'!#04	9Z9Z 9Z .	9Z
 9Z 
9Zz #'04TT .T 	T
 
T.O8
0 !%04&& .& 	&
 & 
 &P:E| )-040%0 .0 	0
 
0r7   r9   c                  J   e Zd ZdZdeddf	 	 	 	 	 	 	 	 	 	 	 ddZ	 	 	 d	 	 	 	 	 	 	 	 	 ddZ	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZej                  	 	 	 d	 	 	 	 	 	 	 	 	 	 	 dd       Z
ej                  	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Z	 d	 	 	 	 	 dd	Zej                  	 d	 	 	 	 	 	 	 dd
       Zej                  ddd       Zej                  	 d	 	 	 	 	 dd       ZddZ	 d	 	 	 	 	 	 	 ddZej                  	 	 d	 	 	 	 	 	 	 	 	 d d       Z	 d	 	 	 	 	 	 	 d!dZ	 d	 	 	 	 	 	 	 d"dZy)#AsyncGridFSBucketr:   r   Nc                   t        |t              st        dt        |             t	        |      }||n|j
                  }|j                  st        d      || _        ||   | _	        | j                  j                  j                  ||      | _        | j                  j                  j                  ||      | _        || _        |j                   j"                  j$                  | _        y)a!  Create a new instance of :class:`GridFSBucket`.

        Raises :exc:`TypeError` if `database` is not an instance of
        :class:`~pymongo.database.Database`.

        Raises :exc:`~pymongo.errors.ConfigurationError` if `write_concern`
        is not acknowledged.

        :param database: database to use.
        :param bucket_name: The name of the bucket. Defaults to 'fs'.
        :param chunk_size_bytes: The chunk size in bytes. Defaults
            to 255KB.
        :param write_concern: The
            :class:`~pymongo.write_concern.WriteConcern` to use. If ``None``
            (the default) db.write_concern is used.
        :param read_preference: The read preference to use. If
            ``None`` (the default) db.read_preference is used.

        .. versionchanged:: 4.0
           Removed the `disable_md5` parameter. See
           :ref:`removed-gridfs-checksum` for details.

        .. versionchanged:: 3.11
           Running a GridFSBucket operation in a transaction now always raises
           an error. GridFSBucket does not support multi-document transactions.

        .. versionchanged:: 3.7
           Added the `disable_md5` parameter.

        .. versionadded:: 3.1

        .. seealso:: The MongoDB documentation on `gridfs <https://dochub.mongodb.org/core/gridfs>`_.
        z3database must be an instance of AsyncDatabase, not Nz"write concern must be acknowledged)r?   read_preference)r<   r%   r=   r>   r   r?   r@   r)   _bucket_namerA   rD   with_optionsrE   rB   rC   _chunk_size_bytesclientoptionstimeout_timeout)rF   dbbucket_namechunk_size_bytesr?   r   wtcs          r5   rI   zAsyncGridFSBucket.__init__  s    R "m,QRVWYRZQ[\]](,,8mb>N>N$%IJJ'k?(,(8(8(?(?(L(L' )M )
 (,'7'7'='='J'J' (K (
 "2		))11r7   c                ~    t        d|       |||n| j                  d}|||d<   t        | j                  fd|i|S )a  Opens a Stream that the application can write the contents of the
        file to.

        The user must specify the filename, and can choose to add any
        additional information in the metadata field of the file document or
        modify the chunk size.
        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          with fs.open_upload_stream(
                "test_file", chunk_size_bytes=4,
                metadata={"contentType": "text/plain"}) as grid_in:
              grid_in.write("data I want to store!")
          # uploaded on close

        Returns an instance of :class:`~gridfs.grid_file.GridIn`.

        Raises :exc:`~gridfs.errors.NoFile` if no such version of
        that file exists.
        Raises :exc:`~ValueError` if `filename` is not a string.

        :param filename: The name of the file to upload.
        :param chunk_size_bytes` (options): The number of bytes per chunk of this
            file. Defaults to the chunk_size_bytes in :class:`GridFSBucket`.
        :param metadata: User data for the 'metadata' field of the
            files collection document. If not provided the metadata field will
            be omitted from the files collection document.
        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r^   )r^   
chunk_sizemetadatar4   r'   r   rK   rA   )rF   r^   r   r   r4   optss         r5   open_upload_streamz$AsyncGridFSBucket.open_upload_stream  sY    R 	
H- !$4$@ dF\F\
 'D4++EWEEEr7   c                    t        d|       ||||n| j                  d}|||d<   t        | j                  fd|i|S )a?  Opens a Stream that the application can write the contents of the
        file to.

        The user must specify the file id and filename, and can choose to add
        any additional information in the metadata field of the file document
        or modify the chunk size.
        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          with fs.open_upload_stream_with_id(
                ObjectId(),
                "test_file",
                chunk_size_bytes=4,
                metadata={"contentType": "text/plain"}) as grid_in:
              grid_in.write("data I want to store!")
          # uploaded on close

        Returns an instance of :class:`~gridfs.grid_file.GridIn`.

        Raises :exc:`~gridfs.errors.NoFile` if no such version of
        that file exists.
        Raises :exc:`~ValueError` if `filename` is not a string.

        :param file_id: The id to use for this file. The id must not have
            already been used for another file.
        :param filename: The name of the file to upload.
        :param chunk_size_bytes` (options): The number of bytes per chunk of this
            file. Defaults to the chunk_size_bytes in :class:`GridFSBucket`.
        :param metadata: User data for the 'metadata' field of the
            files collection document. If not provided the metadata field will
            be omitted from the files collection document.
        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r^   )rP   r^   r   r   r4   r   )rF   rY   r^   r   r   r4   r   s          r5   open_upload_stream_with_idz,AsyncGridFSBucket.open_upload_stream_with_idE  s\    \ 	
H-  $4$@ dF\F\	
 'D4++EWEEEr7   c                  K   | j                  ||||      4 d{   }|j                  |       d{    ddd      d{    t        t        j                        S 7 G7 07 "# 1 d{  7  sw Y   2xY ww)a  Uploads a user file to a GridFS bucket.

        Reads the contents of the user file from `source` and uploads
        it to the file `filename`. Source can be a string or file-like object.
        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          file_id = fs.upload_from_stream(
              "test_file",
              "data I want to store!",
              chunk_size_bytes=4,
              metadata={"contentType": "text/plain"})

        Returns the _id of the uploaded file.

        Raises :exc:`~gridfs.errors.NoFile` if no such version of
        that file exists.
        Raises :exc:`~ValueError` if `filename` is not a string.

        :param filename: The name of the file to upload.
        :param source: The source stream of the content to be uploaded. Must be
            a file-like object that implements :meth:`read` or a string.
        :param chunk_size_bytes` (options): The number of bytes per chunk of this
            file. Defaults to the chunk_size_bytes of :class:`GridFSBucket`.
        :param metadata: User data for the 'metadata' field of the
            files collection document. If not provided the metadata field will
            be omitted from the files collection document.
        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r3   N)r   rO   r
   r   rP   )rF   r^   sourcer   r   r4   gins          r5   upload_from_streamz$AsyncGridFSBucket.upload_from_stream  s     V **&' + 
 	$ 	$))F###	$ 	$
 Hcgg&&	$ $	$ 	$ 	$ 	$sS   A?A$A?A*A&A*A?A(A?&A*(A?*A<0A31A<8A?c                   K   | j                  |||||      4 d{   }|j                  |       d{    ddd      d{    y7 .7 7 	# 1 d{  7  sw Y   yxY ww)a  Uploads a user file to a GridFS bucket with a custom file id.

        Reads the contents of the user file from `source` and uploads
        it to the file `filename`. Source can be a string or file-like object.
        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          file_id = fs.upload_from_stream(
              ObjectId(),
              "test_file",
              "data I want to store!",
              chunk_size_bytes=4,
              metadata={"contentType": "text/plain"})

        Raises :exc:`~gridfs.errors.NoFile` if no such version of
        that file exists.
        Raises :exc:`~ValueError` if `filename` is not a string.

        :param file_id: The id to use for this file. The id must not have
            already been used for another file.
        :param filename: The name of the file to upload.
        :param source: The source stream of the content to be uploaded. Must be
            a file-like object that implements :meth:`read` or a string.
        :param chunk_size_bytes` (options): The number of bytes per chunk of this
            file. Defaults to the chunk_size_bytes of :class:`GridFSBucket`.
        :param metadata: User data for the 'metadata' field of the
            files collection document. If not provided the metadata field will
            be omitted from the files collection document.
        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r3   N)r   rO   )rF   rY   r^   r   r   r   r4   r   s           r5   upload_from_stream_with_idz,AsyncGridFSBucket.upload_from_stream_with_id  sr     Z 22X/7 3 
 	$ 	$))F###	$ 	$ 	$ $	$ 	$ 	$ 	$sS   A'AA'AAAA'AA'AA'A$AA$ A'c                r   K   t        | j                  ||      }|j                          d{    |S 7 w)a  Opens a Stream from which the application can read the contents of
        the stored file specified by file_id.

        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          # get _id of file to read.
          file_id = fs.upload_from_stream("test_file", "data I want to store!")
          grid_out = fs.open_download_stream(file_id)
          contents = grid_out.read()

        Returns an instance of :class:`~gridfs.grid_file.GridOut`.

        Raises :exc:`~gridfs.errors.NoFile` if no file with file_id exists.

        :param file_id: The _id of the file to be downloaded.
        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r3   NrU   rX   s       r5   open_download_streamz&AsyncGridFSBucket.open_download_stream  s7     4 D,,gwG iik 	r\   c                  K   | j                  ||       d{   4 d{   }	 |j                          d{   }t        |      sn|j                  |       6ddd      d{    y7 U7 N7 77 # 1 d{  7  sw Y   yxY ww)au  Downloads the contents of the stored file specified by file_id and
        writes the contents to `destination`.

        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          # Get _id of file to read
          file_id = fs.upload_from_stream("test_file", "data I want to store!")
          # Get file to write to
          file = open('myfile','wb+')
          fs.download_to_stream(file_id, file)
          file.seek(0)
          contents = file.read()

        Raises :exc:`~gridfs.errors.NoFile` if no file with file_id exists.

        :param file_id: The _id of the file to be downloaded.
        :param destination: a file-like object implementing :meth:`write`.
        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r3   N)r   	readchunklenrO   )rF   rY   destinationr4   rZ   chunks         r5   download_to_streamz$AsyncGridFSBucket.download_to_stream  s     : 227G2LL 	) 	)PT"nn..5z!!%(	 	) 	) 	)L 	).	) 	) 	) 	)sd   BA/BA1BA7A3"A7B)A5*B1B3A75B7B	=B >B	Bc                   K   t        |       | j                  j                  d|i|       d{   }| j                  j	                  d|i|       d{    |j
                  st        d|z        y7 F7 !w)a  Given an file_id, delete this stored file's files collection document
        and associated chunks from a GridFS bucket.

        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          # Get _id of file to delete
          file_id = fs.upload_from_stream("test_file", "data I want to store!")
          fs.delete(file_id)

        Raises :exc:`~gridfs.errors.NoFile` if no file with file_id exists.

        :param file_id: The _id of the file to be deleted.
        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        rP   r3   Nrt   z0no file could be deleted because none matched %s)r6   rC   ru   rE   rv   deleted_countr   )rF   rY   r4   ress       r5   rw   zAsyncGridFSBucket.delete)  s|     , 	w'KK**E7+;W*MMll&&
G'<g&NNN  KgUVV ! NNs!   .A;A7&A;A9 A;9A;c                  K   t        |       | j                  j                  d|iddi|      }|2 cg c3 d{   }|d   7 
6 nc c}w }}| j                  j                  dd|ii|       d{  7  }| j                  j                  dd|ii|       d{  7   |j
                  st        d|      yw)	an  Given a filename, delete this stored file's files collection document(s)
        and associated chunks from a GridFS bucket.

        For example::

          my_db = AsyncMongoClient().test
          fs = AsyncGridFSBucket(my_db)
          await fs.upload_from_stream("test_file", "data I want to store!")
          await fs.delete_by_name("test_file")

        Raises :exc:`~gridfs.errors.NoFile` if no file with the given filename exists.

        :param filename: The name of the file to be deleted.
        :param session: a :class:`~pymongo.client_session.AsyncClientSession`

        .. versionadded:: 4.12
        r^   rP   r`   r3   Nz$inrt   z7no file could be deleted because none matched filename )r6   rC   re   rv   rE   r   r   )rF   r^   r4   rB   filefile_idsr   s          r5   delete_by_namez AsyncGridFSBucket.delete_by_nameE  s     * 	w'  *h!7%W U2788$DK8888KK++UUH4E,FPW+XXXll&&
UH4E'FPW&XXX  RS[R^_`` !sH   2B?A	AA
AA	AA	,B?4A75)B?B! B?c                4    t        | j                  g|i |S )a  Find and return the files collection documents that match ``filter``

        Returns a cursor that iterates across files matching
        arbitrary queries on the files collection. Can be combined
        with other modifiers for additional control.

        For example::

          for grid_data in fs.find({"filename": "lisa.txt"},
                                  no_cursor_timeout=True):
              data = grid_data.read()

        would iterate through all versions of "lisa.txt" stored in GridFS.
        Note that setting no_cursor_timeout to True may be important to
        prevent the cursor from timing out during long multi-file processing
        work.

        As another example, the call::

          most_recent_three = fs.find().sort("uploadDate", -1).limit(3)

        would return a cursor to the three most recently uploaded files
        in GridFS.

        Follows a similar interface to
        :meth:`~pymongo.collection.Collection.find`
        in :class:`~pymongo.collection.Collection`.

        If a :class:`~pymongo.client_session.AsyncClientSession` is passed to
        :meth:`find`, all returned :class:`~gridfs.grid_file.GridOut` instances
        are associated with that session.

        :param filter: Search query.
        :param batch_size: The number of documents to return per
            batch.
        :param limit: The maximum number of documents to return.
        :param no_cursor_timeout: The server normally times out idle
            cursors after an inactivity period (10 minutes) to prevent excess
            memory use. Set this option to True prevent that.
        :param skip: The number of documents to skip before
            returning.
        :param sort: The order by which to sort results. Defaults to
            None.
        r   r   s      r5   re   zAsyncGridFSBucket.findb  s     Z "$"2"2DTDVDDr7   c                
  K   t        d|       d|i}t        |       | j                  j                  ||      }|dk  rCt	        |      dz
  }|j                  d      j                  |      j                  dt               n4|j                  d      j                  |      j                  dt               	 t        |       d{   }t        | j                  ||      S 7 # t        $ r t        d	||fz        dw xY ww)
a  Opens a Stream from which the application can read the contents of
        `filename` and optional `revision`.

        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          grid_out = fs.open_download_stream_by_name("test_file")
          contents = grid_out.read()

        Returns an instance of :class:`~gridfs.grid_file.GridOut`.

        Raises :exc:`~gridfs.errors.NoFile` if no such version of
        that file exists.

        Raises :exc:`~ValueError` filename is not a string.

        :param filename: The name of the file to read from.
        :param revision: Which revision (documents with the same
            filename and different uploadDate) of the file to retrieve.
            Defaults to -1 (the most recent revision).
        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession`

        :Note: Revision numbers are defined as follows:

          - 0 = the original stored file
          - 1 = the first revision
          - 2 = the second revision
          - etc...
          - -2 = the second most recent revision
          - -1 = the most recent revision

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r^   r3   r   r`   r_   ra   Nrb   rd   )r'   r6   rC   re   rf   rg   rh   ri   r   r   r&   rV   rA   rj   r   )rF   r^   revisionr4   rl   rm   rh   rR   s           r5   open_download_stream_by_namez.AsyncGridFSBucket.open_download_stream_by_name  s     N 	
H-X&w'!!%!9a<x=1$DLL!!$',,\:FLL!!(+00yI	[#Fm+I 0 0	SZ[[ ,! 	[8Hh;OOPVZZ	[s0   B5D8C% C#C% "D#C% %D  Dc                  K   | j                  |||       d{   4 d{   }	 |j                          d{   }t        |      sn|j                  |       6ddd      d{    y7 U7 N7 77 # 1 d{  7  sw Y   yxY ww)a  Write the contents of `filename` (with optional `revision`) to
        `destination`.

        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          # Get file to write to
          file = open('myfile','wb')
          fs.download_to_stream_by_name("test_file", file)

        Raises :exc:`~gridfs.errors.NoFile` if no such version of
        that file exists.

        Raises :exc:`~ValueError` if `filename` is not a string.

        :param filename: The name of the file to read from.
        :param destination: A file-like object that implements :meth:`write`.
        :param revision: Which revision (documents with the same
            filename and different uploadDate) of the file to retrieve.
            Defaults to -1 (the most recent revision).
        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession`

        :Note: Revision numbers are defined as follows:

          - 0 = the original stored file
          - 1 = the first revision
          - 2 = the second revision
          - etc...
          - -2 = the second most recent revision
          - -1 = the most recent revision

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r3   N)r   r   r   rO   )rF   r^   r   r   r4   rZ   r   s          r5   download_to_stream_by_namez,AsyncGridFSBucket.download_to_stream_by_name  s     X ::h ; 
 
 	) 	)"nn..5z!!%(	 	) 	) 	) 
 	) /		) 	) 	) 	)sd   BA0BA2BA8A4"A8B*A6+B2B4A86B8B
>B?B
Bc                   K   t        |       | j                  j                  d|idd|ii|       d{   }|j                  st	        d||fz        y7 !w)a  Renames the stored file with the specified file_id.

        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          # Get _id of file to rename
          file_id = fs.upload_from_stream("test_file", "data I want to store!")
          fs.rename(file_id, "new_test_name")

        Raises :exc:`~gridfs.errors.NoFile` if no file with file_id exists.

        :param file_id: The _id of the file to be renamed.
        :param new_filename: The new name of the file.
        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        rP   $setr^   r3   Nz<no files could be renamed %r because none matched file_id %i)r6   rC   
update_onematched_countr   )rF   rY   new_filenamer4   results        r5   renamezAsyncGridFSBucket.rename  sx     . 	w'{{--Gv
L'ABG . 
 
 ##%(4g'>?  $
s   3AA"Ac                   K   t        |       | j                  j                  d|idd|ii|       d{   }|j                  st	        d|d|      y7 "w)ar  Renames the stored file with the specified filename.

        For example::

          my_db = AsyncMongoClient().test
          fs = AsyncGridFSBucket(my_db)
          await fs.upload_from_stream("test_file", "data I want to store!")
          await fs.rename_by_name("test_file", "new_test_name")

        Raises :exc:`~gridfs.errors.NoFile` if no file with the given filename exists.

        :param filename: The filename of the file to be renamed.
        :param new_filename: The new name of the file.
        :param session: a :class:`~pymongo.client_session.AsyncClientSession`

        .. versionadded:: 4.12
        r^   r   r3   Nzno files could be renamed z because none matched filename )r6   rC   update_manyr   r   )rF   r^   r   r4   r   s        r5   rename_by_namez AsyncGridFSBucket.rename_by_name  s{     ( 	w'{{.."Vj,-G$HRY / 
 
 ##,\,<<[\d[gh  $
s   3AA#A)r   r%   r   r   r   intr?   zOptional[WriteConcern]r   zOptional[_ServerMode]r   r   NNN)
r^   r   r   r   r   Optional[Mapping[str, Any]]r4   r   r   rK   )rY   r   r^   r   r   r   r   r   r4   r   r   rK   )r^   r   r   r   r   r   r   r   r4   r   r   r   )rY   r   r^   r   r   r   r   r   r   r   r4   r   r   r   r   r   )rY   r   r   r   r4   r   r   r   r   )r^   r   r4   r   r   r   r   )r_   N)r^   r   r   r   r4   r   r   rV   )
r^   r   r   r   r   r   r4   r   r   r   )rY   r   r   r   r4   r   r   r   )r^   r   r   r   r4   r   r   r   )r   r   r   r   r   rI   r   r   r!   applyr   r   r   r   rw   r   re   r   r   r   r   rq   r7   r5   r   r     sH   <
   20415=2=2 =2 	=2
 .=2 /=2 
=2D +/04044F4F (4F .	4F
 .4F 
4Ft +/0404:F:F :F (	:F
 .:F .:F 
:Fx [[
 +/0404/'/' /' (	/'
 ./' ./' 
/' /'b [[ +/0404/$/$ /$ 	/$
 (/$ ./$ ./$ 
/$ /$d EI%A	@ [[VZ!)!)),!)7S!)	!) !)F [[W W6 [[EIaa&Ba	a a8-E` Z^4[4['*4[:V4[	4[l [[
 042)2) 2) 	2)
 .2) 
2) 2)j X\*-8T	D Y]+.9U	r7   r   c                     e Zd ZU dZ	 d:	 	 	 	 	 	 	 d;dZ	 	 	 	 	 	 	 	 d<dZd=dZd=dZed>d	       Z	 e
d
dd      Zded
<    e
dd      Zded<    e
dd      Zded<    e
dd      Zded<    e
ddd      Zded<    e
ddd      Zded<    e
ddd      Zded <    e
d!d"d      Zded!<   d#ed$<   ded%<   d&ed'<   ded(<   d?d)Zd@d*Zd@d+ZdAdBd,ZdAdCd-ZdDd.ZdEd/Zd=d0ZdFdGd1Zd>d2Zd>d3ZdHd4ZdId5Z dJd6Z!d>d7Z"dKd8Z#dLd9Z$y)MrK   zClass to write data to GridFS.Nr   c                   t        |t              st        dt        |             |j                  j
                  st        d      t        |       d|v r|j                  d      |d<   d|v r|j                  d      |d<   t        |t        j                        }|j                  dt                     |d<   |j                  dt              |d<   t        j!                  | d	|       t        j!                  | d
|       t        j!                  | d|j"                         t        j!                  | d|       t        j!                  | dt%        j&                                t        j!                  | dd       t        j!                  | dd       t        j!                  | dd       t        j!                  | dd       t        j!                  | dg        t        j!                  | dd       y)a  Write a file to GridFS

        Application developers should generally not need to
        instantiate this class directly - instead see the methods
        provided by :class:`~gridfs.GridFS`.

        Raises :class:`TypeError` if `root_collection` is not an
        instance of :class:`~pymongo.collection.AsyncCollection`.

        Any of the file level options specified in the `GridFS Spec
        <http://dochub.mongodb.org/core/gridfsspec>`_ may be passed as
        keyword arguments. Any additional keyword arguments will be
        set as additional fields on the file document. Valid keyword
        arguments include:

          - ``"_id"``: unique ID for this file (default:
            :class:`~bson.objectid.ObjectId`) - this ``"_id"`` must
            not have already been used for another file

          - ``"filename"``: human name for the file

          - ``"contentType"`` or ``"content_type"``: valid mime-type
            for the file

          - ``"chunkSize"`` or ``"chunk_size"``: size of each of the
            chunks, in bytes (default: 255 kb)

          - ``"encoding"``: encoding used for this file. Any :class:`str`
            that is written to the file will be converted to :class:`bytes`.

        :param root_collection: root collection to write to
        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession` to use for all
            commands
        :param kwargs: Any: file level options (see above)

        .. versionchanged:: 4.0
           Removed the `disable_md5` parameter. See
           :ref:`removed-gridfs-checksum` for details.

        .. versionchanged:: 3.7
           Added the `disable_md5` parameter.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.0
           `root_collection` must use an acknowledged
           :attr:`~pymongo.collection.AsyncCollection.write_concern`
        <root_collection must be an instance of AsyncCollection, not z3root_collection must use acknowledged write_concerncontent_typecontentTyper   	chunkSize)r   rP   _session_collrE   _file_buffer	_positionr   _chunk_number_closedF_ensured_index_buffered_docs_buffered_docs_sizeN)r<   r#   r=   r>   r?   r@   r)   r6   popr   r/   PRIMARYr[   r   r   object__setattr__rD   ioBytesIO)rF   root_collectionr4   rL   colls        r5   rI   zAsyncGridIn.__init__>  s   p /?;NtTcOdNef  ,,99$%Z[[w' V#$*JJ~$>F=!6!"(**\":F;*?NLbLbc 

5(*5u$jj6HI{4W54$/4DKK84&14BJJL94a04!44E24!1594!1264!6:r7   r   c                  K   |j                  ddi| j                         d {   }|:	 |j                  | j                         d {   2 cg c3 d {   }|d   y y y 7 A7 7 6 nc c}w }}n# t        $ r g }Y nw xY w||vs(|j	                  |j                         || j                         d {  7   _w)NrP   r`   )
projectionr4   r3   key)uniquer4   )r   r   list_indexesr-   create_indexitems)rF   rH   	index_keyr   rn   
index_spec
index_keyss          r5   _create_indexzAsyncGridIn._create_index  s      ''E1:t}}'UU;  3=2I2IRVR_R_2I2`,` ( u%
 +  V
 -a  
  $  
 
* --OO%fdmm .   s   #CA'CA7 A)A7 A/A-A+
A-A/$C)A7 +A--A/.A7 6C7BCBC/C<B?=Cc                f  K   t         j                  | d      st        | j                         | j	                  | j
                  j                  t        d       d {    | j	                  | j
                  j                  t        d       d {    t         j                  | dd       y y 7 P7 w)Nr   FT)r   __getattribute__r6   r   r   r   rB   r   rD   r   r   rF   s    r5   _ensure_indexeszAsyncGridIn._ensure_indexes  s     &&t-=>"4==1$$TZZ%5%5xGGG$$TZZ%6%6$GGGt%5t<	 ?GGs$   AB1B-2B1B/B1/B1c                b  K   | j                   j                  j                  d| j                  d   i| j                         d{    | j                   j
                  j                  d| j                  d   i| j                         d{    t        j                  | dd       y7 d7 w)z>Remove all chunks/files that may have been uploaded and close.rt   rP   r3   Nr   T)	r   rD   rv   r   r   rB   ru   r   r   r   s    r5   abortzAsyncGridIn.abort  s     jj++ZE9J,KUYUbUb+cccjj))5$**U2C*Ddmm)\\\4D1 	d\s%   AB/B+AB/B-B/-B/c                    | j                   S )zIs this file closed?)r   r   s    r5   closedzAsyncGridIn.closed  s     ||r7   rP   "The ``'_id'`` value for this file.T)	read_onlyr^   Name of this file.r   Alias for `filename`.rz   r   DDEPRECATED, will be removed in PyMongo 5.0. Mime-type for this file.r   lengthLength (in bytes) of this file.)closed_onlyr   r   Chunk size for this file.r   ra   z!Date that this file was uploaded.datetime.datetimeupload_datemd5gDEPRECATED, will be removed in PyMongo 5.0. MD5 of the contents of this file if an md5 sum was created.z
io.BytesIOr   r   zlist[dict[str, Any]]r   r   c                    |dk(  rt         j                  | |      S || j                  v r| j                  |   S t        d|z        )Nr   z#GridIn object has no attribute '%s')r   r   r   AttributeErrorrF   rz   s     r5   __getattr__zAsyncGridIn.__getattr__  sH    7?**466TZZ::d##BTIJJr7   c                L   || j                   v s|| j                  j                   v rt        j                  | ||       y || j                  |<   | j
                  rKt        r:| j                  j                  j                  d| j                  d   id||ii       y t        d      y )NrP   r   zAsyncGridIn does not support __setattr__ after being closed(). Set the attribute before closing the file or use AsyncGridIn.set() instead)__dict__	__class__r   r   r   r   _IS_SYNCr   rB   r   r  rF   rz   values      r5   r   zAsyncGridIn.__setattr__  s     4== DDNN,C,C$CtT51
  %DJJt||JJ$$//

58I0JVVZ\aUbLcd( d 	 r7   c                   K   || j                   |<   | j                  rB| j                  j                  j	                  d| j                   d   id||ii       d {    y y 7 w)NrP   r   )r   r   r   rB   r   r  s      r5   setzAsyncGridIn.set  s]      

4<<**""--udjj6G.H6TXZ_S`Jabbb bs   AA#A!A#c                  K   | j                          d{    t        |      | j                  k  sJ |r[| j                  j	                  | j
                  d   | j                  |d       | xj                  t        |      t        z   z  c_        | j                  sy|s/| j                  t        k\  st        | j                        t        k\  rH	 | j                  j                  | j                  | j                         d{    g | _        d| _        | xj                  dz  c_        | xj&                  t        |      z  c_        y7 67 I# t        $ rv}|j                  d   }|D ]4  }|j!                  d      dv s| j#                  | j
                  d          6 d|i}|j                  d   }|r|d	   |d
<   t%        |        d}~ww xY ww)zFlush `data` to a chunk.NrP   )rt   nrQ   r3   writeErrorscode)i*  i*  i&1  writeConcernErrorsr_   writeConcernErrorr   r`   )r   r   r   r   appendr   r   r   r   r   r   rE   insert_manyr   r(   detailsr[   _raise_file_existsr.   r   )rF   rQ   forceexcwrite_errorserrr   wcess           r5   _flush_datazAsyncGridIn._flush_data  s    ""$$$4yDOO+++&&!ZZ.T5G5GQUV $$D	O(CC$"" ''+>>4&&'+@@ll..t/B/BDMM.ZZZ #%D'(D$a#d)#A 	%  [! "{{=9' CCwwv*??//

50ABC (6{{#7826r(F./-f5sN   GEB9G4E EE 
AGE 	G'GA	GGGc                   K   | j                  | j                  j                         |       d{    | j                  j                          t	        j
                         | _        y7 8w)z)Flush the buffer contents out to a chunk.r'  N)r,  r   getvaluecloser   r   )rF   r'  s     r5   _flush_bufferzAsyncGridIn._flush_buffer  sO     t||446eDDDzz| 	Es   /A,A*9A,c                  K   	 | j                  d       d{    t        | j                        | j                  d<   t        j                  j                  t        j                  j                        | j                  d<   | j                  j                  j                  | j                  | j                         d{   S 7 7 # t        $ r | j                  | j                         Y yw xY ww)zFlush the file to the database.Tr.  Nr	  )tzra   r3   )r1  r   r   r   datetimenowtimezoneutcr   rB   
insert_oner   r+   r&  rP   r   s    r5   _flushzAsyncGridIn._flush  s     	.$$4$000#(#8DJJx '/'8'8'<'<@Q@Q@U@U'<'VDJJ|$))44TZZ4WWW 1
 X  	.##DHH-	.sK   C6C CB)C C
C C6C 
C $C30C62C33C6c                    t        d|z        )z3Raise a FileExists exception for the given file_id.zfile with _id %r already exists)r   )rF   rY   s     r5   r&  zAsyncGridIn._raise_file_exists#  s    :WDEEr7   c                   K   | j                   s0| j                          d{    t        j                  | dd       yy7 w)zFlush the file and close it.

        A closed file cannot be written any more. Calling
        :meth:`close` more than once is allowed.
        Nr   T)r   r9  r   r   r   s    r5   r0  zAsyncGridIn.close'  s8      ||++-tY5 s    AA Ac                ,    t        j                  d      )Nreadr   UnsupportedOperationrF   sizes     r5   r=  zAsyncGridIn.read1  s    %%f--r7   c                     yNFrq   r   s    r5   readablezAsyncGridIn.readable4      r7   c                     yrC  rq   r   s    r5   seekablezAsyncGridIn.seekable7  rE  r7   c                |  K   | j                   rt        d      	 |j                  }t        j                  |      r| j                  |       d{    y| j                  j!                         dkD  rt| j"                  | j                  j!                         z
  }|r3	  ||      }| j                  j)                  |       t+        |      |k  ry| j-                          d{     || j"                        }|r^t+        |      | j"                  k(  rF| j/                  |       d{     || j"                        }|rt+        |      | j"                  k(  rF| j                  j)                  |       y# t        $ r t	        |t
        t        f      st        d      dt	        |t
              r6	 |j                  | j                        }n# t        $ r t        d      dw xY wt        j                  |      j                  }Y w xY w7 # t$        $ r | j'                          d{  7    w xY w7 T7 w)ag  Write data to the file. There is no return value.

        `data` can be either a string of bytes or a file-like object
        (implementing :meth:`read`). If the file has an
        :attr:`encoding` attribute, `data` can also be a
        :class:`str` instance, which will be encoded as
        :attr:`encoding` before being written.

        Due to buffering, the data may not actually be written to the
        database until the :meth:`close` method is called. Raises
        :class:`ValueError` if this file is already closed. Raises
        :class:`TypeError` if `data` is not an instance of
        :class:`bytes`, a file-like object, or an instance of :class:`str`.
        Unicode data is only allowed if the file has an :attr:`encoding`
        attribute.

        :param data: string of bytes or file-like object to be written
            to the file
        zcannot write to a closed filez+can only write strings or file-like objectsNz7must specify an encoding for file in order to write strr   )r   
ValueErrorr=  r  r<   r   bytesr=   encodeencodingr   r   inspectiscoroutinefunction_write_asyncr   tellr   BaseExceptionr  rO   r   r1  r,  )rF   rQ   r=  spaceto_writes        r5   rO   zAsyncGridIn.write:  s    ( <<<==	)99D &&t,##D)))||  "Q&$,,*;*;*==#'; LL&&x08}u,((***DOO,Hs8}?&&x0000 s8}? LLx(C  	)dS%L1 MNTXX$$ ;;t}}5D%  #Q   ::d#((D	) * ) "jjl** + 1s   H<E5 )H<HAH<H %=H<"H6#AH<'H9(0H<H<5;H	1GH	G##"H	H<H		H<H3+H.,H33H<9H<c                  K   | j                   j                         dkD  r|| j                  | j                   j                         z
  }|r;	  ||       d {   }| j                   j                  |       t        |      |k  ry | j                          d {     || j                         d {   }|rft        |      | j                  k(  rN| j                  |       d {     || j                         d {   }|rt        |      | j                  k(  rN| j                   j                  |       y 7 # t        $ r | j	                          d {  7    w xY w7 7 7 7 jwNr   )	r   rP  r   rQ  r  rO   r   r1  r,  )rF   r=  rR  rS  s       r5   rO  zAsyncGridIn._write_asyncw  s&    <<"OOdll&7&7&99E%)%[0H ""8,x=5($$&&&doo..3x=DOO;""8,,,!$//22H 3x=DOO; 	8$  1$ **,&& '.,2s   AE+
D< D:D< =E+E#E+1E%22E+$E'%E+>E)?E+E+:D< <E EE  E+%E+'E+)E+c                P   K   |D ]  }| j                  |       d{     y7 w)zSWrite a sequence of strings to the file.

        Does not add separators.
        N)rO   )rF   sequencelines      r5   
writelineszAsyncGridIn.writelines  s,     
  	#D**T"""	#"s   &$&c                     yNTrq   r   s    r5   	writeablezAsyncGridIn.writeable      r7   c                   K   | S w)z)Support for the context manager protocol.rq   r   s    r5   
__aenter__zAsyncGridIn.__aenter__  s        c                t   K   || j                          d{    yt        j                  | dd       y7 w)zSupport for the context manager protocol.

        Close the file if no exceptions occur and allow exceptions to propagate.
        Nr   TF)r0  r   r   rF   exc_typeexc_valexc_tbs       r5   	__aexit__zAsyncGridIn.__aexit__  s@     
 **,  tY5  s   868r   )r   r#   r4   r   rL   r   r   r   )rH   r#   r   r   r   r   r   r   r   r   r   r   rz   r   r   r   )rz   r   r  r   r   r   )F)rQ   r   r'  r   r   r   )r'  r   r   r   )r   r   )rY   r   r   r   r_   )rA  r   r   r   )rQ   r   r   r   )r=  r   r   r   )rW  zIterable[Any]r   r   )r   rK   rc  r   rd  r   re  r   r   r   )%r   r   r   r   rI   r   r   r  propertyr  r   rP   __annotations__r^   rz   r   r	  r   r  r  r  r   r  r,  r1  r9  r&  r0  r=  rD  rG  rO   rO  rY  r\  r_  rf  rq   r7   r5   rK   rK   ;  s   (
 15V;(V; .V; 	V;
 
V;p)69CG	"=2   #5*NZ^_C_1*>RSHmS-j:QRD-R"5]#L-  &h0Q_cdFCd)+7R^bcJc%89t&K"  -qC  M((K$c
"$H$
.F6.;)z%(#r7   rK   c                  T    e Zd ZU dZ	 	 	 d>	 	 	 	 	 	 	 	 	 d? fdZ edd      Zded<    edd      Zded<    edd	      Z	ded
<    edd      Z
ded<    edd      Zded<    edd      Zded<    edd      Zded<    edd      Zded<    edd      Zded<    edd       Zded<   ded!<   ded"<   esd#ed$<   d@d%ZdAd&ZdBdCd'ZdBdDd(ZdEd)ZdFd*ZdGd+Zd@d,ZdHdId-ZdBdCd.ZdJd/ZefdKd0ZdGd1ZdLd2Z dE fd3Z!dMd4Z"dNd5Z#dGd6Z$dLd7Z%dOd8Z&dPd9Z'dEd:Z(dGd;Z)dQdRd<Z*dEd=Z+ xZ,S )SrV   z!Class to read data out of GridFS.c                f   t        |t              st        dt        |             t	        |       t        |      }t        |           |j                  | _	        |j                  | _        || _        t        | _        d| _        d| _        d| _        || _        || _        t(        sd| _        yy)a  Read a file from GridFS

        Application developers should generally not need to
        instantiate this class directly - instead see the methods
        provided by :class:`~gridfs.GridFS`.

        Either `file_id` or `file_document` must be specified,
        `file_document` will be given priority if present. Raises
        :class:`TypeError` if `root_collection` is not an instance of
        :class:`~pymongo.collection.AsyncCollection`.

        :param root_collection: root collection to read from
        :param file_id: value of ``"_id"`` for the file to read
        :param file_document: file document from
            `root_collection.files`
        :param session: a
            :class:`~pymongo.client_session.AsyncClientSession` to use for all
            commands

        .. versionchanged:: 3.8
           For better performance and to better follow the GridFS spec,
           :class:`GridOut` now uses a single cursor to read all the chunks in
           the file.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.0
           Creating a GridOut does not immediately retrieve the file metadata
           from the server. Metadata is fetched when first needed.
        r   r   NF)r<   r#   r=   r>   r6   r   superrI   rD   rE   rB   rC   _file_idr   r   _buffer_pos_chunk_iterr   r   r   r  r  )rF   r   rY   rc   r4   r  s        r5   rI   zAsyncGridOut.__init__  s    L /?;NtTcOdNef  	w'5oF&--%++"
DK r7   rP   r  r   r^   r  r   r  rz   r   r  r   r   r	  r
  r   r   r  r   ra   z'Date that this file was first uploaded.r  r  aliaseszJDEPRECATED, will be removed in PyMongo 5.0. List of aliases for this file.zOptional[list[str]]r   zMetadata attached to this file.r   r  r  r   rs  r   r  c                Z   K   | j                          d {   }|r|S t               7 wr   )readlinerj   )rF   rX  s     r5   	__anext__zAsyncGridOut.__anext__  s*     (D$&& )s   +)+c                D   K   | 2 cg c3 d {   }|7 6 c}S c c}w wr   rq   )rF   xs     r5   to_listzAsyncGridOut.to_list  s!     %)**A****s$    
 c                D   K   | j                  |d       d{   S 7 w)}Read one line or up to `size` bytes from the file.

            :param size: the maximum number of bytes to read
            T)rA  rX  N_read_size_or_liner@  s     r5   rv  zAsyncGridOut.readline  s$     
 00d0FFFFs     c                |  K   | j                          d{    g }t        | j                        | j                  z
  }d}|dkD  rp| j	                  d       d{   }|t        |      z  }|j                  |       t        | j                        | j                  z
  }d|cxk  r|k  r	 |S  |dkD  rp|S 7 7 ^w)r|  Nr   T)rX  )rW   r   r	  r   r~  r   r#  )rF   rA  lines	remainder
bytes_readrX  s         r5   	readlineszAsyncGridOut.readlines  s     
 ))+EDKK(4>>9IJa-!44$4??c$i'
T",t~~=	t(j(L ) a- L 
 @s)   B<B8AB<B:AB<6B<:B<c                6  K   | j                   st        | j                         | j                  j	                  d| j
                  i| j                         d {   | _         | j                   s%t        d| j                  d| j
                        y y 7 <w)NrP   r3   zno file in gridfs collection z
 with _id )r   r6   r   rC   r   rq  r   r   s    r5   rW   zAsyncGridOut.open.  s     zz"4==1#{{33UDMM4JTXTaTa3bbDJ::3DKK?*T]]L]^   bs   ABB=Bc                    t         r| j                          n| j                  st        d|z        || j                  v r| j                  |   S t	        d|z        )NzBYou must call AsyncGridOut.open() before accessing the %s propertyz$GridOut object has no attribute '%s')r  rW   r   r,   r  r  s     r5   r  zAsyncGridOut.__getattr__7  sY    IIK"TW[[  4::::d##CdJKKr7   c                     yr[  rq   r   s    r5   rD  zAsyncGridOut.readableB  r]  r7   c                  K   | j                          d{    t        | j                        | j                  z
  }t        }t        | j                        }|dkD  r| j                  | j                  d }n| j                  t        | j                        k  rt        || j                  z   |z        }| j                  't        | | j                  | j                  |      | _	        | j                  j                          d{   }|d   | j                  |z  d }|st        d      | xj                  t        |      z  c_        t        | _        d| _        |S 7 G7 [w)z{Reads a chunk at a time. If the current position is within a
        chunk the remainder of the chunk is returned.
        Nr   rQ   ztruncated chunk)rW   r   r   rr  r   r   r   r   r	  rs  _AsyncGridOutChunkIteratorrE   r   nextr   )rF   received
chunk_datar   chunk_numberr   s         r5   r   zAsyncGridOut.readchunkE  s,     iikt||$t'7'77
)
a<d&6&6&89J^^c$++..4>> 9ZGHL'#=$,,|$  **//11Evt~~
'B'DEJ%&788#j/)/ 	 2s#   E"EC-E"E AE" E"c                &  K   | j                          d{    t        | j                        | j                  z
  }|dk  s||kD  r|}|dk(  rt        S d}g }||k  rW||z
  }| j
                  ra| j
                  }| j                  }t        |      | j                  d }	t        | _        d| _        | xj                  t        |	      z  c_        n%| j                          d{   }d}t        |      }	|r/|j                  t        |||z         |z
  }
|
dk\  r||
z   dz   }|
dz   }t        |	      |kD  r[|j                  |	d|        || _        ||z   | _        | xj                  t        | j
                        | j                  z
  z  c_        n|j                  |	       |t        |	      z  }||k  rW||k(  r/| j                  r#	 | j                  j                          d{    dj!                  |      S 7 7 7 # t        $ r Y $w xY ww)z&Internal read() and readline() helper.Nr   r`   r7   )rW   r   r	  r   r   r   rr  
memoryviewr   r   re   r   r#  rs  r  rj   join)rF   rA  rX  r  r  rQ   neededbufchunk_startr  poss              r5   r~  zAsyncGridOut._read_size_or_lineb  s    iik$t~~5	!8ti'D19LoH_F||ll"..'_T-=-=-?@
$#$ #j/1 NN,,'_
hhuk;3GH;V!8#c>A-D 1WF:'Jw/0"#.#7 #dll"3d6F6F"FFJ'J'H9 o> 9!1!1&&++--- xx~_ 	* -, .% s_   HG:CH#G=$CH5HH $H %H )H=H H 	HHHHc                B   K   | j                  |       d{   S 7 w)a  Read at most `size` bytes from the file (less if there
        isn't enough data).

        The bytes are returned as an instance of :class:`bytes`
        If `size` is negative or omitted all data is read.

        :param size: the number of bytes to read

        .. versionchanged:: 3.8
           This method now only checks for extra chunks after reading the
           entire file. Previously, this method would check for extra chunks
           on every call.
        )rA  Nr}  r@  s     r5   r=  zAsyncGridOut.read  s"      ,,$,7777s   c                    | j                   S )z)Return the current position of this file.)r   r   s    r5   rP  zAsyncGridOut.tell  s    ~~r7   c                  K   |t         k(  r|}nG|t        k(  r| j                  |z   }n.|t        k(  rt	        | j
                        |z   }nt        dd      |dk  rt        dd      || j                  k(  r|S || _        t        | _        d| _	        | j                  r)| j                  j                          d{    d| _
        |S 7 w)aK  Set the current position of this file.

        :param pos: the position (or offset if using relative
           positioning) to seek to
        :param whence: where to seek
           from. :attr:`os.SEEK_SET` (``0``) for absolute file
           positioning, :attr:`os.SEEK_CUR` (``1``) to seek relative
           to the current position, :attr:`os.SEEK_END` (``2``) to
           seek relative to the file's end.

        .. versionchanged:: 4.1
           The method now returns the new position in the file, to
           conform to the behavior of :meth:`io.IOBase.seek`.
           zInvalid value for `whence`r   z*Invalid value for `pos` - must be positiveN)r   r   r   r   r   r	  OSErrorr   r   rr  rs  r0  )rF   r  whencenew_poss       r5   seekzAsyncGridOut.seek  s      YGy nns*Gy $++&,G":;;Q;"JKK dnn$N ""((***#D +s   B8C
:C;C
c                     yr[  rq   r   s    r5   rG  zAsyncGridOut.seekable  r]  r7   c                    | S )a-  Return an iterator over all of this file's data.

        The iterator will return lines (delimited by ``b'\n'``) of
        :class:`bytes`. This can be useful when serving files
        using a webserver that handles such an iterator efficiently.

        .. versionchanged:: 3.8
           The iterator now raises :class:`CorruptGridFile` when encountering
           any truncated, missing, or extra chunk in a file. The previous
           behavior was to only raise :class:`CorruptGridFile` on a missing
           chunk.

        .. versionchanged:: 4.0
           The iterator now iterates over *lines* in the file, instead
           of chunks, to conform to the base class :py:class:`io.IOBase`.
           Use :meth:`GridOut.readchunk` to read chunk by chunk instead
           of line by line.
        rq   r   s    r5   	__aiter__zAsyncGridOut.__aiter__  s	    & r7   c                   K   | j                   r)| j                   j                          d{    d| _         t        rt        |           yd| _        y7 (w)z(Make GridOut more generically file-like.NT)rs  r0  r  rp  r  )rF   r  s    r5   r0  zAsyncGridOut.close  sH     ""((***#DGMODK +s   *AA)Ac                ,    t        j                  d      )NrO   r>  )rF   r  s     r5   rO   zAsyncGridOut.write  s    %%g..r7   c                ,    t        j                  d      )NrY  r>  )rF   r  s     r5   rY  zAsyncGridOut.writelines  s    %%l33r7   c                     yrC  rq   r   s    r5   writablezAsyncGridOut.writable  rE  r7   c                   K   | S w)nMakes it possible to use :class:`AsyncGridOut` files
        with the async context manager protocol.
        rq   r   s    r5   r_  zAsyncGridOut.__aenter__  s      r`  c                @   K   | j                          d{    y7 w)r  NF)r0  rb  s       r5   rf  zAsyncGridOut.__aexit__  s      jjl 	s   c                ,    t        j                  d      )Nfilenor>  r   s    r5   r  zAsyncGridOut.fileno  s    %%h//r7   c                     y r   rq   r   s    r5   flushzAsyncGridOut.flush  s    r7   c                     yrC  rq   r   s    r5   isattyzAsyncGridOut.isatty  rE  r7   c                ,    t        j                  d      )Ntruncater>  r@  s     r5   r  zAsyncGridOut.truncate  s     %%j11r7   c                     y r   rq   r   s    r5   __del__zAsyncGridOut.__del__  s    r7   r   )
r   r#   rY   r   rc   r   r4   r   r   r   r   rJ  )r   list[bytes]rj  )rA  r   r   rJ  )rA  r   r   r  rg  ri  rh  )r_   F)rA  r   rX  r   r   rJ  )r   r   )r  r   r  r   r   r   r   rV   )r  r   r   r   )r  r   r   r   rk  )r   r   r   )rA  r   r   r   )-r   r   r   r   rI   r   rP   rm  r^   rz   r   r	  r   r  rt  r   r  r  rw  rz  rv  r  rW   r  rD  r   r~  r=  rP  r   r  rG  r  r0  rO   rY  r  r_  rf  r  r  r  r  r  __classcell__r  s   @r5   rV   rV     s   +
 "&'+04< (<  <  %	< 
 .<  
< | $E+OPCP(5IJHcJ$Z1HID#I"6]#L-  'x1RSFCS*;8STJT%9?&K"  $8_$G   -A5-H)  .qC 
 J	'	+	G	&	L:1f8  2; %N*/402r7   rV   c                  l    e Zd ZU dZ	 	 	 	 	 	 	 	 	 	 ddZded<   ddZddZddZddZ	dd	Z
e
Zdd
Zy)r  zIterates over a file's chunks using a single cursor.

    Raises CorruptGridFile when encountering any truncated, missing, or extra
    chunk in a file.
    c                :   |j                   | _         t        |j                        | _        t        |j                        | _        || _        || _        || _        t        j                  t        | j
                        | j                  z        | _        d | _        y r   )rP   r   r   _chunk_sizer	  _lengthrE   r   _next_chunkmathceilfloat_num_chunks_cursor)rF   grid_outrD   r4   
next_chunks        r5   rI   z#_AsyncGridOutChunkIterator.__init__%  st     <<x2238??+%99U4<<%84;K;K%KLr7   zOptional[AsyncCursor]r  c                    || j                   dz
  k  r| j                  S | j                  | j                  | j                   dz
  z  z
  S )Nr`   )r  r  r  )rF   chunk_ns     r5   expected_chunk_lengthz0_AsyncGridOutChunkIterator.expected_chunk_length7  sF    T%%))###||t//43C3Ca3GHIIr7   c                    | S r   rq   r   s    r5   r  z$_AsyncGridOutChunkIterator.__aiter__<      r7   c                    d| j                   i}| j                  dkD  rd| j                  i|d<   t        | j                         | j                  j                  |dg| j                        | _        y )Nrt   r   z$gter  )r  r`   )ri   r4   )rP   r  r6   r   rE   re   r  )rF   r}   s     r5   _create_cursorz)_AsyncGridOutChunkIterator._create_cursor?  sa    dhh'a!4#3#34F3Kt}}-||((xj$--(Xr7   c                r  K   | j                   | j                          | j                   J 	 | j                   j                          d{   S 7 # t        $ rY | j                   j	                          d{  7   | j                          | j                   j                          d{  7  cY S w xY ww)a  Return the next chunk and retry once on CursorNotFound.

        We retry on CursorNotFound to maintain backwards compatibility in
        cases where two calls to read occur more than 10 minutes apart (the
        server's default cursor timeout).
        N)r  r  r  r*   r0  r   s    r5   _next_with_retryz+_AsyncGridOutChunkIterator._next_with_retryF  s      <<!<<+++	-**,,,, 	-,,$$&&&!**,,,,	-sR   +B7A AA B7A &B48A;92B4+B.,B41B73B44B7c           	       K   	 | j                          d {   }|d   | j                  k7  r5| j                          d {    t	        d| j                  |d   fz        |d   | j                  k\  rCt        |d         r5| j                          d {    t	        d| j                  |d   fz        | j                  |d         }t        |d         |k7  r8| j                          d {    t	        d|d   |t        |d         fz        | xj                  dz  c_        |S 7 # t        $ r4 | j                  | j                  k\  r t	        d| j                  z        d w xY w7 .7 7 w)Nzno chunk #%dr  z;Missing chunk: expected chunk #%d but found chunk with n=%drQ   z?Extra chunk found: expected %d chunks but found chunk with n=%dzRtruncated chunk #%d: expected chunk length to be %d but found chunk with length %dr`   )r  rj   r  r  r   r0  r   r  )rF   r   expected_lengths      r5   r  z_AsyncGridOutChunkIterator.nextW  s    	O//11E :)))**,!"%)%5%5uSz$BC 
 :)))5=!jjl""%&)-)9)95:(FG 
 44U3Z@uV}0**,!-05c
OSQVW]Q^M_/`a 
 	A? 2! 	O4#3#33!.43C3C"CD$N	O  # s]   E6D/ D,D/ %E6E/AE6E2AE60E41;E6,D/ /=E,,E62E64E6c                |   K   | j                   r*| j                   j                          d {    d | _         y y 7 wr   )r  r0  r   s    r5   r0  z _AsyncGridOutChunkIterator.close|  s2     <<,,$$&&&DL &s   *<:<N)
r  rV   rD   r#   r4   r   r  r   r   r   )r  r   r   r   )r   r  rg  )r   zMapping[str, Any])r   r   r   r   rI   rm  r  r  r  r  r  rw  r0  rq   r7   r5   r  r    sl       .	
  
  #"J
Y-"!F I r7   r  c                  4    e Zd Z	 	 	 	 	 	 ddZddZddZeZy)AsyncGridOutIteratorc                *    t        |||d      | _        y rU  )r  rs  )rF   r  rD   r4   s       r5   rI   zAsyncGridOutIterator.__init__  s     6hQRSr7   c                    | S r   rq   r   s    r5   r  zAsyncGridOutIterator.__aiter__  r  r7   c                n   K   | j                   j                          d {   }t        |d         S 7 w)NrQ   )rs  r  rJ  )rF   r   s     r5   r  zAsyncGridOutIterator.next  s1     &&++--U6]## .s   535N)r  rV   rD   r#   r4   r"   )r   r  r  )r   r   r   rI   r  r  rw  rq   r7   r5   r  r    s4    T$T.=THZT
$ Ir7   r  c                       e Zd ZdZ	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	 fdZd
 fdZdddZeZddZddZ	ddZ
 xZS )r   zA cursor / iterator for returning GridOut objects as the result
    of an arbitrary query against the GridFS files collection.
    c	           
         t        |       t        |      }|| _        t        	|   |j
                  |||||||       y)ay  Create a new cursor, similar to the normal
        :class:`~pymongo.cursor.Cursor`.

        Should not be called directly by application developers - see
        the :class:`~gridfs.GridFS` method :meth:`~gridfs.GridFS.find` instead.

        .. versionadded 2.7

        .. seealso:: The MongoDB documentation on `cursors <https://dochub.mongodb.org/core/cursors>`_.
        )rh   rg   no_cursor_timeoutri   
batch_sizer4   N)r6   r   _root_collectionrp  rI   rB   )
rF   rH   r}   rh   rg   r  ri   r  r4   r  s
            r5   rI   zAsyncGridOutCursor.__init__  sQ    * 	w'0<
 !+/! 	 		
r7   c                   K   t        | j                         t        |           d{   }t	        | j
                  || j                        S 7 &w)z$Get next GridOut object from cursor.Nrb   )r6   r4   rp  r  rV   r  )rF   	next_filer  s     r5   r  zAsyncGridOutCursor.next  sB     t||,',.(	D11TXT`T`aa )s   'AA'Ac                   K   || 2 cg c3 d{   }||dk  rt        d      g }t        |      D ])  }|j                  | j                          d{          + |S 7 R6 c}S c c}w 7 w)zConvert the cursor to a list.Nr`   z'to_list() length must be greater than 0)rI  ranger#  r  )rF   r	  ry  ret_s        r5   rz  zAsyncGridOutCursor.to_list  sr     >%)**AA:FGGv 	*AJJTYY[()	*
 +***
 )sA   A/A(A$A"
A$A(>A/A-
A/"A$$A(%	A/c                    t        d      Nz'Method does not exist for GridOutCursorNotImplementedErrorr   s      r5   
add_optionzAsyncGridOutCursor.add_option      !"KLLr7   c                    t        d      r  r  r   s      r5   remove_optionz AsyncGridOutCursor.remove_option  r  r7   c                0    t        | j                  |      S )zACreates an empty GridOutCursor for information to be copied into.r3   )r   r  )rF   r4   s     r5   _clone_basezAsyncGridOutCursor._clone_base  s    !$"7"7IIr7   )Nr   r   FNr   N)rH   r#   r}   r   rh   r   rg   r   r  r   ri   r   r  r   r4   r   r   r   r  r   )r	  r   r   zlist[AsyncGridOut])r~   r   rL   r   r   r   )r4   r   r   r   )r   r   r   r   rI   r  rz  rw  r  r  r  r  r  s   @r5   r   r     s     /3"'"04$
#$
 ,$
 	$

 $
  $
 $
 $
 .$
 
$
Lb	 IMMJr7   r   )r4   r   r   r   )Pr   
__future__r   r4  rM  r   r  collectionsr   typingr   r   r   r   r	   r
   
bson.int64r   bson.objectidr   gridfs.errorsr   r   r   gridfs.grid_file_sharedr   r   r   r   r   r   r   r   r   r   r   r   r   r   pymongor   r   r    r!   #pymongo.asynchronous.client_sessionr"   pymongo.asynchronous.collectionr#   pymongo.asynchronous.cursorr$   pymongo.asynchronous.databaser%   pymongo.asynchronous.helpersr&   pymongo.commonr'   pymongo.errorsr(   r)   r*   r+   r,   r-   pymongo.helpers_sharedr.   pymongo.read_preferencesr/   r0   r  r6   r9   r   rK   IOBaser   GRIDOUT_BASE_CLASSrV   r  r  r   rq   r7   r5   <module>r     s    5 "   	   C C  " = =     ? > B ; 3 7 . *  A @V
D DNk	 k	\l l^ #+RYY n% nba  a H  FJ FJr7   