a
    �Ï?e¼	  ã                   @  s€   d Z ddlmZ ddlmZ ddlmZmZ ddlZddl	m
Z
 ddlmZmZmZ edƒZdeje
jfd	d
dddœdd„ZdS )z2
Helpers related to (dynamic) resource retrieval.
é    )Úannotations©Ú	lru_cache)ÚCallableÚTypeVarN)ÚResource)ÚURIÚDÚRetrieveÚ_Tz+Callable[[Retrieve[D]], Retrieve[D]] | NonezCallable[[_T], D]zCallable[[D], Resource[D]]z,Callable[[Callable[[URI], _T]], Retrieve[D]])ÚcacheÚloadsÚfrom_contentsÚreturnc                   s,   ˆ du rt dd�‰ ddœ‡ ‡‡fdd„}|S )a  
    Create a retriever which caches its return values from a simpler callable.

    Takes a function which returns things like serialized JSON (strings) and
    returns something suitable for passing to `Registry` as a retrieve
    function.

    This decorator both reduces a small bit of boilerplate for a common case
    (deserializing JSON from strings and creating `Resource` objects from the
    result) as well as makes the probable need for caching a bit easier.
    Retrievers which otherwise do expensive operations (like hitting the
    network) might otherwise be called repeatedly.

    Examples
    --------

    .. testcode::

        from referencing import Registry
        import referencing.retrieval


        @referencing.retrieval.to_cached_resource()
        def retrieve(uri: str):
            print(f"Retrieved {uri}")

            # Normally, go get some expensive JSON from the network, a file ...
            return '''
                {
                    "$schema": "https://json-schema.org/draft/2020-12/schema",
                    "foo": "bar"
                }
            '''

        one = Registry(retrieve=retrieve).get_or_retrieve("urn:example:foo")
        print(one.value.contents["foo"])

        # Retrieving the same URI again reuses the same value (and thus doesn't
        # print another retrieval message here)
        two = Registry(retrieve=retrieve).get_or_retrieve("urn:example:foo")
        print(two.value.contents["foo"])

    .. testoutput::

        Retrieved urn:example:foo
        bar
        bar

    N)ÚmaxsizezCallable[[URI], _T]©Úretrievec                   s   ˆddœ‡‡‡ fdd„ƒ}|S )Nr   )Úuric                   s   ˆ| ƒ}ˆ|ƒ}ˆ |ƒS )N© )r   ÚresponseÚcontents)r   r   r   r   úX/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/referencing/retrieval.pyÚcached_retrieveK   s    z>to_cached_resource.<locals>.decorator.<locals>.cached_retriever   )r   r   ©r   r   r   r   r   Ú	decoratorJ   s    z%to_cached_resource.<locals>.decoratorr   )r   r   r   r   r   r   r   Úto_cached_resource   s    6
	r   )Ú__doc__Ú
__future__r   Ú	functoolsr   Útypingr   r   ÚjsonZreferencingr   Zreferencing.typingr   r	   r
   r   r   r   r   r   r   r   r   Ú<module>   s   ý