connection.py 5.88 KB
Newer Older
davebshow's avatar
davebshow committed
1
2
3
4
5
6
7
8
9
10
11
12
import asyncio
import logging
import uuid

try:
    import ujson as json
except ImportError:
    import json

from aiogremlin.driver import provider, resultset
from aiogremlin.driver.protocol import GremlinServerWSProtocol
from aiogremlin.driver.aiohttp.transport import AiohttpTransport
13
from gremlin_python.driver import serializer
davebshow's avatar
davebshow committed
14
15
16
17
18
19
20
21
22
23
24
25


logger = logging.getLogger(__name__)


class Connection:
    """
    Main classd for interacting with the Gremlin Server. Encapsulates a
    websocket connection. Not instantiated directly. Instead use
    :py:meth:`Connection.open<aiogremlin.connection.Connection.open>`.

    :param str url: url for host Gremlin Server
26
    :param gremlin_python.driver.transport.AbstractBaseTransport transport:
davebshow's avatar
davebshow committed
27
        Transport implementation
28
    :param gremlin_python.driver.protocol.AbstractBaseProtocol protocol:
davebshow's avatar
davebshow committed
29
        Protocol implementation
davebshow's avatar
davebshow committed
30
31
32
33
34
    :param asyncio.BaseEventLoop loop:
    :param str username: Username for database auth
    :param str password: Password for database auth
    :param int max_inflight: Maximum number of unprocessed requests at any
        one time on the connection
davebshow's avatar
davebshow committed
35
    :param float response_timeout: (optional) `None` by default
davebshow's avatar
davebshow committed
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
    """
    def __init__(self, url, transport, protocol, loop, username, password,
                 max_inflight, response_timeout, message_serializer, provider):
        self._url = url
        self._transport = transport
        self._protocol = protocol
        self._loop = loop
        self._response_timeout = response_timeout
        self._username = username
        self._password = password
        self._closed = False
        self._result_sets = {}
        self._receive_task = self._loop.create_task(self._receive())
        self._semaphore = asyncio.Semaphore(value=max_inflight,
                                            loop=self._loop)
        if isinstance(message_serializer, type):
            message_serializer = message_serializer()
        self._message_serializer = message_serializer
        self._provider = provider

    @classmethod
    async def open(cls, url, loop, *,
                   protocol=None,
                   transport_factory=None,
                   ssl_context=None,
                   username='',
                   password='',
                   max_inflight=64,
                   response_timeout=None,
                   message_serializer=serializer.GraphSONMessageSerializer,
                   provider=provider.TinkerGraph):
        """
        **coroutine** Open a connection to the Gremlin Server.

        :param str url: url for host Gremlin Server
        :param asyncio.BaseEventLoop loop:
72
        :param gremlin_python.driver.protocol.AbstractBaseProtocol protocol:
davebshow's avatar
davebshow committed
73
74
            Protocol implementation
        :param func transport_factory: Factory function for transports
davebshow's avatar
davebshow committed
75
76
77
78
79
80
81
        :param ssl.SSLContext ssl_context:
        :param str username: Username for database auth
        :param str password: Password for database auth

        :param int max_inflight: Maximum number of unprocessed requests at any
            one time on the connection
        :param float response_timeout: (optional) `None` by default
davebshow's avatar
davebshow committed
82
83
        :param message_serializer: Message serializer implementation
        :param provider: Graph provider object implementation
davebshow's avatar
davebshow committed
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103

        :returns: :py:class:`Connection<aiogremlin.connection.Connection>`
        """
        if not protocol:
            protocol = GremlinServerWSProtocol(message_serializer)
        if not transport_factory:
            transport_factory = lambda: AiohttpTransport(loop)
        transport = transport_factory()
        await transport.connect(url, ssl_context=ssl_context)
        return cls(url, transport, protocol, loop, username, password,
                   max_inflight, response_timeout, message_serializer,
                   provider)

    @property
    def message_serializer(self):
        return self._message_serializer

    @property
    def closed(self):
        """
davebshow's avatar
davebshow committed
104
        Read-only property. Check if connection has been closed.
davebshow's avatar
davebshow committed
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122

        :returns: `bool`
        """
        return self._closed or self._transport.closed

    @property
    def url(self):
        """
        Readonly property.

        :returns: str The url association with this connection.
        """
        return self._url

    async def write(self, message):
        """
        Submit a script and bindings to the Gremlin Server

123
        :param `RequestMessage<gremlin_python.driver.request.RequestMessage>` message:
davebshow's avatar
davebshow committed
124
125
126
127
128
129
130
131
132
        :returns: :py:class:`ResultSet<aiogremlin.driver.resultset.ResultSet>`
            object
        """
        await self._semaphore.acquire()
        request_id = str(uuid.uuid4())
        message = self._message_serializer.serialize_message(
            request_id, message)
        if self._transport.closed:
            await self._transport.connect(self.url)
133
134
135
        func = self._transport.write(message)
        if asyncio.iscoroutine(func):
            await func
davebshow's avatar
davebshow committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
        result_set = resultset.ResultSet(request_id, self._response_timeout,
                                   self._loop)
        self._result_sets[request_id] = result_set
        self._loop.create_task(
            self._terminate_response(result_set, request_id))
        return result_set

    submit = write

    async def close(self):
        """**coroutine** Close underlying connection and mark as closed."""
        self._receive_task.cancel()
        await self._transport.close()
        self._closed = True

    async def _terminate_response(self, resp, request_id):
        await resp.done.wait()
        del self._result_sets[request_id]
        self._semaphore.release()

    async def _receive(self):
        while True:
            data = await self._transport.read()
            await self._protocol.data_received(data, self._result_sets)

    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc, tb):
        await self.close()
davebshow's avatar
davebshow committed
166
        self._transport = None