tokio_postgres/
cancel_token.rs

1use crate::config::{SslMode, SslNegotiation};
2use crate::tls::TlsConnect;
3#[cfg(feature = "runtime")]
4use crate::{cancel_query, client::SocketConfig, tls::MakeTlsConnect, Socket};
5use crate::{cancel_query_raw, Error};
6use tokio::io::{AsyncRead, AsyncWrite};
7
8/// The capability to request cancellation of in-progress queries on a
9/// connection.
10#[derive(Clone)]
11pub struct CancelToken {
12    #[cfg(feature = "runtime")]
13    pub(crate) socket_config: Option<SocketConfig>,
14    pub(crate) ssl_mode: SslMode,
15    pub(crate) ssl_negotiation: SslNegotiation,
16    pub(crate) process_id: i32,
17    pub(crate) secret_key: i32,
18}
19
20impl CancelToken {
21    /// Attempts to cancel the in-progress query on the connection associated
22    /// with this `CancelToken`.
23    ///
24    /// The server provides no information about whether a cancellation attempt was successful or not. An error will
25    /// only be returned if the client was unable to connect to the database.
26    ///
27    /// Cancellation is inherently racy. There is no guarantee that the
28    /// cancellation request will reach the server before the query terminates
29    /// normally, or that the connection associated with this token is still
30    /// active.
31    ///
32    /// Requires the `runtime` Cargo feature (enabled by default).
33    #[cfg(feature = "runtime")]
34    pub async fn cancel_query<T>(&self, tls: T) -> Result<(), Error>
35    where
36        T: MakeTlsConnect<Socket>,
37    {
38        cancel_query::cancel_query(
39            self.socket_config.clone(),
40            self.ssl_mode,
41            self.ssl_negotiation,
42            tls,
43            self.process_id,
44            self.secret_key,
45        )
46        .await
47    }
48
49    /// Like `cancel_query`, but uses a stream which is already connected to the server rather than opening a new
50    /// connection itself.
51    pub async fn cancel_query_raw<S, T>(&self, stream: S, tls: T) -> Result<(), Error>
52    where
53        S: AsyncRead + AsyncWrite + Unpin,
54        T: TlsConnect<S>,
55    {
56        cancel_query_raw::cancel_query_raw(
57            stream,
58            self.ssl_mode,
59            self.ssl_negotiation,
60            tls,
61            true,
62            self.process_id,
63            self.secret_key,
64        )
65        .await
66    }
67}