Skip to content

Commit 37ceae2

Browse files
committed
Add metric when acquiring permit to make outbound request
Signed-off-by: Ryan Levick <[email protected]>
1 parent 463a3ff commit 37ceae2

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

crates/factor-outbound-http/src/spin.rs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,28 @@ impl spin_http::Host for crate::InstanceState {
101101
// Note: since we don't have access to the underlying connection, we can only
102102
// limit the number of concurrent requests, not connections.
103103
let permit = match &self.concurrent_outbound_connections_semaphore {
104-
Some(s) => s.acquire().await.ok(),
104+
Some(s) => {
105+
// Try to acquire a permit without waiting first
106+
// Keep track of whether we had to wait for metrics purposes.
107+
let mut waited = false;
108+
let permit = match s.try_acquire() {
109+
Ok(p) => Ok(p),
110+
// No available permits right now; wait for one
111+
Err(tokio::sync::TryAcquireError::NoPermits) => {
112+
waited = true;
113+
s.acquire().await.map_err(|_| ())
114+
}
115+
Err(_) => Err(()),
116+
};
117+
if permit.is_ok() {
118+
spin_telemetry::monotonic_counter!(
119+
outbound_http.acquired_permits = 1,
120+
interface = "spin",
121+
waited = waited
122+
);
123+
}
124+
permit.ok()
125+
}
105126
None => None,
106127
};
107128
let resp = client.execute(req).await.map_err(log_reqwest_error)?;

crates/factor-outbound-http/src/wasi.rs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -599,7 +599,28 @@ impl ConnectOptions {
599599

600600
// If we're limiting concurrent outbound requests, acquire a permit
601601
let permit = match &self.concurrent_outbound_connections_semaphore {
602-
Some(s) => s.clone().acquire_owned().await.ok(),
602+
Some(s) => {
603+
// Try to acquire a permit without waiting first
604+
// Keep track of whether we had to wait for metrics purposes.
605+
let mut waited = false;
606+
let permit = match s.clone().try_acquire_owned() {
607+
Ok(p) => Ok(p),
608+
// No available permits right now; wait for one
609+
Err(tokio::sync::TryAcquireError::NoPermits) => {
610+
waited = true;
611+
s.clone().acquire_owned().await.map_err(|_| ())
612+
}
613+
Err(_) => Err(()),
614+
};
615+
if permit.is_ok() {
616+
spin_telemetry::monotonic_counter!(
617+
outbound_http.acquired_permits = 1,
618+
interface = "wasi",
619+
waited = waited
620+
);
621+
}
622+
permit.ok()
623+
}
603624
None => None,
604625
};
605626

0 commit comments

Comments
 (0)