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
//! One absolute cutoff covers acquisition and application execution; cancelled leases close.
use super::{
OperationFuture, PgConnection, PgFallibleOperationError, PgOperation, PgOperationError,
lease::Lease, operation_metrics::Observation,
};
use std::time::Duration;
use tokio::time::{Instant, timeout_at};
use tracing::Instrument;
impl PgOperation {
/// Acquire and execute once under an absolute deadline, at most 24 hours away.
///
/// Pass `RequestDeadline::instant()` to preserve time already spent in a request.
/// Pool acquisition also retains the pool's own shorter allowance. An expired
/// deadline never invokes the callback. The callback may run multiple native
/// queries and explicitly begin/commit/rollback a transaction; it is never retried.
///
/// Timeout, cancellation, and panic close the checked-out connection rather than
/// recycling it. Native SQLx owns that asynchronous close and retains the pool
/// permit until it completes. A completed callback returns its result while
/// the connection recycles in the background, within the pool acquisition
/// allowance. Pool closure or expiry discards a connection still recycling.
/// Server work may continue until disconnect or the configured session timeout.
/// A client timeout does not prove a write failed
/// to commit. Awaited native errors are available through `PgOperationError`.
/// Synchronous blocking work cannot be preempted by this cooperative deadline.
pub async fn run<T, F>(&self, deadline: Instant, operation: F) -> Result<T, PgOperationError>
where
T: Send,
F: for<'connection> FnOnce(
&'connection mut PgConnection,
) -> OperationFuture<'connection, T>
+ Send,
{
self.run_with(deadline, operation, PgOperationError::Query)
.await
}
/// Run with an application error type under the same contract as [`Self::run`].
///
/// The callback borrows the checked-out connection. Begin and commit
/// transactions inside the callback. Use `?` for native SQLx errors when
/// the application error type implements `From<sqlx::Error>`.
/// Servlet returns such errors unchanged in [`PgFallibleOperationError::Application`].
/// Acquisition and deadline failures remain available through
/// [`PgFallibleOperationError::Operation`]. Callback errors use the existing
/// `query_error` metric and span outcome without recording error details.
pub async fn run_fallible<T, E, F>(
&self,
deadline: Instant,
operation: F,
) -> Result<T, PgFallibleOperationError<E>>
where
T: Send,
F: for<'connection> FnOnce(
&'connection mut PgConnection,
) -> OperationFuture<'connection, T, E>
+ Send,
{
self.run_with(deadline, operation, PgFallibleOperationError::Application)
.await
}
async fn run_with<T, E, F, R>(
&self,
deadline: Instant,
operation: F,
callback_error: impl FnOnce(E) -> R + Send,
) -> Result<T, R>
where
F: for<'connection> FnOnce(
&'connection mut PgConnection,
) -> OperationFuture<'connection, T, E>
+ Send,
R: From<PgOperationError>,
{
let span = tracing::info_span!("postgresql.operation", pool = %self.pool_name,
operation = %self.name, "db.system.name" = "postgresql", "otel.kind" = "client",
outcome = tracing::field::Empty, "otel.status_code" = tracing::field::Empty);
let observation = span.clone();
async move {
let mut observed = Observation::new(self.metrics.clone(), observation);
if deadline.saturating_duration_since(Instant::now()) > Duration::from_secs(86400) {
observed.invalid_deadline();
return Err(PgOperationError::InvalidDeadline.into());
}
if Instant::now() >= deadline {
observed.acquired(2);
observed.finish(3);
return Err(PgOperationError::Deadline.into());
}
let acquired = timeout_at(deadline, async {
self.pool.acquire().await.map(Lease::new)
})
.await;
if Instant::now() >= deadline || acquired.is_err() {
observed.acquired(2);
observed.finish(3);
return Err(PgOperationError::Deadline.into());
}
let mut lease = match acquired.expect("timeout handled above") {
Ok(lease) => {
observed.acquired(0);
lease
}
Err(error) => {
observed.acquired(1);
observed.finish(2);
return Err(PgOperationError::Acquire(error).into());
}
};
let result = timeout_at(deadline, operation(lease.connection())).await;
if Instant::now() >= deadline || result.is_err() {
observed.finish(3);
return Err(PgOperationError::Deadline.into());
}
lease.recycle(&self.pool);
match result.expect("timeout handled above") {
Ok(value) => {
observed.finish(0);
Ok(value)
}
Err(error) => {
observed.finish(1);
Err(callback_error(error))
}
}
}
.instrument(span)
.await
}
}