Skip to content

Commit 025418c

Browse files
committed
Add fastly_compute_runtime::get_heap_mib hostcall
1 parent 7743893 commit 025418c

File tree

7 files changed

+60
-14
lines changed

7 files changed

+60
-14
lines changed

src/component/compute/compute_runtime.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ impl compute_runtime::Host for ComponentCtx {
88
}
99

1010
fn get_heap_mib(&mut self) -> compute_runtime::MemoryMib {
11-
0 // TODO
11+
self.session().get_heap_usage_mib()
1212
}
1313

1414
fn get_sandbox_id(&mut self) -> String {

src/execute.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -882,6 +882,10 @@ impl ExecuteCtx {
882882

883883
Some(rx)
884884
}
885+
886+
pub fn is_component(&self) -> bool {
887+
matches!(self.instance_pre.as_ref(), Instance::Component(_))
888+
}
885889
}
886890

887891
pub struct ExecuteCtxBuilder {

src/linking.rs

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,15 @@ pub struct Limiter {
1919
internal: StoreLimits,
2020
}
2121

22-
impl Default for Limiter {
23-
fn default() -> Self {
24-
Limiter::new(1, 1, 1)
22+
impl Limiter {
23+
pub fn for_wasip2() -> Self {
24+
Self::new(100, 100, 100)
25+
}
26+
27+
pub fn for_wasip1() -> Self {
28+
Self::new(1, 1, 1)
2529
}
26-
}
2730

28-
impl Limiter {
2931
fn new(max_instances: usize, max_memories: usize, max_tables: usize) -> Self {
3032
Limiter {
3133
memory_allocated: 0,
@@ -99,7 +101,6 @@ pub struct ComponentCtx {
99101
pub wasi_random: wasmtime_wasi::random::WasiRandomCtx,
100102
pub(crate) session: Session,
101103
guest_profiler: Option<Box<GuestProfiler>>,
102-
limiter: Limiter,
103104
}
104105

105106
/// An extension trait for users of `ComponentCtx` to access the session.
@@ -132,7 +133,7 @@ impl ComponentCtx {
132133
}
133134

134135
pub fn limiter(&self) -> &Limiter {
135-
&self.limiter
136+
self.session.limiter()
136137
}
137138

138139
pub fn close_downstream_response_sender(&mut self, resp: Response<Body>) {
@@ -159,7 +160,6 @@ impl ComponentCtx {
159160
wasi_random: wasmtime_wasi::random::WasiRandomCtx::default(),
160161
session,
161162
guest_profiler: guest_profiler.map(Box::new),
162-
limiter: Limiter::new(100, 100, 100),
163163
};
164164
let mut store = Store::new(ctx.engine(), wasm_ctx);
165165
store.set_epoch_deadline(1);
@@ -182,7 +182,7 @@ impl ComponentCtx {
182182
Ok(UpdateDeadline::Yield(1))
183183
});
184184

185-
store.limiter(|ctx| &mut ctx.limiter);
185+
store.limiter(|ctx| ctx.session.limiter_mut());
186186
Ok(store)
187187
}
188188
}
@@ -207,7 +207,6 @@ pub struct WasmCtx {
207207
wasi_nn: WasiNnCtx,
208208
session: Session,
209209
guest_profiler: Option<Box<GuestProfiler>>,
210-
limiter: Limiter,
211210
}
212211

213212
impl WasmCtx {
@@ -228,7 +227,7 @@ impl WasmCtx {
228227
}
229228

230229
pub fn limiter(&self) -> &Limiter {
231-
&self.limiter
230+
self.session.limiter()
232231
}
233232
}
234233

@@ -260,7 +259,6 @@ pub(crate) fn create_store(
260259
wasi_nn,
261260
session,
262261
guest_profiler: guest_profiler.map(Box::new),
263-
limiter: Limiter::default(),
264262
};
265263
let mut store = Store::new(ctx.engine(), wasm_ctx);
266264
store.set_epoch_deadline(1);
@@ -283,7 +281,7 @@ pub(crate) fn create_store(
283281
Ok(UpdateDeadline::Yield(1))
284282
});
285283

286-
store.limiter(|ctx| &mut ctx.limiter);
284+
store.limiter(|ctx| ctx.session.limiter_mut());
287285
Ok(store)
288286
}
289287

src/session.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ use std::sync::{Arc, Mutex};
1818
use std::time::Duration;
1919

2020
use crate::cache::{Cache, CacheEntry};
21+
use crate::linking::Limiter;
2122
use crate::object_store::KvStoreError;
2223
use crate::wiggle_abi::types::{CacheBusyHandle, CacheHandle, FramingHeadersMode};
2324

@@ -122,6 +123,7 @@ pub struct Session {
122123
secrets_by_name: PrimaryMap<SecretHandle, SecretLookup>,
123124
/// How many additional downstream requests have been receive by this Session.
124125
next_req_accepted: usize,
126+
limiter: Limiter,
125127
}
126128

127129
impl Session {
@@ -144,6 +146,12 @@ impl Session {
144146
});
145147
let downstream_req_body_handle = async_items.push(Some(AsyncItem::Body(body))).into();
146148

149+
let limiter = if ctx.is_component() {
150+
Limiter::for_wasip2()
151+
} else {
152+
Limiter::for_wasip1()
153+
};
154+
147155
Session {
148156
session_id,
149157
downstream_req_handle,
@@ -165,6 +173,7 @@ impl Session {
165173
secrets_by_name: PrimaryMap::new(),
166174
downstream_pending_handle: None,
167175
next_req_accepted: 0,
176+
limiter,
168177

169178
ctx,
170179
}
@@ -1325,6 +1334,24 @@ impl Session {
13251334
pub fn ctx(&self) -> &Arc<ExecuteCtx> {
13261335
&self.ctx
13271336
}
1337+
1338+
/// Get the guest's heap usage in mebibytes.
1339+
///
1340+
/// This rounds up to the nearest mebibyte, so that guests won't accidentally
1341+
/// rely on implementation details that may change over time.
1342+
pub fn get_heap_usage_mib(&self) -> u32 {
1343+
const MEBIBYTE: usize = 1024 * 1024;
1344+
let mb = self.limiter.memory_allocated.next_multiple_of(MEBIBYTE) / MEBIBYTE;
1345+
mb.try_into().unwrap_or(u32::MAX)
1346+
}
1347+
1348+
pub fn limiter(&self) -> &Limiter {
1349+
&self.limiter
1350+
}
1351+
1352+
pub fn limiter_mut(&mut self) -> &mut Limiter {
1353+
&mut self.limiter
1354+
}
13281355
}
13291356

13301357
pub struct SelectedTargets<'session> {

src/wiggle_abi/compute_runtime.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,8 @@ impl FastlyComputeRuntime for Session {
1111
// try to minimize timing attacks.
1212
Ok(self.active_cpu_time_us.load(Ordering::SeqCst) / 1000)
1313
}
14+
15+
fn get_heap_mib(&mut self, _memory: &mut GuestMemory<'_>) -> Result<u32, Error> {
16+
Ok(self.get_heap_usage_mib())
17+
}
1418
}

wasm_abi/compute-at-edge-abi/compute-at-edge.witx

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1352,6 +1352,18 @@
13521352
(@interface func (export "get_vcpu_ms")
13531353
(result $err (expected $vcpu_ms (error $fastly_status)))
13541354
)
1355+
1356+
;;; Get a snapshot of the current dynamic memory usage, rounded up to the nearest mebibyte (2^20).
1357+
;;;
1358+
;;; This includes usage from the Wasm linear memory (heap) and usage from host allocations
1359+
;;; made on behalf of this sandbox, e.g. buffered bodies of HTTP responses.
1360+
;;; The returned value is just a snapshot- it can change without any explicit action
1361+
;;; by the sandbox (for instance, additional response data coming in from an HTTP response.)
1362+
;;; It can also change over time / across runs, as the Compute platform's memory usage
1363+
;;; changes. Consider the returned value with these uncertainties in mind.
1364+
(@interface func (export "get_heap_mib")
1365+
(result $err (expected $memory_mib (error $fastly_status)))
1366+
)
13551367
)
13561368

13571369
(module $fastly_acl

wasm_abi/compute-at-edge-abi/typenames.witx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,7 @@
491491

492492
(typename $body_length u64)
493493
(typename $vcpu_ms u64)
494+
(typename $memory_mib u32)
494495

495496
(typename $inspect_info_mask
496497
(flags (@witx repr u32)

0 commit comments

Comments
 (0)