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