# -*- coding: utf-8 -*-
from setuptools import setup

package_dir = \
{'': 'src'}

packages = \
['meta_memcache', 'meta_memcache.base', 'meta_memcache.events']

package_data = \
{'': ['*']}

install_requires = \
['uhashring>=2.1,<3.0']

setup_kwargs = {
    'name': 'meta-memcache',
    'version': '0.9.4',
    'description': 'Modern, pure python, memcache client with support for new meta commands.',
    'long_description': '# meta-memcache-py\nModern, pure python, memcache client with support for new meta commands.\n\n# Usage:\n\n## Install:\n```\npip install meta-memcache\n```\n## Configure a pool:\n```python:\nfrom meta_memcache import (\n    Key,\n    ServerAddress,\n    ShardedCachePool,\n    connection_pool_factory_builder,\n)\n\npool = ShardedCachePool.from_server_addresses(\n    servers=[\n        ServerAddress(host="1.1.1.1", port=11211),\n        ServerAddress(host="2.2.2.2", port=11211),\n        ServerAddress(host="3.3.3.3", port=11211),\n    ],\n    connection_pool_factory_fn=connection_pool_factory_builder(),\n)\n```\n\nThe design is very pluggable. Rather than supporting a lot of features, it\nrelies on dependency injection to configure behavior.\n\nThe `CachePool`s expects a `connection_pool_factory_fn` callback to build the\ninternal connection pool. And the connection pool receives a function to create\na new memcache connection.\n\nWhile this is very flexible, it can be complex to initialize, so there is a\ndefault builder provided to tune the most frequent things:\n```\ndef connection_pool_factory_builder(\n    initial_pool_size: int = 1,\n    max_pool_size: int = 3,\n    mark_down_period_s: float = DEFAULT_MARK_DOWN_PERIOD_S,\n    connection_timeout: float = 1,\n    recv_timeout: float = 1,\n    no_delay: bool = True,\n    read_buffer_size: int = 4096,\n) -> Callable[[ServerAddress], ConnectionPool]:\n```\n* `initial_pool_size`: How many connections open for each host in the pool\n* `max_pool_size`: Maximum number of connections to keep open for each host in\n  the pool. Note that if there are no connections available in the pool, the\n  client will open a new connection always, instead of just blocking waiting\n  for a free connection. If you see too many connection creations in the\n  stats, you might need to increase this setting.\n* `mark_down_period_s`: When a network failure is detected, the destination host\n  is marked down, and requests will fail fast, instead of trying to reconnect\n  causing clients to block. A single client request will be checking if the host\n  is still down every `mark_down_period_s`, while the others fail fast.\n* `connection_timeout`: Timeout to stablish initial connection, ideally should\n  be < 1 s for memcache servers in local network.\n* `recv_timeout`: Timeout of requests. Ideally should be < 1 s for memcache\n  servers in local network.\n* `no_delay`: Wether to configure socket with NO_DELAY. This library tries to\n  send requests as a single write(), so enabling no_delay is a good idea.\n* `read_buffer_size`: This client tries to minimize memory allocation by reading\n  bytes from the socket into a reusable read buffer. If the memcache response\n  size is < `read_buffer_size` no memory allocations happen for the network\n  read. Note: Each connection will have its own read buffer, so you must find a\n  good balance between memory usage and reducing memory allocations. Note: While\n  reading from the socket has zero allocations, the values will be deserialized\n  and those will have the expected memory allocations.\n\nIf you need to customize how the sockets are created (IPv6, add auth, unix\nsockets) you will need to implement your own `connection_pool_factory_builder`\nand override the `socket_factory_fn`.\n\n## Use the pool:\n```python:\ncache_pool.set(key=Key("bar"), value=1, ttl=1000)\n```\n\n## Keys:\n### String or `Key` named tuple\nOn the high-level commands you can use either plain strings as keys\nor the more advanced `Key` object that allows extra features like\ncustom routing and unicode keys.\n\n### Custom routing:\nYou can control the routing of the keys setting a custom `routing_key`:\n```python:\nKey("key:1:2", routing_key="key:1")\n```\nThis is useful if you have several keys related with each other. You can use the\nsame routing key, and they will be placed in the same server. This is handy for\nspeed of retrieval (single request instead of fan-out) and/or consistency (all\nwill be gone or present, since they are stored in the same server). Note this is\nalso risky, if you place all keys of a user in the same server, and the server\ngoes down, the user life will be miserable.\n\n### Unicode keys:\nUnicode keys are supported, the keys will be hashed according to Meta commands\n[binary encoded keys](https://github.com/memcached/memcached/wiki/MetaCommands#binary-encoded-keys)\nspecification.\n\nTo use this, mark the key as unicode:\n```python:\nKey("🍺", unicode=True)\n```\n\n### Large keys:\nLarge keys are also automatically supported and binary encoded as above. But\ndon\'t use large keys :)\n\n# Design:\nThe code relies on dependency injection to allow to configure a lot of the\naspects of the cache client. For example, instead of supporting a lot of\nfeatures on how to connect, authenticate, etc, a `socket_factory_fn` is required\nand you can customize the socket creation to your needs. We provide some basic\nsane defaults, but you should not have a lot of issues to customize it for your\nneeds.\n\nRegarding cache client features, relies in inheritance to abstract different\nlayers of responsibility, augment the capabilities while abstracting details\nout:\n\n## Low level meta commands:\n\nThe low-level class is\n[BaseCachePool](https://github.com/RevenueCat/meta-memcache-py/blob/main/src/meta_memcache/base/base_cache_pool.py).\nImplements the connection pool handling as well as the memcache protocol,\nfocusing on the new\n[Memcache MetaCommands](https://github.com/memcached/memcached/blob/master/doc/protocol.txt#L79):\nmeta get, meta set, meta delete and meta arithmetic. They implement the full set\nof flags, and features, but are very low level.\n\n```python:\n    def meta_multiget(\n        self,\n        keys: List[Key],\n        flags: Optional[Set[Flag]] = None,\n        int_flags: Optional[Dict[IntFlag, int]] = None,\n        token_flags: Optional[Dict[TokenFlag, bytes]] = None,\n    ) -> Dict[Key, ReadResponse]:\n\n    def meta_get(\n        self,\n        key: Key,\n        flags: Optional[Set[Flag]] = None,\n        int_flags: Optional[Dict[IntFlag, int]] = None,\n        token_flags: Optional[Dict[TokenFlag, bytes]] = None,\n    ) -> ReadResponse:\n\n    def meta_set(\n        self,\n        key: Key,\n        value: Any,\n        ttl: int,\n        flags: Optional[Set[Flag]] = None,\n        int_flags: Optional[Dict[IntFlag, int]] = None,\n        token_flags: Optional[Dict[TokenFlag, bytes]] = None,\n    ) -> WriteResponse:\n\n    def meta_delete(\n        self,\n        key: Key,\n        flags: Optional[Set[Flag]] = None,\n        int_flags: Optional[Dict[IntFlag, int]] = None,\n        token_flags: Optional[Dict[TokenFlag, bytes]] = None,\n    ) -> WriteResponse:\n\n    def meta_arithmetic(\n        self,\n        key: Key,\n        flags: Optional[Set[Flag]] = None,\n        int_flags: Optional[Dict[IntFlag, int]] = None,\n        token_flags: Optional[Dict[TokenFlag, bytes]] = None,\n    ) -> WriteResponse:\n```\n\nYou won\'t use this api unless you are implementing some custom high-level\ncommand. See below for the usual memcache api.\n\n## High level commands:\n\nThe\n[CachePool](https://github.com/RevenueCat/meta-memcache-py/blob/main/src/meta_memcache/base/cache_pool.py)\naugments the low-level class and implements the more high-level memcache\noperations (get, set, touch, cas...), plus the memcached\'s\n[new MetaCommands anti-dogpiling techniques](https://github.com/memcached/memcached/wiki/MetaCommands)\nfor high qps caching needs: Atomic Stampeding control, Herd Handling, Early\nRecache, Serve Stale, No Reply, Probabilistic Hot Cache, Hot Key Cache\nInvalidation...\n\n```python:\n    def set(\n        self,\n        key: Union[Key, str],\n        value: Any,\n        ttl: int,\n        no_reply: bool = False,\n        cas_token: Optional[int] = None,\n        stale_policy: Optional[StalePolicy] = None,\n        set_mode: SetMode = SetMode.SET,  # Other are ADD, REPLACE, APPEND...\n    ) -> bool:\n\n    def delete(\n        self,\n        key: Union[Key, str],\n        cas_token: Optional[int] = None,\n        no_reply: bool = False,\n        stale_policy: Optional[StalePolicy] = None,\n    ) -> bool:\n\n    def touch(\n        self,\n        key: Union[Key, str],\n        ttl: int,\n        no_reply: bool = False,\n    ) -> bool:\n\n    def get_or_lease(\n        self,\n        key: Union[Key, str],\n        lease_policy: LeasePolicy,\n        touch_ttl: Optional[int] = None,\n        recache_policy: Optional[RecachePolicy] = None,\n    ) -> Optional[Any]:\n\n    def get_or_lease_cas(\n        self,\n        key: Union[Key, str],\n        lease_policy: LeasePolicy,\n        touch_ttl: Optional[int] = None,\n        recache_policy: Optional[RecachePolicy] = None,\n    ) -> Tuple[Optional[Any], Optional[int]]:\n\n    def get(\n        self,\n        key: Union[Key, str],\n        touch_ttl: Optional[int] = None,\n        recache_policy: Optional[RecachePolicy] = None,\n    ) -> Optional[Any]:\n\n    def multi_get(\n        self,\n        keys: List[Union[Key, str]],\n        touch_ttl: Optional[int] = None,\n        recache_policy: Optional[RecachePolicy] = None,\n    ) -> Dict[Key, Optional[Any]]:\n\n    def get_cas(\n        self,\n        key: Union[Key, str],\n        touch_ttl: Optional[int] = None,\n        recache_policy: Optional[RecachePolicy] = None,\n    ) -> Tuple[Optional[Any], Optional[int]]:\n\n    def get_typed(\n        self,\n        key: Union[Key, str],\n        cls: Type[T],\n        touch_ttl: Optional[int] = None,\n        recache_policy: Optional[RecachePolicy] = None,\n        error_on_type_mismatch: bool = False,\n    ) -> Optional[T]:\n\n    def get_cas_typed(\n        self,\n        key: Union[Key, str],\n        cls: Type[T],\n        touch_ttl: Optional[int] = None,\n        recache_policy: Optional[RecachePolicy] = None,\n        error_on_type_mismatch: bool = False,\n    ) -> Tuple[Optional[T], Optional[int]]:\n\n    def delta(\n        self,\n        key: Union[Key, str],\n        delta: int,\n        refresh_ttl: Optional[int] = None,\n        no_reply: bool = False,\n        cas_token: Optional[int] = None,\n    ) -> bool:\n\n    def delta_initialize(\n        self,\n        key: Union[Key, str],\n        delta: int,\n        initial_value: int,\n        initial_ttl: int,\n        refresh_ttl: Optional[int] = None,\n        no_reply: bool = False,\n        cas_token: Optional[int] = None,\n    ) -> bool:\n\n    def delta_and_get(\n        self,\n        key: Union[Key, str],\n        delta: int,\n        refresh_ttl: Optional[int] = None,\n        cas_token: Optional[int] = None,\n    ) -> Optional[int]:\n\n    def delta_initialize_and_get(\n        self,\n        key: Union[Key, str],\n        delta: int,\n        initial_value: int,\n        initial_ttl: int,\n        refresh_ttl: Optional[int] = None,\n        cas_token: Optional[int] = None,\n    ) -> Optional[int]:\n```\n\n# Anti-dogpiling techniques\nSome commands receive `RecachePolicy`, `StalePolicy` and `LeasePolicy` for the\nadvanced anti-dogpiling control needed in high-qps environments:\n\n```python:\nclass RecachePolicy(NamedTuple):\n    """\n    This controls the recache herd control behavior\n    If recache ttl is indicated, when remaining ttl is < given value\n    one of the clients will win, return a miss and will populate the\n    value, while the other clients will loose and continue to use the\n    stale value.\n    """\n\n    ttl: int = 30\n\n\nclass LeasePolicy(NamedTuple):\n    """\n    This controls the lease or miss herd control behavior\n    If miss lease retries > 0, on misses a lease will be created. The\n    winner will get a Miss and will continue to populate the cache,\n    while the others are BLOCKED! Use with caution! You can define\n    how many times and how often clients will retry to get the\n    value. After the retries are expired, clients will get a Miss\n    if they weren\'t able to get the value.\n    """\n\n    ttl: int = 30\n    miss_retries: int = 3\n    miss_retry_wait: float = 1.0\n    wait_backoff_factor: float = 1.2\n    miss_max_retry_wait: float = 5.0\n\n\nclass StalePolicy(NamedTuple):\n    """\n    This controls the stale herd control behavior\n    * Deletions can mark items stale instead of deleting them\n    * Stale items automatically do recache control, one client\n      will get the miss, others will receive the stale value\n      until the winner refreshes the value in the cache.\n    * cas mismatches (due to race / further invalidation) can\n      store the value as stale instead of failing\n    """\n\n    mark_stale_on_deletion_ttl: int = 0  # 0 means disabled\n    mark_stale_on_cas_mismatch: bool = False\n``` \n\n### Notes:\n* Recache/Stale policies are typically used together. Make sure all your reads\n  for a given key share the same recache policy to avoid unexpected behaviors.\n* Leases are for a more traditional, more consistent model, where other clients\n  will block instead of getting a stale value.\n\n## Pool level features:\nFinally in\n[`cache_pools.py`](https://github.com/RevenueCat/meta-memcache-py/blob/main/src/meta_memcache/cache_pools.py)\na few classes implement the pool-level semantics:\n* `ShardedCachePool`: implements a consistent hashing cache pool using uhashring\'s `HashRing`.\n* `ShardedWithGutterCachePool`: implements a sharded cache pool like above, but\n  with a \'gutter pool\' (See\n  [Scaling Memcache at Facebook](http://www.cs.utah.edu/~stutsman/cs6963/public/papers/memcached.pdf)),\n  so when a server of the primary pool is down, requests are sent to the\n  \'gutter\' pool, with TTLs overriden and lowered on the fly, so they provide\n  some level of caching instead of hitting the backend for each request.\n\nThese pools also provide an option to register a callback for write failure events. This might be useful\nif you are serious about cache consistency. If you have transient network issues, some writes might fail,\nand if the server comes back without being restarted or the cache flushed, the data will be stale. The\nevents allows for failed writes to be collected and logged. Affected keys can then be invalidated later\nand eventual cache consistency guaranteed.\n\nIt should be trivial to implement your own cache pool if you need custom\nsharding, shadowing, pools that support live migrations, etc. Feel free to\ncontribute!\n\n## Write failure tracking\nWhen a write failure occures with a `SET` or `DELETE` opperation occures then the `pool.on_write_failure` event\nhandler will be triggered. Consumers subscribing to this handler will receive the key that failed. The\nfollowing is an example on how to subscribe to these events:\n```python:\nfrom meta_memcache import CachePool, Key\n\nclass SomeConsumer(object):\n    def __init__(self, pool: CachePool):\n        self.pool = pool\n        self.pool.on_write_failures += self.on_write_failure_handler\n\n    def call_before_dereferencing(self):\n        self.pool.on_write_failures -= self.on_write_failure_handler\n\n    def on_write_failure_handler(self, key: Key) -> None:\n        # Handle the failures here\n        pass\n        \n```\n\n## Stats:\nThe cache pools offer a `get_counters()` that return information about the state\nof the servers and their connection pools:\n\n```python:\n    def get_counters(self) -> Dict[ServerAddress, PoolCounters]:\n```\n\nThe counters are:\n```python:\nclass PoolCounters(NamedTuple):\n    # Available connections in the pool, ready to use\n    available: int\n    # The # of connections active, currently in use, out of the pool\n    active: int\n    # Current stablished connections (available + active)\n    stablished: int\n    # Total # of connections created. If this keeps growing\n    # might mean the pool size is too small and we are\n    # constantly needing to create new connections:\n    total_created: int\n    # Total # of connection or socket errors\n    total_errors: int\n```\n\n',
    'author': 'Guillermo Perez',
    'author_email': 'bisho@revenuecat.com',
    'maintainer': 'None',
    'maintainer_email': 'None',
    'url': 'https://github.com/RevenueCat/meta-memcache-py',
    'package_dir': package_dir,
    'packages': packages,
    'package_data': package_data,
    'install_requires': install_requires,
    'python_requires': '>=3.8,<4.0',
}


setup(**setup_kwargs)
