Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion pkgs/id/src/world/actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,23 @@ impl WorldActor {
if !self.active_subs.insert(sub.clone()) {
continue;
}
// The tick floor is a hard limit, not a grant question: a
// sub-floor tick is refused like a denied subscription (once
// per spec) and never armed, however it was granted.
if let Subscription::Tick(ms) = sub
&& *ms < self.core.limits.min_tick_ms
{
let spec = sub.spec();
if self.denied_subs.insert(spec.clone()) {
let error = crate::world_caps::CapError::bad_args_with(format!(
"time.tick interval {ms}ms is below the world minimum {}ms",
self.core.limits.min_tick_ms
));
self.deliver(crate::world_caps::subscription_refused_event(&spec, error))
.await;
}
continue;
}
match self.core.ledger.decide(sub.cap()) {
Decision::Allow => self.arm(sub),
Decision::AllowAndGrant => {
Expand All @@ -529,8 +546,10 @@ impl WorldActor {
}

/// Arm a granted subscription's timer, if any and if anyone is present.
/// A tick below the world's `min_tick_ms` floor is never armed.
fn arm(&mut self, sub: &Subscription) {
if let Subscription::Tick(ms) = sub
&& *ms >= self.core.limits.min_tick_ms
&& !self.presence.is_empty()
&& !self.ticks.contains_key(ms)
{
Expand Down Expand Up @@ -804,7 +823,12 @@ impl WorldActor {
.active_subs
.iter()
.filter_map(|sub| match sub {
Subscription::Tick(ms) if self.core.ledger.is_granted(sub.cap()) => Some(*ms),
Subscription::Tick(ms)
if *ms >= self.core.limits.min_tick_ms
&& self.core.ledger.is_granted(sub.cap()) =>
{
Some(*ms)
}
_ => None,
})
.collect();
Expand Down
4 changes: 4 additions & 0 deletions pkgs/id/src/world/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ impl WorldCore {
limits.snapshot_bytes > 0,
"world snapshot limit must be nonzero"
);
ensure!(
limits.min_tick_ms > 0,
"world minimum tick interval must be nonzero"
);
let server_caps: Vec<String> = limits.server_caps.iter().cloned().collect();
crate::world_caps::validate_ceiling_names(&server_caps)
.context("server capability ceiling")?;
Expand Down
3 changes: 2 additions & 1 deletion pkgs/id/src/world/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ pub struct WorldLimits {
/// Trim the journal behind a program snapshot once this many events were
/// committed since the last one. `0` disables checkpointing.
pub checkpoint_every: u64,
/// Slowest tick a program may subscribe to, in milliseconds.
/// Minimum tick interval a program may subscribe to, in milliseconds.
/// Subscriptions below this floor are refused at subscription time.
pub min_tick_ms: u64,
/// Whether a world's policy grants a capability on its first use.
pub grant_on_use: bool,
Expand Down
107 changes: 103 additions & 4 deletions pkgs/id/src/world/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -678,11 +678,89 @@ mod tests {
.unwrap_or(0)
}

/// A program that subscribes to fixed tick intervals and counts deliveries.
#[derive(Debug)]
struct FixedTicks {
subscribe: Vec<String>,
ticks: u64,
}

impl WorldProgram for FixedTicks {
fn update(&mut self, event: &WorldEvent) -> Result<()> {
if let WorldEventKind::System { event } = &event.kind {
let value: serde_json::Value =
serde_json::from_str(event).unwrap_or(serde_json::Value::Null);
if value["cap"] == "time.tick" {
self.ticks += 1;
}
}
Ok(())
}

fn wants(&mut self) -> Result<Option<String>> {
Ok(Some(
serde_json::json!({"v": 1, "subscribe": self.subscribe.clone()}).to_string(),
))
}

fn records(&mut self) -> Result<Option<String>> {
Ok(Some(serde_json::json!({"ticks": self.ticks}).to_string()))
}
}

#[tokio::test]
async fn sub_floor_ticks_are_refused_at_the_default_and_custom_floors() {
for (floor, below, at) in [(1000, 999, 1000), (250, 249, 250)] {
let clock: Arc<ManualClock> = Arc::new(ManualClock::new(0));
let limits = WorldLimits {
min_tick_ms: floor,
..WorldLimits::default()
};
let mut core = WorldCore::new_with_clock("tick-floor", limits, clock.clone()).unwrap();
core.ledger
.set_granted(BTreeSet::from(["time.tick".to_owned()]));
let (_, _token) = core
.issue_capability("ann", WorldScopes::GUEST, CapabilityBounds::default())
.unwrap();
let program = FixedTicks {
subscribe: vec![format!("time.tick:{below}"), format!("time.tick:{at}")],
ticks: 0,
};
let mut actor = WorldActor::for_test(core, Box::new(program), None);

actor.after_change().await;
assert!(
actor.denied_subs.contains(&format!("time.tick:{below}")),
"the sub-floor tick was not refused at floor {floor}"
);

actor
.handle(WorldCommand::Presence {
participant: 1,
joined: true,
})
.await;
assert!(!actor.ticks.contains_key(&below), "sub-floor tick armed");
assert!(actor.ticks.contains_key(&at), "at-floor tick did not arm");

clock.advance(at);
actor.fire_ticks().await;
assert_eq!(tick_count(&actor), 1, "only the at-floor tick delivered");
}
}

#[tokio::test]
async fn subscribed_ticks_arrive_only_while_someone_is_present() {
let clock: Arc<ManualClock> = Arc::new(ManualClock::new(0));
let mut core =
WorldCore::new_with_clock("ticks", WorldLimits::default(), clock.clone()).unwrap();
WorldCore::new_with_clock(
"ticks",
WorldLimits {
min_tick_ms: 20,
..WorldLimits::default()
},
clock.clone(),
).unwrap();
core.ledger
.set_granted(BTreeSet::from(["time.tick".to_owned()]));
let (_, _token) = core
Expand Down Expand Up @@ -728,7 +806,14 @@ mod tests {
async fn ticks_follow_the_world_grant_not_a_participant_capability() {
let clock: Arc<ManualClock> = Arc::new(ManualClock::new(0));
let mut core =
WorldCore::new_with_clock("ticks", WorldLimits::default(), clock.clone()).unwrap();
WorldCore::new_with_clock(
"ticks",
WorldLimits {
min_tick_ms: 20,
..WorldLimits::default()
},
clock.clone(),
).unwrap();
core.ledger
.set_granted(BTreeSet::from(["time.tick".to_owned()]));
let owner_scopes = WorldScopes(WorldScopes::GUEST.bits() | WorldScopes::DELEGATE.bits());
Expand Down Expand Up @@ -799,7 +884,14 @@ mod tests {
async fn ticks_speak_for_the_world_not_for_a_present_participant() {
let clock: Arc<ManualClock> = Arc::new(ManualClock::new(0));
let mut core =
WorldCore::new_with_clock("tick-attribution", WorldLimits::default(), clock.clone())
WorldCore::new_with_clock(
"tick-attribution",
WorldLimits {
min_tick_ms: 20,
..WorldLimits::default()
},
clock.clone(),
)
.unwrap();
core.ledger.set_granted(BTreeSet::from([
"time.tick".to_owned(),
Expand Down Expand Up @@ -1036,7 +1128,14 @@ mod tests {
async fn lowering_the_ceiling_stops_an_active_subscription_and_reports_it_refused() {
let clock: Arc<ManualClock> = Arc::new(ManualClock::new(0));
let mut core =
WorldCore::new_with_clock("ceiling-ticks", WorldLimits::default(), clock.clone())
WorldCore::new_with_clock(
"ceiling-ticks",
WorldLimits {
min_tick_ms: 20,
..WorldLimits::default()
},
clock.clone(),
)
.unwrap();
core.ledger
.set_granted(BTreeSet::from(["time.tick".to_owned()]));
Expand Down
Loading