-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathclient.py
More file actions
302 lines (271 loc) · 11.1 KB
/
client.py
File metadata and controls
302 lines (271 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# Copyright 2025 vesoft-inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from collections.abc import AsyncGenerator, Generator
from contextlib import asynccontextmanager, contextmanager
from typing import Any, Dict, List, Literal, Optional, Union
from nebulagraph_python.client._connection import (
AsyncConnection,
Connection,
ConnectionConfig,
)
from nebulagraph_python.client._connection_pool import (
AsyncConnectionPool,
ConnectionPool,
)
from nebulagraph_python.client._session import (
AsyncSession,
Session,
SessionConfig,
)
from nebulagraph_python.client._session_pool import (
AsyncSessionPool,
SessionPool,
SessionPoolConfig,
)
from nebulagraph_python.client.base_executor import (
NebulaBaseAsyncExecutor,
NebulaBaseExecutor,
)
from nebulagraph_python.data import HostAddress, SSLParam
from nebulagraph_python.error import PoolError
from nebulagraph_python.result_set import ResultSet
logger = logging.getLogger(__name__)
class NebulaAsyncClient(NebulaBaseAsyncExecutor):
"""The async client for connecting to NebulaGraph. It is async/coroutine-level safe but not thread-safe,
which means you can not share the client instance across threads,
but you can call `await client.execute()` concurrently in async coroutines.
Required to explicitly call `close()` to release all resources.
"""
# Owned Resources
_conn: AsyncConnection | AsyncConnectionPool
_sessions: dict[HostAddress, AsyncSession | AsyncSessionPool]
def __init__(*args, **kwargs):
raise RuntimeError(
"Using `await NebulaAsyncClient.connect()` to create a client instance."
)
@classmethod
async def connect(
cls,
hosts: Union[str, List[str], List[HostAddress]],
username: str,
password: Optional[str] = None,
*,
ssl_param: Union[SSLParam, Literal[True], None] = None,
auth_options: Optional[Dict[str, Any]] = None,
conn_config: Optional[ConnectionConfig] = None,
session_config: Optional[SessionConfig] = None,
session_pool_config: Optional[SessionPoolConfig] = None,
):
"""Connect to NebulaGraph and initialize the client
Args:
----
hosts: Single host string ("hostname:port"), list of host strings,
or list of HostAddress objects
username: Username for authentication
password: Password for authentication
ssl_param: SSL configuration
auth_options: dict of authentication options
conn_config: Connection configuration. If provided, it overrides hosts and ssl_param.
session_config: Session configuration.
"""
self = super().__new__(cls)
conn_conf = conn_config or ConnectionConfig.from_defults(hosts, ssl_param)
hosts = conn_conf.hosts
self._sessions = {}
if len(hosts) == 1:
self._conn = AsyncConnection(conn_conf)
await self._conn.connect()
else:
self._conn = AsyncConnectionPool(conn_conf)
await self._conn.connect()
try:
for host_addr in hosts:
conn = (
await self._conn.get_connection(host_addr)
if isinstance(self._conn, AsyncConnectionPool)
else self._conn
)
if conn is None:
raise PoolError(
f"Failed to get connection to {host_addr} when initializing NebulaAsyncClient"
)
if session_pool_config:
self._sessions[host_addr] = await AsyncSessionPool.connect(
conn=conn,
username=username,
password=password,
auth_options=auth_options or {},
session_config=session_config or SessionConfig(),
pool_config=session_pool_config,
)
else:
self._sessions[host_addr] = AsyncSession(
_conn=conn,
username=username,
password=password,
session_config=session_config or SessionConfig(),
auth_options=auth_options or {},
)
except Exception as e:
await self._conn.close()
raise e
return self
async def execute(
self, statement: str, *, timeout: Optional[float] = None, do_ping: bool = False
) -> ResultSet:
async with self.borrow() as session:
return await session.execute(statement, timeout=timeout, do_ping=do_ping)
@asynccontextmanager
async def borrow(self) -> AsyncGenerator[AsyncSession, None]:
if isinstance(self._conn, AsyncConnectionPool):
addr, conn = await self._conn.next_connection()
else:
conn = self._conn
addr = conn.connected
if addr is None:
raise ValueError("Connection not connected")
_session = self._sessions[addr]
if isinstance(_session, AsyncSessionPool):
async with _session.borrow() as session:
yield session
else:
yield _session
async def close(self):
"""Close the client connection and session. No Exception will be raised but an error will be logged."""
for session in self._sessions.values():
await session._close()
await self._conn.close()
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_value, traceback):
await self.close()
class NebulaClient(NebulaBaseExecutor):
"""The client for connecting to NebulaGraph. It is thread-safe,
which means you can share a client instance across threads and call `execute` concurrently.
Required to explicitly call `close()` to release all resources.
"""
# Owned Resources
_conn: Connection | ConnectionPool
_sessions: dict[HostAddress, Session | SessionPool]
def __init__(
self,
hosts: Union[str, List[str], List[HostAddress]],
username: str,
password: Optional[str] = None,
*,
ssl_param: Union[SSLParam, Literal[True], None] = None,
auth_options: Optional[Dict[str, Any]] = None,
conn_config: Optional[ConnectionConfig] = None,
session_config: Optional[SessionConfig] = None,
session_pool_config: Optional[SessionPoolConfig] = None,
):
"""Initialize NebulaGraph client
Args:
----
hosts: Single host string ("hostname:port"), list of host strings,
or list of HostAddress objects
username: Username for authentication
password: Password for authentication
ssl_param: SSL configuration
auth_options: dict of authentication options
conn_config: Connection configuration. If provided, it overrides hosts and ssl_param.
session_config: Session configuration.
session_pool_config: Session pool configuration. If provided, a session pool will be created.
"""
conn_conf = conn_config or ConnectionConfig.from_defults(hosts, ssl_param)
hosts = conn_conf.hosts
self._sessions = {}
if len(hosts) == 1:
self._conn = Connection(conn_conf)
self._conn.connect()
else:
self._conn = ConnectionPool(conn_conf)
self._conn.connect()
try:
for host_addr in hosts:
conn = (
self._conn.get_connection(host_addr)
if isinstance(self._conn, ConnectionPool)
else self._conn
)
if conn is None:
raise PoolError(
f"Failed to get connection to {host_addr} when initializing NebulaClient"
)
if session_pool_config:
self._sessions[host_addr] = SessionPool.connect(
conn=conn,
username=username,
password=password,
auth_options=auth_options or {},
session_config=session_config or SessionConfig(),
pool_config=session_pool_config,
)
else:
self._sessions[host_addr] = Session(
_conn=conn,
username=username,
password=password,
session_config=session_config or SessionConfig(),
auth_options=auth_options or {},
)
except Exception as e:
self._conn.close()
raise e
def execute(
self, statement: str, *, timeout: Optional[float] = None, do_ping: bool = False
) -> ResultSet:
"""Execute a statement using a borrowed session, raising on errors."""
with self.borrow() as session:
return session.execute(statement, timeout=timeout, do_ping=do_ping)
@contextmanager
def borrow(self) -> Generator[Session, None, None]:
"""Yield a session bound to the selected connection."""
if isinstance(self._conn, ConnectionPool):
addr, conn = self._conn.next_connection()
else:
conn = self._conn
addr = conn.connected
if addr is None:
raise ValueError("Connection not connected")
# Route to the correct session (pool or single session)
_session = self._sessions[addr]
if isinstance(_session, SessionPool):
with _session.borrow() as session:
yield session
else:
yield _session
def ping(self, timeout: Optional[float] = None) -> bool:
try:
res = (
(self.execute(statement="RETURN 1", timeout=timeout))
.one()
.as_primitive()
)
if not res == {"1": 1}:
raise ValueError(f"Unexpected result from ping: {res}")
return True
except Exception:
logger.exception("Failed to ping NebulaGraph")
return False
def close(self):
"""Close the client connection and session. No Exception will be raised but an error will be logged."""
for session in self._sessions.values():
session._close()
self._conn.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()