pub struct Client<S: AsyncRead + AsyncWrite + Unpin> { /* private fields */ }Expand description
An asynchronous client for Bolt servers.
Implementations§
Source§impl<S: AsyncRead + AsyncWrite + Unpin> Client<S>
impl<S: AsyncRead + AsyncWrite + Unpin> Client<S>
Sourcepub async fn new(
stream: S,
version_specifiers: &[u32; 4],
) -> ConnectionResult<Self>
pub async fn new( stream: S, version_specifiers: &[u32; 4], ) -> ConnectionResult<Self>
Attempt to create a new client from an asynchronous stream. A handshake will be performed with the provided protocol version specifiers, and, if this succeeds, a Client will be returned.
Sourcepub fn server_state(&self) -> ServerState
pub fn server_state(&self) -> ServerState
Get the current server state for this client.
Sourcepub async fn hello(
&mut self,
metadata: Metadata,
) -> CommunicationResult<Message>
pub async fn hello( &mut self, metadata: Metadata, ) -> CommunicationResult<Message>
Send a HELLO (or INIT) message to the server.
(Sends INIT for Bolt v1 - v2, and HELLO for Bolt v3+.)
§Description
The HELLO message requests the connection to be authorized for use with the remote
database. Clients should send a HELLO message to the server immediately after connection
and process the response before using that connection in any other way.
The server must be in the Connected state to be able to process
a HELLO message. For any other states, receipt of a HELLO message is considered a
protocol violation and leads to connection closure.
If authentication fails, the server will respond with a FAILURE
message and immediately close the connection. Clients wishing to retry initialization
should establish a new connection.
§Fields
metadata should contain at least two entries:
user_agent, which should conform to the format"Name/Version", for example"Example/1.0.0"(see here).schemeis the authentication scheme. Predefined schemes are"none","basic", or"kerberos".
If using Bolt v4.1 or later, the following additional metadata entries can be specified:
routing, a map which should contain routing context information as well as anaddressfield indicating to which address the client should initially connect. Leaving this unspecified indicates that the server should not carry out any routing. (Bolt v4.1+ only.)
Further entries in metadata are passed to the implementation of the chosen authentication
scheme. Their names, types, and defaults depend on that choice. For example, the scheme
"basic" requires metadata to contain the username and password in the form
{"principal": "<username>", "credentials": "<password>"}.
§Response
Message::Success- initialization has completed successfully and the server has entered theReadystate. The server may include metadata that describes details of the server environment and/or the connection. The following fields are defined for inclusion in theSUCCESSmetadata:server, the server agent string (e.g."Neo4j/4.3.0")connection_id, a unique identifier for the connection (e.g."bolt-61") (Bolt v3+ only.)hints, a map of configuration hints (e.g.{"connection.recv_timeout_seconds": 120}) These hints may be interpreted or ignored by drivers at their own discretion in order to augment operations where applicable. Hints remain valid throughout the lifetime of a given connection and cannot be changed. As such, newly established connections may observe different hints as the server configuration is adjusted. (Bolt v4.3+ only.)
Message::Failure- initialization has failed and the server has entered theDefunctstate. The server may choose to include metadata describing the nature of the failure but will immediately close the connection after the failure has been sent.
Sourcepub async fn route(
&mut self,
context: RoutingContext,
bookmarks: impl Into<Vec<String>>,
metadata: Option<Metadata>,
) -> CommunicationResult<Message>
pub async fn route( &mut self, context: RoutingContext, bookmarks: impl Into<Vec<String>>, metadata: Option<Metadata>, ) -> CommunicationResult<Message>
Send a ROUTE message to the server.
(Bolt v4.3+ only. For Bolt v4.3, an alternate version of the message is
sent.)
§Description
The ROUTE message instructs the server to return the current routing table.
The server must be in the Ready state to be able to successfully
process a ROUTE request. If the server is in the Failed or
Interrupted state, the response will be
IGNORED. For any other states, receipt of a ROUTE request will be
considered a protocol violation and will lead to connection closure.
§Fields
context, which should contain routing context information as well as anaddressfield indicating to which address the client should initially connect.bookmarks, a list of strings containing some kind of bookmark identification, e.g["bkmk-transaction:1", "bkmk-transaction:2"]. Default is[].metadata, a map which can contain the following optional entries:db, a string containing the name of the database for which this command should be run.nulldenotes the server-side configured default database.imp_user, a string specifying the impersonated user for the purposes of resolving their home database.nulldenotes no impersonation (i.e., execution takes place as the current user). (Bolt v4.4+ only.)
§Response
Message::Success- the routing table has been successfully retrieved and the server has entered theReadystate. The server sends the following metadata fields in the response:rt, a map with the following fields:ttl, an integer denoting the number of seconds this routing table should be considered validservers, a list of maps representing roles for one or more addresses. Each element will have the following fields:role, a server role. Possible values are"READ","WRITE", and"ROUTE".addresses, a list of strings representing the servers with the specified role
Message::Ignored- the server is in theFailedorInterruptedstate, and the request was discarded without being processed. No server state change has occurred.Message::Failure- the request could not be processed successfully and the server has entered theFailedstate. The server may attach metadata to the message to provide more detail on the nature of the failure.
Sourcepub async fn run(
&mut self,
query: impl Into<String>,
parameters: Option<Params>,
metadata: Option<Metadata>,
) -> CommunicationResult<Message>
pub async fn run( &mut self, query: impl Into<String>, parameters: Option<Params>, metadata: Option<Metadata>, ) -> CommunicationResult<Message>
Send a RUN message to the server.
(Bolt v1+. For Bolt v1 - v2, the metadata parameter is ignored.)
§Description
A RUN message submits a new query for execution, the result of which will be consumed by
a subsequent message, such as PULL.
The server must be in either the Ready state, the
TxReady state (Bolt v3+), or the
TxStreaming state (Bolt v4+) to be able to successfully
process a RUN request. If the server is in the Failed or
Interrupted state, the response will be
IGNORED. For any other states, receipt of a RUN request will be
considered a protocol violation and will lead to connection closure.
§Fields
querycontains a database query or remote procedure call.parameterscontains variable fields forquery.
If using Bolt v3 or later, the following metadata entries can be specified:
bookmarks, a list of strings containing some kind of bookmark identification, e.g["bkmk-transaction:1", "bkmk-transaction:2"]. Default is[].tx_timeout, an integer specifying a transaction timeout in milliseconds. Default is the server-side configured timeout.tx_metadata, a map containing some metadata information, mainly used for logging.mode, a string which specifies what kind of server should be used for this transaction. For write access, use"w"and for read access use"r". Default is"w".db, a string containing the name of the database where the transaction should take place.nulland""denote the server-side configured default database. (Bolt v4+ only.)imp_user, a string specifying the impersonated user which executes this transaction.nulldenotes no impersonation (i.e., execution takes place as the current user). (Bolt v4.4+ only.)
§Response
Message::Success- the request has been successfully received and the server has entered theStreamingstate. Clients should not consider aSUCCESSresponse to indicate completion of the execution of the query, merely acceptance of it. The server may attach metadata to the message to provide header detail for the results that follow. The following fields are defined for inclusion in the metadata:fields, the fields included in the result (e.g.["name", "age"])result_available_after, the time in milliseconds after which the first record in the result stream is available. (Bolt v1 - v2 only.)t_first, supercedesresult_available_after. (Bolt v3+ only.)qid, an integer that specifies the server-assigned query ID. This is sent for queries submitted within an explicit transaction. (Bolt v4+ only.)
Message::Ignored- the server is in theFailedorInterruptedstate, and the request was discarded without being processed. No server state change has occurred.Message::Failure- the request could not be processed successfully or is invalid, and the server has entered theFailedstate. The server may attach metadata to the message to provide more detail on the nature of the failure.
Sourcepub async fn pull(
&mut self,
metadata: Option<Metadata>,
) -> CommunicationResult<(Vec<Record>, Message)>
pub async fn pull( &mut self, metadata: Option<Metadata>, ) -> CommunicationResult<(Vec<Record>, Message)>
Send a PULL (or PULL_ALL) message to the server.
(Sends PULL_ALL for Bolt v1 - v3, and PULL for Bolt v4+. For Bolt v1 - v3, the
metadata parameter is ignored.)
§Description
The PULL message issues a request to stream outstanding results back to the client,
before returning to the Ready state.
Result details consist of zero or more RECORD messages and a summary
message. Each record carries with it a list of values which form the data content of the
record. The order of the values within that list should be meaningful to the client,
perhaps based on a requested ordering for that result, but no guarantees are made around
the order of records within the result. A record should only be considered valid if
accompanied by a SUCCESS summary message.
The server must be in the Streaming or
TxStreaming state to be able to successfully process a PULL
request. If the server is in the Failed state or
Interrupted state, the response will be
IGNORED. For any other states, receipt of a PULL request will be
considered a protocol violation and will lead to connection closure.
§Fields
For Bolt v4+, additional metadata is passed along with this message:
nis an integer specifying how many records to fetch.-1will fetch all records.nhas no default and must be present.qidis an integer that specifies for which statement thePULLoperation should be carried out within an explicit transaction.-1is the default, which denotes the last executed statement.
§Response
(_,Message::Success)- results have been successfully pulled and the server has entered theReadystate. The server may attach metadata to theSUCCESSmessage to provide footer detail for the results. The following fields are defined for inclusion in the metadata:type, the type of query: read-only ("r"), write-only ("w"), read-write ("rw"), or schema ("s")result_consumed_after, the time in milliseconds after which the last record in the result stream is consumed. (Bolt v1 - v2 only.)t_last, supercedesresult_consumed_after. (Bolt v3+ only.)bookmark(e.g."bookmark:1234"). (Bolt v3+ only.)stats, a map containing counter information, such as DB hits, etc. (Bolt v3+ only.)plan, a map containing the query plan result. (Bolt v3+ only.)profile, a map containing the query profile result. (Bolt v3+ only.)notifications, a map containing any notifications generated during execution of the query. (Bolt v3+ only.)db, a string containing the name of the database where the query was executed. (Bolt v4+ only.)has_more, a boolean indicating whether there are still records left in the result stream. Default isfalse. (Bolt v4+ only.)
(_,Message::Ignored)- the server is in theFailedorInterruptedstate, and the request was discarded without being processed. No server state change has occurred.(_,Message::Failure)- the request could not be processed successfully and the server has entered theFailedstate. The server may attach metadata to the message to provide more detail on the nature of the failure. Failure may occur at any time during result streaming, so any records returned in the response should be considered invalid.
Sourcepub async fn discard(
&mut self,
metadata: Option<Metadata>,
) -> CommunicationResult<Message>
pub async fn discard( &mut self, metadata: Option<Metadata>, ) -> CommunicationResult<Message>
Send a DISCARD (or DISCARD_ALL) message to
the server.
(Sends a DISCARD_ALL for Bolt v1 - v3, and DISCARD for Bold v4+. For Bolt v1 - v3, the
metadata parameter is ignored.)
§Description
The DISCARD message issues a request to discard the outstanding result and return to the
Ready state. A receiving server will not abort the request but
continue to process it without streaming any detail messages to the client.
The server must be in the Streaming or
TxStreaming state to be able to successfully process a
DISCARD request. If the server is in the Failed state or
Interrupted state, the response will be
IGNORED. For any other states, receipt of a DISCARD request will be
considered a protocol violation and will lead to connection closure.
§Fields
For Bolt v4+, additional metadata is passed along with this message:
nis an integer specifying how many records to discard.-1will discard all records.nhas no default and must be present.qidis an integer that specifies for which statement theDISCARDoperation should be carried out within an explicit transaction.-1is the default, which denotes the last executed statement.
§Response
Message::Success- results have been successfully discarded and the server has entered theReadystate. The server may attach metadata to the message to provide footer detail for the discarded results. The following fields are defined for inclusion in the metadata:type, the type of query: read-only ("r"), write-only ("w"), read-write ("rw"), or schema ("s")result_consumed_after, the time in milliseconds after which the last record in the result stream is consumed. (Bolt v1 - v2 only.)t_last, supercedesresult_consumed_after. (Bolt v3+ only.)bookmark(e.g."bookmark:1234"). (Bolt v3+ only.)db, a string containing the name of the database where the query was executed. (Bolt v4+ only.)has_more, a boolean indicating whether there are still records left in the result stream. Default isfalse. (Bolt v4+ only.)
Message::Ignored- the server is in theFailedorInterruptedstate, and the request was discarded without being processed. No server state change has occurred.Message::Failure- the request could not be processed successfully and the server has entered theFailedstate. The server may attach metadata to the message to provide more detail on the nature of the failure.
Sourcepub async fn begin(
&mut self,
metadata: Option<Metadata>,
) -> CommunicationResult<Message>
pub async fn begin( &mut self, metadata: Option<Metadata>, ) -> CommunicationResult<Message>
Send a BEGIN message to the server.
(Bolt v3+ only.)
§Description
The BEGIN message starts a new explicit transaction and transitions the server to the
TxReady state. The explicit transaction is closed with either the
COMMIT message or ROLLBACK message.
The server must be in the Ready state to be able to successfully
process a BEGIN request. If the server is in the Failed or
Interrupted state, the response will be
IGNORED. For any other states, receipt of a BEGIN request will be
considered a protocol violation and will lead to connection closure.
§Fields
metadata may contain the following optional fields:
bookmarks, a list of strings containing some kind of bookmark identification, e.g["bkmk-transaction:1", "bkmk-transaction:2"]. Default is[].tx_timeout, an integer specifying a transaction timeout in milliseconds. Default is the server-side configured timeout.tx_metadata, a map containing some metadata information, mainly used for logging.mode, a string which specifies what kind of server should be used for this transaction. For write access, use"w"and for read access use"r". Default is"w".db, a string containing the name of the database where the transaction should take place.nulland""denote the server-side configured default database. (Bolt v4+ only.)imp_user, a string specifying the impersonated user which executes this transaction.nulldenotes no impersonation (i.e., execution takes place as the current user). (Bolt v4.4+ only.)
§Response
Message::Success- the transaction has been successfully started and the server has entered theTxReadystate.Message::Ignored- the server is in theFailedorInterruptedstate, and the request was discarded without being processed. No server state change has occurred.Message::Failure- the request could not be processed successfully and the server has entered theFailedstate. The server may attach metadata to the message to provide more detail on the nature of the failure.
Sourcepub async fn commit(&mut self) -> CommunicationResult<Message>
pub async fn commit(&mut self) -> CommunicationResult<Message>
Send a COMMIT message to the server.
(Bolt v3+ only.)
§Description
The COMMIT message requests to commit the results of an explicit transaction and
transition the server back to the Ready state.
The server must be in the TxReady state to be able to
successfully process a COMMIT request, which means that any outstanding results in the
result stream must be consumed via Client::pull. If the server is in the
Failed or Interrupted state, the
response will be IGNORED. For any other states, receipt of a COMMIT
request will be considered a protocol violation and will lead to connection closure.
To instead cancel pending changes, send a ROLLBACK message.
§Response
Message::Success- the transaction has been successfully committed and the server has entered theReadystate. The server sends the following metadata fields in the response:bookmark(e.g."bookmark:1234")
Message::Ignored- the server is in theFailedorInterruptedstate, and the request was discarded without being processed. No server state change has occurred.Message::Failure- the request could not be processed successfully and the server has entered theFailedstate. The server may attach metadata to the message to provide more detail on the nature of the failure.
Sourcepub async fn rollback(&mut self) -> CommunicationResult<Message>
pub async fn rollback(&mut self) -> CommunicationResult<Message>
Send a ROLLBACK message to the server.
(Bolt v3+ only.)
§Description
The ROLLBACK message requests to cancel a transaction and transition the server back to
the Ready state. Any changes made since the transaction was started
will be undone.
The server must be in the TxReady state to be able to
successfully process a ROLLBACK request, which means that any outstanding results in the
result stream must be consumed via Client::pull. If the server is in the
Failed or Interrupted state, the
response will be IGNORED. For any other states, receipt of a
ROLLBACK request will be considered a protocol violation and will lead to connection
closure.
To instead persist pending changes, send a COMMIT message.
§Response
Message::Success- the transaction has been successfully reverted and the server has entered theReadystate.Message::Ignored- the server is in theFailedorInterruptedstate, and the request was discarded without being processed. No server state change has occurred.Message::Failure- the request could not be processed successfully and the server has entered theFailedstate. The server may attach metadata to the message to provide more detail on the nature of the failure.
Sourcepub async fn ack_failure(&mut self) -> CommunicationResult<Message>
pub async fn ack_failure(&mut self) -> CommunicationResult<Message>
Send an ACK_FAILURE message to the server.
(Bolt v1 - v2 only. For Bolt v3+, see Client::reset.)
§Description
ACK_FAILURE signals to the server that the client has acknowledged a previous failure and
should return to the Ready state.
The server must be in the Failed state to be able to successfully
process an ACK_FAILURE request. For any other states, receipt of an ACK_FAILURE request
will be considered a protocol violation and will lead to connection closure.
§Response
Message::Success- failure has been successfully acknowledged and the server has entered theReadystate. The server may attach metadata to theSUCCESSmessage.Message::Failure- the request could not be processed successfully and the server has entered theDefunctstate. The server may choose to include metadata describing the nature of the failure but will immediately close the connection after the failure has been sent.
Sourcepub async fn reset(&mut self) -> CommunicationResult<Message>
pub async fn reset(&mut self) -> CommunicationResult<Message>
Send a RESET message to the server.
(Bolt v1+. For Bolt v1 - v2, see Client::ack_failure for just clearing the
Failed state.)
§Description
The RESET message requests that the connection be set back to its initial state, as if
initialization had just been successfully completed. The RESET message is unique in that
it on arrival at the server, it jumps ahead in the message queue, stopping any unit of work
that happens to be executing. All the queued messages originally in front of the RESET
message will then be IGNORED until the RESET position is reached,
at which point the server will be ready for a new session.
Specifically, RESET will:
- force any currently processing message to abort with
IGNORED - force any pending messages that have not yet started processing to be
IGNORED - clear any outstanding
Failedstate - dispose of any outstanding result records
- cancel the current transaction, if any
§Response
Message::Success- the session has been successfully reset and the server has entered theReadystate.Message::Failure- the request could not be processed successfully and the server has entered theDefunctstate. The server may choose to include metadata describing the nature of the failure but will immediately close the connection after the failure has been sent.
Sourcepub async fn goodbye(&mut self) -> CommunicationResult<()>
pub async fn goodbye(&mut self) -> CommunicationResult<()>
Send a GOODBYE message to the server.
(Bolt v3+ only.)
§Description
The GOODBYE message notifies the server that the connection is terminating gracefully. On
receipt of this message, the server will immediately shut down the socket on its side
without sending a response. A client may shut down the socket at any time after sending the
GOODBYE message. This message interrupts the server’s current work, if any.
Sourcepub async fn pipeline(
&mut self,
messages: Vec<Message>,
) -> CommunicationResult<Vec<Message>>
pub async fn pipeline( &mut self, messages: Vec<Message>, ) -> CommunicationResult<Vec<Message>>
Send multiple messages to the server without waiting for a response. Returns a Vec
containing the server’s response messages for each of the sent messages, in the order they
were provided.
§Description
The client is not required to wait for a response before sending more messages. Sending multiple messages together like this is called pipelining. For performance reasons, it is recommended that clients use pipelining wherever possible. Using pipelining, multiple messages can be transmitted together in the same network package, significantly reducing latency and increasing throughput.
A common technique is to buffer outgoing messages on the client until the last possible moment, such as when a commit is issued or a result is read by the application, and then sending all messages in the buffer together.
§Failure Handling
Because the protocol leverages pipelining, the client and the server need to agree on what happens when a failure occurs, otherwise messages that were sent assuming no failure would occur might have unintended effects.
When requests fail on the server, the server will send the client a
FAILURE message. The client must clear the failure state by sending a
RESET (Bolt v3+) or ACK_FAILURE (Bolt v1 - v2)
message to the server. Until the server receives the RESET/ACK_FAILURE message, it will
send an IGNORED message in response to any other message from the
client, including messages that were sent in a pipeline.