|
| 1 | +# Copyright (c) "Neo4j" |
| 2 | +# Neo4j Sweden AB [http://neo4j.com] |
| 3 | +# |
| 4 | +# This file is part of Neo4j. |
| 5 | +# |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +# you may not use this file except in compliance with the License. |
| 8 | +# You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, software |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +# See the License for the specific language governing permissions and |
| 16 | +# limitations under the License. |
| 17 | + |
| 18 | + |
| 19 | +from .addressing import Address |
| 20 | +from .api import READ_ACCESS |
| 21 | +from .conf import ( |
| 22 | + Config, |
| 23 | + PoolConfig, |
| 24 | + SessionConfig, |
| 25 | + WorkspaceConfig, |
| 26 | +) |
| 27 | +from .meta import experimental |
| 28 | +from .work.simple import Session |
| 29 | + |
| 30 | + |
| 31 | +class Direct: |
| 32 | + |
| 33 | + default_host = "localhost" |
| 34 | + default_port = 7687 |
| 35 | + |
| 36 | + default_target = ":" |
| 37 | + |
| 38 | + def __init__(self, address): |
| 39 | + self._address = address |
| 40 | + |
| 41 | + @property |
| 42 | + def address(self): |
| 43 | + return self._address |
| 44 | + |
| 45 | + @classmethod |
| 46 | + def parse_target(cls, target): |
| 47 | + """ Parse a target string to produce an address. |
| 48 | + """ |
| 49 | + if not target: |
| 50 | + target = cls.default_target |
| 51 | + address = Address.parse(target, default_host=cls.default_host, |
| 52 | + default_port=cls.default_port) |
| 53 | + return address |
| 54 | + |
| 55 | + |
| 56 | +class Routing: |
| 57 | + |
| 58 | + default_host = "localhost" |
| 59 | + default_port = 7687 |
| 60 | + |
| 61 | + default_targets = ": :17601 :17687" |
| 62 | + |
| 63 | + def __init__(self, initial_addresses): |
| 64 | + self._initial_addresses = initial_addresses |
| 65 | + |
| 66 | + @property |
| 67 | + def initial_addresses(self): |
| 68 | + return self._initial_addresses |
| 69 | + |
| 70 | + @classmethod |
| 71 | + def parse_targets(cls, *targets): |
| 72 | + """ Parse a sequence of target strings to produce an address |
| 73 | + list. |
| 74 | + """ |
| 75 | + targets = " ".join(targets) |
| 76 | + if not targets: |
| 77 | + targets = cls.default_targets |
| 78 | + addresses = Address.parse_list(targets, default_host=cls.default_host, default_port=cls.default_port) |
| 79 | + return addresses |
| 80 | + |
| 81 | + |
| 82 | +class Driver: |
| 83 | + """ Base class for all types of :class:`neo4j.Driver`, instances of which are |
| 84 | + used as the primary access point to Neo4j. |
| 85 | + """ |
| 86 | + |
| 87 | + #: Connection pool |
| 88 | + _pool = None |
| 89 | + |
| 90 | + def __init__(self, pool): |
| 91 | + assert pool is not None |
| 92 | + self._pool = pool |
| 93 | + |
| 94 | + def __del__(self): |
| 95 | + self.close() |
| 96 | + |
| 97 | + def __enter__(self): |
| 98 | + return self |
| 99 | + |
| 100 | + def __exit__(self, exc_type, exc_value, traceback): |
| 101 | + self.close() |
| 102 | + |
| 103 | + @property |
| 104 | + def encrypted(self): |
| 105 | + return bool(self._pool.pool_config.encrypted) |
| 106 | + |
| 107 | + def session(self, **config): |
| 108 | + """Create a session, see :ref:`session-construction-ref` |
| 109 | +
|
| 110 | + :param config: session configuration key-word arguments, see :ref:`session-configuration-ref` for available key-word arguments. |
| 111 | +
|
| 112 | + :returns: new :class:`neo4j.Session` object |
| 113 | + """ |
| 114 | + raise NotImplementedError |
| 115 | + |
| 116 | + @experimental("The pipeline API is experimental and may be removed or changed in a future release") |
| 117 | + def pipeline(self, **config): |
| 118 | + """ Create a pipeline. |
| 119 | + """ |
| 120 | + raise NotImplementedError |
| 121 | + |
| 122 | + def close(self): |
| 123 | + """ Shut down, closing any open connections in the pool. |
| 124 | + """ |
| 125 | + self._pool.close() |
| 126 | + |
| 127 | + @experimental("The configuration may change in the future.") |
| 128 | + def verify_connectivity(self, **config): |
| 129 | + """ This verifies if the driver can connect to a remote server or a cluster |
| 130 | + by establishing a network connection with the remote and possibly exchanging |
| 131 | + a few data before closing the connection. It throws exception if fails to connect. |
| 132 | +
|
| 133 | + Use the exception to further understand the cause of the connectivity problem. |
| 134 | +
|
| 135 | + Note: Even if this method throws an exception, the driver still need to be closed via close() to free up all resources. |
| 136 | + """ |
| 137 | + raise NotImplementedError |
| 138 | + |
| 139 | + @experimental("Feature support query, based on Bolt Protocol Version and Neo4j Server Version will change in the future.") |
| 140 | + def supports_multi_db(self): |
| 141 | + """ Check if the server or cluster supports multi-databases. |
| 142 | +
|
| 143 | + :return: Returns true if the server or cluster the driver connects to supports multi-databases, otherwise false. |
| 144 | + :rtype: bool |
| 145 | + """ |
| 146 | + with self.session() as session: |
| 147 | + session._connect(READ_ACCESS) |
| 148 | + return session._connection.supports_multiple_databases |
| 149 | + |
| 150 | + |
| 151 | +class BoltDriver(Direct, Driver): |
| 152 | + """ A :class:`.BoltDriver` is created from a ``bolt`` URI and addresses |
| 153 | + a single database machine. This may be a standalone server or could be a |
| 154 | + specific member of a cluster. |
| 155 | +
|
| 156 | + Connections established by a :class:`.BoltDriver` are always made to the |
| 157 | + exact host and port detailed in the URI. |
| 158 | + """ |
| 159 | + |
| 160 | + @classmethod |
| 161 | + def open(cls, target, *, auth=None, **config): |
| 162 | + """ |
| 163 | + :param target: |
| 164 | + :param auth: |
| 165 | + :param config: The values that can be specified are found in :class: `neo4j.PoolConfig` and :class: `neo4j.WorkspaceConfig` |
| 166 | +
|
| 167 | + :return: |
| 168 | + :rtype: :class: `neo4j.BoltDriver` |
| 169 | + """ |
| 170 | + from neo4j.io import BoltPool |
| 171 | + address = cls.parse_target(target) |
| 172 | + pool_config, default_workspace_config = Config.consume_chain(config, PoolConfig, WorkspaceConfig) |
| 173 | + pool = BoltPool.open(address, auth=auth, pool_config=pool_config, workspace_config=default_workspace_config) |
| 174 | + return cls(pool, default_workspace_config) |
| 175 | + |
| 176 | + def __init__(self, pool, default_workspace_config): |
| 177 | + Direct.__init__(self, pool.address) |
| 178 | + Driver.__init__(self, pool) |
| 179 | + self._default_workspace_config = default_workspace_config |
| 180 | + |
| 181 | + def session(self, **config): |
| 182 | + """ |
| 183 | + :param config: The values that can be specified are found in :class: `neo4j.SessionConfig` |
| 184 | +
|
| 185 | + :return: |
| 186 | + :rtype: :class: `neo4j.Session` |
| 187 | + """ |
| 188 | + from neo4j.work.simple import Session |
| 189 | + session_config = SessionConfig(self._default_workspace_config, config) |
| 190 | + SessionConfig.consume(config) # Consume the config |
| 191 | + return Session(self._pool, session_config) |
| 192 | + |
| 193 | + def pipeline(self, **config): |
| 194 | + from neo4j.work.pipelining import ( |
| 195 | + Pipeline, |
| 196 | + PipelineConfig, |
| 197 | + ) |
| 198 | + pipeline_config = PipelineConfig(self._default_workspace_config, config) |
| 199 | + PipelineConfig.consume(config) # Consume the config |
| 200 | + return Pipeline(self._pool, pipeline_config) |
| 201 | + |
| 202 | + @experimental("The configuration may change in the future.") |
| 203 | + def verify_connectivity(self, **config): |
| 204 | + server_agent = None |
| 205 | + config["fetch_size"] = -1 |
| 206 | + with self.session(**config) as session: |
| 207 | + result = session.run("RETURN 1 AS x") |
| 208 | + value = result.single().value() |
| 209 | + summary = result.consume() |
| 210 | + server_agent = summary.server.agent |
| 211 | + return server_agent |
| 212 | + |
| 213 | + |
| 214 | +class Neo4jDriver(Routing, Driver): |
| 215 | + """ A :class:`.Neo4jDriver` is created from a ``neo4j`` URI. The |
| 216 | + routing behaviour works in tandem with Neo4j's `Causal Clustering |
| 217 | + <https://neo4j.com/docs/operations-manual/current/clustering/>`_ |
| 218 | + feature by directing read and write behaviour to appropriate |
| 219 | + cluster members. |
| 220 | + """ |
| 221 | + |
| 222 | + @classmethod |
| 223 | + def open(cls, *targets, auth=None, routing_context=None, **config): |
| 224 | + from neo4j.io import Neo4jPool |
| 225 | + addresses = cls.parse_targets(*targets) |
| 226 | + pool_config, default_workspace_config = Config.consume_chain(config, PoolConfig, WorkspaceConfig) |
| 227 | + pool = Neo4jPool.open(*addresses, auth=auth, routing_context=routing_context, pool_config=pool_config, workspace_config=default_workspace_config) |
| 228 | + return cls(pool, default_workspace_config) |
| 229 | + |
| 230 | + def __init__(self, pool, default_workspace_config): |
| 231 | + Routing.__init__(self, pool.get_default_database_initial_router_addresses()) |
| 232 | + Driver.__init__(self, pool) |
| 233 | + self._default_workspace_config = default_workspace_config |
| 234 | + |
| 235 | + def session(self, **config): |
| 236 | + session_config = SessionConfig(self._default_workspace_config, config) |
| 237 | + SessionConfig.consume(config) # Consume the config |
| 238 | + return Session(self._pool, session_config) |
| 239 | + |
| 240 | + def pipeline(self, **config): |
| 241 | + from neo4j.work.pipelining import ( |
| 242 | + Pipeline, |
| 243 | + PipelineConfig, |
| 244 | + ) |
| 245 | + pipeline_config = PipelineConfig(self._default_workspace_config, config) |
| 246 | + PipelineConfig.consume(config) # Consume the config |
| 247 | + return Pipeline(self._pool, pipeline_config) |
| 248 | + |
| 249 | + @experimental("The configuration may change in the future.") |
| 250 | + def verify_connectivity(self, **config): |
| 251 | + """ |
| 252 | + :raise ServiceUnavailable: raised if the server does not support routing or if routing support is broken. |
| 253 | + """ |
| 254 | + # TODO: Improve and update Stub Test Server to be able to test. |
| 255 | + return self._verify_routing_connectivity() |
| 256 | + |
| 257 | + def _verify_routing_connectivity(self): |
| 258 | + from neo4j.exceptions import ( |
| 259 | + Neo4jError, |
| 260 | + ServiceUnavailable, |
| 261 | + SessionExpired, |
| 262 | + ) |
| 263 | + |
| 264 | + table = self._pool.get_routing_table_for_default_database() |
| 265 | + routing_info = {} |
| 266 | + for ix in list(table.routers): |
| 267 | + try: |
| 268 | + routing_info[ix] = self._pool.fetch_routing_info( |
| 269 | + address=table.routers[0], |
| 270 | + database=self._default_workspace_config.database, |
| 271 | + imp_user=self._default_workspace_config.impersonated_user, |
| 272 | + bookmarks=None, |
| 273 | + timeout=self._default_workspace_config |
| 274 | + .connection_acquisition_timeout |
| 275 | + ) |
| 276 | + except (ServiceUnavailable, SessionExpired, Neo4jError): |
| 277 | + routing_info[ix] = None |
| 278 | + for key, val in routing_info.items(): |
| 279 | + if val is not None: |
| 280 | + return routing_info |
| 281 | + raise ServiceUnavailable("Could not connect to any routing servers.") |
0 commit comments