How to use aiozk - 10 common examples

To help you get started, we’ve selected a few aiozk examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github micro-fan / aiozk / aiozk / recipes / base_lock.py View on Github external
state_fut, states.States.LOST)
                fut.cancel()

            await self.delete_unique_znode(znode_label)

        class Lock:
            async def __aenter__(self):
                return self

            async def __aexit__(self, exc_type, exc, tb):
                await on_exit()

        return Lock()


class LockLostError(exc.ZKError):
    pass
github micro-fan / aiozk / aiozk / recipes / counter.py View on Github external
async def start(self):
        base, _leaf = self.base_path.rsplit("/", 1)
        if base:
            await self.client.ensure_path(base)
        try:
            await self.client.create(self.base_path, str(self._default))
            self.value = self._default
            self._version = 0
        except exc.NodeExists:
            await self._fetch()
github micro-fan / aiozk / aiozk / client.py View on Github external
acl = acl or self.default_acl

        paths_to_make = []
        for segment in path[1:].split("/"):
            if not paths_to_make:
                paths_to_make.append("/" + segment)
                continue

            paths_to_make.append("/".join([paths_to_make[-1], segment]))

        while paths_to_make:
            path = paths_to_make[0]

            if self.features.create_with_stat:
                request = protocol.Create2Request(path=path, acl=acl)
            else:
                request = protocol.CreateRequest(path=path, acl=acl)
            request.set_flags(
                ephemeral=False, sequential=False, container=self.features.containers
            )

            try:
                await self.send(request)
            except exc.NodeExists:
                pass

            paths_to_make.pop(0)
github micro-fan / aiozk / aiozk / transaction.py View on Github external
async def commit(self):
        if not self.request.requests:
            raise ValueError("No operations to commit.")

        response = await self.client.send(self.request)
        pairs = zip(self.request.requests, response.responses)

        result = Result()
        for request, reply in pairs:
            if isinstance(reply, protocol.CheckVersionResponse):
                result.checked.add(self.client.denormalize_path(request.path))
            elif isinstance(reply, protocol.CreateResponse):
                result.created.add(self.client.denormalize_path(request.path))
            elif isinstance(reply, protocol.SetDataResponse):
                result.updated.add(self.client.denormalize_path(request.path))
            elif isinstance(reply, protocol.DeleteResponse):
                result.deleted.add(self.client.denormalize_path(request.path))

        return result
github micro-fan / aiozk / aiozk / recipes / barrier.py View on Github external
async def wait(self, timeout=None):
        barrier_lifted = self.client.wait_for_events(
            [WatchEvent.DELETED], self.path
        )

        exists = await self.client.exists(path=self.path, watch=True)
        if not exists:
            return

        try:
            if timeout:
                await asyncio.wait_for(barrier_lifted, timeout)
            else:
                await barrier_lifted
        except asyncio.TimeoutError:
            raise exc.TimeoutError
github micro-fan / aiozk / aiozk / recipes / base_lock.py View on Github external
async def on_exit():
            state["acquired"] = False
            if not fut.done():
                if not state_fut.done():
                    self.client.session.state.remove_waiting(
                        state_fut, states.States.LOST)
                fut.cancel()

            await self.delete_unique_znode(znode_label)
github micro-fan / aiozk / aiozk / recipes / barrier.py View on Github external
import asyncio

from aiozk import exc, WatchEvent

from .recipe import Recipe


class Barrier(Recipe):

    def __init__(self, path):
        super().__init__()
        self.path = path

    async def create(self):
        await self.ensure_path()
        await self.create_znode(self.path)

    async def lift(self):
        try:
            await self.client.delete(self.path)
        except exc.NoNode:
            pass

    async def wait(self, timeout=None):
github micro-fan / aiozk / aiozk / recipes / sequential.py View on Github external
import asyncio
import logging
import re
import uuid

from aiozk import exc, WatchEvent, RetryPolicy, states

from .recipe import Recipe


log = logging.getLogger(__name__)

sequential_re = re.compile(r'.*[0-9]{10}$')


class SequentialRecipe(Recipe):

    def __init__(self, base_path):
        super().__init__(base_path)
        self.guid = uuid.uuid4().hex

        self.owned_paths = {}

    def sequence_number(self, sibling):
        return int(sibling[-10:])

    def determine_znode_label(self, sibling):
        return sibling.rsplit("-", 2)[0]

    def sibling_path(self, path):
        return "/".join([self.base_path, path])
github micro-fan / aiozk / aiozk / connection.py View on Github external
with suppress(asyncio.CancelledError):
                await self.read_loop_task

        if self.pending or (self.pending_specials and self.pending_specials != {None: []}):
            log.warning('Pendings: {}; specials:  {}'.format(self.pending, self.pending_specials))

        try:
            # await list(pending_with_timeouts)
            self.abort(exception=exc.TimeoutError)
            # wlist = list(self.drain_all_pending())
            # log.warning('Wait for list: {} {}'.format(wlist, self.pending))
            # if len(wlist) > 0:
            #     await asyncio.wait(wlist, timeout=timeout)
        except asyncio.TimeoutError:
            log.warning('ABORT Timeout')
            await self.abort(exception=exc.TimeoutError)
        except Exception as e:
            log.exception('in close: {}'.format(e))
            raise e
        finally:
            log.debug('Closing writer')
            self.writer.close()
            log.debug('Writer closed')
github micro-fan / aiozk / aiozk / connection.py View on Github external
async def close(self, timeout):
        if self.closing:
            return
        self.closing = True

        if self.read_loop_task:
            self.read_loop_task.cancel()
            with suppress(asyncio.CancelledError):
                await self.read_loop_task

        if self.pending or (self.pending_specials and self.pending_specials != {None: []}):
            log.warning('Pendings: {}; specials:  {}'.format(self.pending, self.pending_specials))

        try:
            # await list(pending_with_timeouts)
            self.abort(exception=exc.TimeoutError)
            # wlist = list(self.drain_all_pending())
            # log.warning('Wait for list: {} {}'.format(wlist, self.pending))
            # if len(wlist) > 0:
            #     await asyncio.wait(wlist, timeout=timeout)
        except asyncio.TimeoutError:
            log.warning('ABORT Timeout')
            await self.abort(exception=exc.TimeoutError)
        except Exception as e:
            log.exception('in close: {}'.format(e))
            raise e
        finally:
            log.debug('Closing writer')
            self.writer.close()
            log.debug('Writer closed')