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: 15 additions & 11 deletions crates/resource/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,19 +72,19 @@ impl ResourceBuilder {

/// Build the definition and the usage and bounds record types.
///
/// With no capacities the result is a unit resource: an empty usage record
/// and no bounds.
///
/// # Errors
///
/// Errors if no capacity was added, a name is repeated, or generating the
/// records or constraint data fails.
/// Errors if a name is repeated, or generating the records or constraint
/// data fails.
pub fn build(self) -> Result<ResourceParts, BuildError> {
let ResourceBuilder {
name,
capacities,
mut errors,
} = self;
if capacities.is_empty() {
errors.push(BuildError::NoCapacities);
}
match errors.len() {
0 => {}
1 => return Err(errors.pop().unwrap()),
Expand Down Expand Up @@ -152,8 +152,6 @@ fn suffixed_identifier(resource: &Identifier, suffix: &str) -> Result<Identifier

#[derive(Debug, Error)]
pub enum BuildError {
#[error("resource must declare at least one capacity")]
NoCapacities,
#[error("duplicate capacity \"{0}\"")]
DuplicateCapacity(Identifier),
#[error("multiple resource builder errors: {0:?}")]
Expand Down Expand Up @@ -197,13 +195,19 @@ mod tests {
Ok(())
}

/// A resource with no capacities is a unit resource: a fieldless usage
/// record and no bounds.
#[test]
fn rejects_empty_resource() {
let result = ResourceBuilder::new(Identifier::try_new("Memory").unwrap()).build();
assert!(matches!(result, Err(BuildError::NoCapacities)));
fn builds_unit_resource() -> Result<(), BuildError> {
let parts = ResourceBuilder::new(Identifier::try_new("Thread")?).build()?;
assert!(parts.definition.capacities().unwrap().next().is_none());
assert_eq!(parts.usage.name(), &Identifier::try_new("ThreadUsage")?);
assert_eq!(parts.usage.fields().count(), 0);
assert!(parts.bounds.is_none());
Ok(())
}

/// Requirement 2: capacity identifiers are unique within a resource.
/// Requirement 1: capacity identifiers are unique within a resource.
#[test]
fn rejects_duplicate_capacities() {
let bytes = Identifier::try_new("bytes").unwrap();
Expand Down
49 changes: 21 additions & 28 deletions crates/resource/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,22 @@ pub use builder::{BuildError, ResourceBuilder, ResourceParts};
///
/// ## Requirements
///
/// 1. A resource is an entity with at least one [`Capacity`].
/// 2. [`Capacity`] identifiers are unique within a resource.
/// 3. If and only if any of the resource's capacities have a bound, the
/// 1. [`Capacity`] identifiers are unique within a resource.
/// 2. If and only if any of the resource's capacities have a bound, the
/// resource entity has at least one event (the "bounds event") which
/// declares the bounds of all capacities that are bounded.
/// 4. An entity can use some quantity of a resource's capacities if and
/// 3. An entity can use some quantity of a resource's capacities if and
/// only if it is an FSM.
/// 5. The resource named by a usage or bounds is a declared resource.
/// 6. A usage claims only capacities declared by its resource.
/// 7. A usage record is used only as the data carried by an entity reference.
/// 8. A bounds record is used only by events of the resource it names.
/// 4. The resource named by a usage or bounds is a declared resource.
/// 5. A usage claims only capacities declared by its resource.
/// 6. A usage record is used only as the data carried by an entity reference.
/// 7. A bounds record is used only by events of the resource it names.
///
/// ## Unit resources
///
/// A resource without capacities is a unit resource. It has an implicit,
/// dimensionless capacity with a fixed bound of one, which each usage claims in
/// full.
#[derive(Default)]
pub struct ResourceConstraint {
errors: Vec<ResourceError>,
Expand Down Expand Up @@ -87,7 +92,7 @@ pub enum CapacityKind {
Rate,
}

// Map keys enforce capacity-name uniqueness (requirement 2).
// Map keys enforce capacity-name uniqueness (requirement 1).
type Capacities = indexmap::IndexMap<Identifier, Capacity>;

/// Payload of the `quent.resource.v0.1.0` constraint.
Expand Down Expand Up @@ -152,7 +157,6 @@ impl Visitor for ResourceConstraint {
Element::Entity(entity) => {
match self.decode_resource_annotation(cursor, entity.annotations()) {
Some(Resource::Definition(capacities)) => {
self.validate_definition(entity.name(), &capacities);
self.resources.insert(
entity.name().clone(),
capacities
Expand Down Expand Up @@ -248,7 +252,7 @@ impl Visitor for ResourceConstraint {
record_refs,
} = self;

// Requirements 5 and 6: a usage names a declared resource and claims
// Requirements 4 and 5: a usage names a declared resource and claims
// only that resource's capacities.
for UsageRecord {
resource,
Expand All @@ -274,7 +278,7 @@ impl Visitor for ResourceConstraint {
}
}

// Requirements 4, 7 and 8: validate references after record roles are
// Requirements 3, 6 and 7: validate references after record roles are
// known.
let mut non_fsm_seen = FxHashSet::default();
let mut resources_with_bounds_event = FxHashSet::default();
Expand All @@ -286,14 +290,14 @@ impl Visitor for ResourceConstraint {
} in &record_refs
{
if let Some(usage) = usage_records.get(record) {
// Requirement 7: a usage is carried by an entity reference.
// Requirement 6: a usage is carried by an entity reference.
if !on_entity_ref {
errors.push(ResourceError::UsageNotOnReference {
location: location.clone(),
});
continue;
}
// Requirement 4: only an FSM entity may use a resource.
// Requirement 3: only an FSM entity may use a resource.
match entity {
Some((entity, is_fsm)) => {
if !is_fsm && non_fsm_seen.insert((entity.clone(), usage.resource.clone()))
Expand All @@ -311,7 +315,7 @@ impl Visitor for ResourceConstraint {
}),
}
} else if let Some(bounds) = bounds_records.get(record) {
// Requirement 8: a bounds record belongs to its resource, so the
// Requirement 7: a bounds record belongs to its resource, so the
// entity referencing it must be that resource.
let on_resource = matches!(entity, Some((entity, _)) if entity == &bounds.resource);
if !on_resource {
Expand All @@ -325,7 +329,7 @@ impl Visitor for ResourceConstraint {
}
}

// Requirement 3: a bounds record covers exactly its resource's bounded
// Requirement 2: a bounds record covers exactly its resource's bounded
// capacities.
for BoundsRecord {
resource,
Expand Down Expand Up @@ -367,7 +371,7 @@ impl Visitor for ResourceConstraint {
}
}

// Requirement 3: a resource with a bounded capacity has a bounds event.
// Requirement 2: a resource with a bounded capacity has a bounds event.
for (resource, capacities) in &resources {
if capacities.values().any(|bounded| *bounded)
&& !resources_with_bounds_event.contains(resource)
Expand Down Expand Up @@ -407,15 +411,6 @@ impl ResourceConstraint {
Some(Ok(resource)) => Some(resource),
}
}

/// Validate requirements local to a resource definition.
fn validate_definition(&mut self, resource: &Identifier, capacities: &Capacities) {
if capacities.is_empty() {
self.errors.push(ResourceError::NoCapacities {
resource: resource.clone(),
});
}
}
}

impl Constraint for ResourceConstraint {
Expand Down Expand Up @@ -469,8 +464,6 @@ pub enum ResourceError {
role: &'static str,
element: &'static str,
},
#[error("resource \"{resource}\" declares no capacities")]
NoCapacities { resource: Identifier },
#[error("{location}: names undeclared resource \"{resource}\"")]
UnknownResource {
location: String,
Expand Down
29 changes: 12 additions & 17 deletions crates/resource/tests/resource-constraint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,22 +123,17 @@ fn valid_resource_passes() {
assert!(resource_errors(&schema("App", vec![memory, worker], vec![bounds, usage])).is_empty());
}

/// Requirement 1: a resource has at least one capacity.
/// A resource with no capacities is accepted as a unit resource.
#[test]
fn resource_without_capacity_is_rejected() {
let memory = resource_entity("Memory", &[], None);
let errors = resource_errors(&schema("App", vec![memory], vec![]));
assert!(
errors
.iter()
.any(|e| matches!(e, ResourceError::NoCapacities { .. }))
);
fn unit_resource_is_accepted() {
let thread = resource_entity("Thread", &[], None);
assert!(resource_errors(&schema("App", vec![thread], vec![])).is_empty());
}

// Requirement 2 is enforced by definition map keys. Repeated builder inputs
// Requirement 1 is enforced by definition map keys. Repeated builder inputs
// are covered by `builder::tests::rejects_duplicate_capacities`.

/// Requirement 3: bounds exist exactly for bounded resources and cover all
/// Requirement 2: bounds exist exactly for bounded resources and cover all
/// bounded capacities.
#[test]
fn bounds_match_resource_boundedness() {
Expand Down Expand Up @@ -182,7 +177,7 @@ fn bounds_match_resource_boundedness() {
));
}

/// Requirements 4–7 govern resource usage.
/// Requirements 3–6 govern resource usage.
///
/// Resource users must be FSM entities. Usage and bounds records must name
/// declared resources, claims must name declared capacities, and usage records
Expand All @@ -203,35 +198,35 @@ fn invalid_usages_are_rejected() {
[usage, bad_claim, off_ref, unknown_usage, unknown_bounds],
));

// Requirement 4: only an FSM entity may use a resource.
// Requirement 3: only an FSM entity may use a resource.
assert!(
errors
.iter()
.any(|e| matches!(e, ResourceError::NonFsmUser { entity, .. } if entity == "Worker"))
);

// Requirement 5: usage and bounds records name declared resources.
// Requirement 4: usage and bounds records name declared resources.
assert!(errors.iter().any(
|e| matches!(e, ResourceError::UnknownResource { resource, .. } if resource == "Ghost")
));
assert!(errors.iter().any(
|e| matches!(e, ResourceError::UnknownResource { resource, .. } if resource == "Phantom")
));

// Requirement 6: a usage claims only its resource's capacities.
// Requirement 5: a usage claims only its resource's capacities.
assert!(errors.iter().any(
|e| matches!(e, ResourceError::UndeclaredCapacity { capacity, .. } if capacity == "watts")
));

// Requirement 7: a usage record rides on an entity reference.
// Requirement 6: a usage record rides on an entity reference.
assert!(
errors
.iter()
.any(|e| matches!(e, ResourceError::UsageNotOnReference { .. }))
);
}

/// Requirement 8: a bounds record appears only on its own resource's events.
/// Requirement 7: a bounds record appears only on its own resource's events.
#[test]
fn bounds_record_used_by_a_foreign_entity_is_rejected() {
let memory = resource_entity(
Expand Down