Skip to content

Commit 2cdc5a1

Browse files
committed
Add metric when acquiring permit to make outbound request
Signed-off-by: Ryan Levick <ryan.levick@fermyon.com>
1 parent b332f52 commit 2cdc5a1

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
@@ -105,7 +105,28 @@ impl spin_http::Host for crate::InstanceState {
105105
// Note: since we don't have access to the underlying connection, we can only
106106
// limit the number of concurrent requests, not connections.
107107
let permit = match &self.concurrent_outbound_connections_semaphore {
108-
Some(s) => s.acquire().await.ok(),
108+
Some(s) => {
109+
// Try to acquire a permit without waiting first
110+
// Keep track of whether we had to wait for metrics purposes.
111+
let mut waited = false;
112+
let permit = match s.try_acquire() {
113+
Ok(p) => Ok(p),
114+
// No available permits right now; wait for one
115+
Err(tokio::sync::TryAcquireError::NoPermits) => {
116+
waited = true;
117+
s.acquire().await.map_err(|_| ())
118+
}
119+
Err(_) => Err(()),
120+
};
121+
if permit.is_ok() {
122+
spin_telemetry::monotonic_counter!(
123+
outbound_http.acquired_permits = 1,
124+
interface = "spin",
125+
waited = waited
126+
);
127+
}
128+
permit.ok()
129+
}
109130
None => None,
110131
};
111132
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
@@ -591,7 +591,28 @@ impl ConnectOptions {
591591

592592
// If we're limiting concurrent outbound requests, acquire a permit
593593
let permit = match &self.concurrent_outbound_connections_semaphore {
594-
Some(s) => s.clone().acquire_owned().await.ok(),
594+
Some(s) => {
595+
// Try to acquire a permit without waiting first
596+
// Keep track of whether we had to wait for metrics purposes.
597+
let mut waited = false;
598+
let permit = match s.clone().try_acquire_owned() {
599+
Ok(p) => Ok(p),
600+
// No available permits right now; wait for one
601+
Err(tokio::sync::TryAcquireError::NoPermits) => {
602+
waited = true;
603+
s.clone().acquire_owned().await.map_err(|_| ())
604+
}
605+
Err(_) => Err(()),
606+
};
607+
if permit.is_ok() {
608+
spin_telemetry::monotonic_counter!(
609+
outbound_http.acquired_permits = 1,
610+
interface = "wasi",
611+
waited = waited
612+
);
613+
}
614+
permit.ok()
615+
}
595616
None => None,
596617
};
597618

0 commit comments

Comments
 (0)