Repository navigation
Entities Design Notes
A few chores have been kicked down the street.
- Add
Property<E: Entity>::hash_value()in preparation for indexes - Make a decision either way about
unsafeinentity::entity_store::get_entity_metadata_static. - Add
Property<E: Entity>::type_id()in preparation for indexes -
define_derived_property!Macro rough edges:- allow omitting empty global properties list
- Minimize or eliminate "type annotations needed"; rustc isn't good at inferring types for closures, which is how we supply function implementation to the macro. There are alternative patterns (e.g. [passing name to macro](https://stackoverflow.com/questions/50318744/creating-environment-for-closure-in-a-macro-in-rust))
Should add_entity<E: Entity> return a Result<EntityId<E>, IxaError>? Right now it fails only if InitializationList is invalid.
pub fn add_entity<E: Entity, PL: PropertyList<E>>(&mut self, property_list: PL) -> Result<EntityId<E>, IxaError>;- Makes sense to return a
Resultif we let user add an entity, say, at debug console or via web API. - Makes sense to just panic if we only care about calling the method from client code directly.
Arguments for making the EntityStore and PropertyStore fields of Context:
- Not every subsystem cares about entities/properties, but a lot of them do.
(
PluginContextdefines the minimal interface allDataPlugins can assume exists. Half of the trait extension constraints inPluginContextare related toPeopleContext.) - Accesses to these stores are often in the hottest paths / tightest loops, which recommends minimizing indirection (one fewer pointer dereference)
Arguments against making the EntityStore and PropertyStore fields of Context:
- Historically the only intrinsic properties and functions of the concrete
Contexttype is managing the timeline (events and plans). All other functionality is (was) provided by plugins. Adding entities (EntityStoreandPropertyStore) toContextexpands its responsibilities from "events that happen in time" to also include "state of the world". Philosophically, one could argue this violates the "separation of concerns" / "single responsibility" principle. (Counterargument: A good software engineer is not constrained by rules of thumb.) - Is the indirection required for accessing a
DataPlugineven measurable?
A wrapper to inhibit the compiler from automatically calling T’s destructor. This wrapper is 0-cost.
We can prevent construction of ValueVecs for values with destructors by using the needs_drop function:
impl<V> ValueVec<V> {
pub fn new() -> Self {
// Panics if `V` has a destructor.
assert!(!needs_drop::<V>(), "Type must not have a destructor");
ValueVec {
values: Vec::new(),
}
}
}- Can we further constrain
Vto be!Drop(and/or!Clone) ? - Where is the compiler inserting
Drop? Can we only implement mutating primitives such thatDropis not called? (If we never "delete" something. IsDropcalled when overwritten?) - If we provide a trivial implementation of
Dropfor allPropertytypes, does that solve the problem? (Could there be a hiddenDropimpl called somehow by virtue of what the type is?)
- The entity ID should know the
Entitytype so that aPersonIdcan't be used as aSettingId. - The original
PersonIdtype is opaque–it cannot be created or destructured outside of theixacrate. To achieve the same thing, we do this:EntityId<E: Entity>(usize, PhantomData<E>) -
Entitycannot store the entity count, because we don't want client code to be able to create a new entity (or modify the entity count), and theEntitytypes are implemented in client code. So we store the entity count in theEntityStore.
This is suspicious:
/// Emitted when a new person is created
/// These should not be emitted outside this module
#[derive(Clone, Copy, IxaEvent)]
#[allow(clippy::manual_non_exhaustive)]
pub struct PersonCreatedEvent {
/// The [`PersonId`] of the new person.
pub person_id: PersonId,
}What does "should not be emitted outside this module" mean? Does this mean that add_person is the only thing that emits the event?
The code adding the entity (person) already gets the new PersonId, so this is for nonlocal code execution on entity creation.
Originally it appears we assumed that it is not possible to have a non-required property without a default value. (I think we just let an internal unwrap fail.) Should we enforce this in the macro implementations? (Related to the next section as well.)
Right now we store: Vec<Option<Property>>
But maybe we should only store: Vec<Property>
If the value is allowed to be not set, it should be an Option<Property>. The difference is, do we enforce this at the API level, or do we make client code deal with it?
- If you try to set a property to the value it already has, is a property change event emitted? (Previously, yes.)
- If you try to set an unset property to its default value, is a property change event emitted? (Previously, yes.)
See PropertyValueStore::replace().
Also: Previously, it appears we assumed that it is not possible to have a non-required property without a default
value. Now we do allow this. Thus, PropertyChangeEvent::previous is now an option.
There are several places in ixa internals where we have checks for
things that should never happen unless there's a bug in ixa itself. These
checks could be conditionally removed depending on the build profile:
#[inline(always)]
fn expect_debug_only<T>(opt: Option<T>, msg: &str) -> T {
if cfg!(debug_assertions) {
opt.expect(msg)
} else {
unsafe { opt.unwrap_unchecked() }
}
}
// or the plain vanilla inline version:
let value = if cfg!(debug_assertions) {
property_store
.get(entity_id)
.expect("getting a property value with \"constant\" initialization should never fail")
} else {
unsafe { property_store.get(entity_id).unwrap_unchecked() }
};The actual performance impact of this is probably negligible. It might be worth running some experiments to see if it's worth it.
We have this "rng_name_duplication_guard_" thing that I don't understand. Some research shows it was a pre-Rust 2018 hack to prevent global singletons with the same name.
- It doesn't work anymore (maybe?).
- Why not have RNGs with the same name?
- The macro makes the RNG private, so it's not accessible outside of the module anyway.
Alternatives (that I am also suspicious of):
- Just remove it. We trust client code to know how to refer to the correct symbol in other places.
- "private trait" trick:
$crate::paste::paste! {
trait [<__rng_guard_ $random_id>] {}
impl [<__rng_guard_ $random_id>] for () {}
}- unique
constgeneric:
struct __RngNameDupGuard<const NAME: &'static str>;
type _ = __RngNameDupGuard<{ stringify!($random_id) }>;We synthesize these types with macros without a pub visibility (or any other visibility).
DataPlugin- RNGs
EntityProperty<E: Entity>