Skip to content
Draft
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
18 changes: 18 additions & 0 deletions libs/@local/graph/api/openapi/openapi.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions libs/@local/graph/store/rust/src/entity/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ pub use self::{
EmptyEntityTypes, EntityRetrieval, EntityTypeRetrieval, EntityTypesError,
EntityValidationReport, LinkDataStateError, LinkDataValidationReport, LinkError,
LinkTargetError, LinkValidationReport, LinkedEntityError, MetadataValidationReport,
MissingLinkData, PropertyMetadataValidationReport, UnexpectedEntityType,
UnexpectedLinkData,
MissingLinkData, PropertyMetadataValidationReport, SelfReferentialLinkData,
UnexpectedEntityType, UnexpectedLinkData,
},
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,21 @@ pub struct MissingLinkData;
#[must_use]
pub struct UnexpectedLinkData;

#[derive(Debug, derive_more::Display, derive_more::Error)]
#[display("The link has the same left and right entity: {entity_id}")]
#[must_use]
pub struct SelfReferentialLinkData {
pub entity_id: EntityId,
}

#[derive(Debug, serde::Serialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde(tag = "type", content = "error", rename_all = "camelCase")]
#[must_use]
pub enum LinkDataStateError {
Missing(Report<MissingLinkData>),
Unexpected(Report<UnexpectedLinkData>),
SelfReferential(Report<SelfReferentialLinkData>),
}

#[derive(Debug, serde::Serialize)]
Expand Down
12 changes: 10 additions & 2 deletions libs/@local/graph/validation/src/entity_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ use futures::{StreamExt as _, TryStreamExt as _, stream};
use hash_graph_store::entity::{
EntityRetrieval, EntityTypeRetrieval, LinkDataStateError, LinkDataValidationReport, LinkError,
LinkTargetError, LinkValidationReport, LinkedEntityError, MissingLinkData,
PropertyMetadataValidationReport, UnexpectedEntityType, UnexpectedLinkData,
ValidateEntityComponents,
PropertyMetadataValidationReport, SelfReferentialLinkData, UnexpectedEntityType,
UnexpectedLinkData, ValidateEntityComponents,
};
use hash_graph_types::{
knowledge::property::visitor::{
Expand Down Expand Up @@ -92,6 +92,14 @@ where
}

if components.link_validation {
if is_link && link_data.left_entity_id == link_data.right_entity_id {
validation_report.link_data = Some(LinkDataStateError::SelfReferential(
Report::new(SelfReferentialLinkData {
entity_id: link_data.left_entity_id,
}),
));
}

validation_report.link_data_validation =
link_data.validate(schema, components, context).await;
}
Expand Down
88 changes: 85 additions & 3 deletions libs/@local/graph/validation/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ mod tests {
use std::collections::HashMap;

use error_stack::ResultExt as _;
use hash_graph_store::entity::ValidateEntityComponents;
use hash_graph_store::entity::{
LinkDataStateError, LinkValidationReport, ValidateEntityComponents,
};
use hash_graph_temporal_versioning::{
ClosedTemporalBound, Interval, OpenTemporalBound, Timestamp,
};
Expand All @@ -64,10 +66,11 @@ mod tests {
use thiserror::Error;
use type_system::{
knowledge::{
entity::id::EntityUuid,
entity::{LinkData, id::EntityUuid},
property::{
Property, PropertyObject, PropertyObjectWithMetadata, PropertyValueWithMetadata,
PropertyWithMetadata, metadata::PropertyMetadata,
PropertyWithMetadata,
metadata::{PropertyMetadata, PropertyProvenance},
},
value::{ValueMetadata, metadata::ValueProvenance},
},
Expand Down Expand Up @@ -503,4 +506,83 @@ mod tests {
.await?;
Ok(PropertyValueWithMetadata { value, metadata })
}

async fn validate_friend_of_link(
left_entity_id: EntityId,
right_entity_id: EntityId,
) -> LinkValidationReport {
let mut ontology_type_resolver = OntologyTypeResolver::default();
for entity_type in [
hash_graph_test_data::entity_type::LINK_V1,
hash_graph_test_data::entity_type::link::FRIEND_OF_V1,
] {
let entity_type = serde_json::from_str::<EntityType>(entity_type)
.expect("entity type should be valid JSON");
ontology_type_resolver.add_unresolved_entity_type(
EntityTypeUuid::from_url(&entity_type.id),
Arc::new(entity_type),
);
}

let friend_of = serde_json::from_str::<EntityType>(
hash_graph_test_data::entity_type::link::FRIEND_OF_V1,
)
.expect("entity type should be valid JSON");
let resolved_data = ontology_type_resolver
.resolve_entity_type_metadata(EntityTypeUuid::from_url(&friend_of.id))
.expect("entity type should be resolvable");
let schema = ClosedMultiEntityType::from_multi_type_closed_schema(iter::once(
ClosedEntityType::from_resolve_data(friend_of, &resolved_data)
.expect("entity type should be closable"),
))
.expect("multi entity type should be closable");

let link_data = LinkData {
left_entity_id,
right_entity_id,
left_entity_confidence: None,
left_entity_provenance: PropertyProvenance::default(),
right_entity_confidence: None,
right_entity_provenance: PropertyProvenance::default(),
};

Some(&link_data)
.validate(
&schema,
ValidateEntityComponents::full(),
&Provider::new([], [], [], []),
)
.await
}

fn entity_id(uuid: u128) -> EntityId {
EntityId {
web_id: WebId::new(EntityUuid::new(Uuid::from_u128(1))),
entity_uuid: EntityUuid::new(Uuid::from_u128(uuid)),
draft_id: None,
}
}

#[tokio::test]
async fn link_with_same_left_and_right_entity_is_rejected() {
let report = validate_friend_of_link(entity_id(2), entity_id(2)).await;

assert!(
matches!(
report.link_data,
Some(LinkDataStateError::SelfReferential(_))
),
"link data with the same left and right entity should be rejected, got {report:?}"
);
}

#[tokio::test]
async fn link_with_different_left_and_right_entity_is_not_self_referential() {
let report = validate_friend_of_link(entity_id(2), entity_id(3)).await;

assert!(
report.link_data.is_none(),
"link data with different left and right entities should be accepted, got {report:?}"
);
}
}
50 changes: 50 additions & 0 deletions tests/graph/http/tests/friendship.http
Original file line number Diff line number Diff line change
Expand Up @@ -1555,6 +1555,56 @@ X-Authenticated-User-Actor-Id: {{user_id}}
});
%}

### Validate link from a person to itself
POST http://127.0.0.1:4000/entities/validate
Content-Type: application/json
X-Authenticated-User-Actor-Id: {{user_id}}

{
"entityTypes": ["{{friendship_link_entity_type_id}}"],
"properties": { "value": {} },
"linkData": {
"leftEntityId": "{{person_a_entity_id}}",
"rightEntityId": "{{person_a_entity_id}}"
}
}

> {%
client.test("status", function() {
client.assert(response.status === 200, "Response status is not 200");
client.assert(response.body["0"].link.linkData.type === "selfReferential", "Self-referential link validation error expected");
});
%}

### Insert link from a person to itself
POST http://127.0.0.1:4000/entities
Content-Type: application/json
Accept: application/json
X-Authenticated-User-Actor-Id: {{user_id}}

{
"webId": "{{user_id}}",
"properties": { "value": {} },
"entityTypeIds": ["{{friendship_link_entity_type_id}}"],
"linkData": {
"leftEntityId": "{{person_a_entity_id}}",
"rightEntityId": "{{person_a_entity_id}}"
},
"draft": true,
"provenance": {
"actorType": "machine",
"origin": {
"type": "api"
}
}
}

> {%
client.test("status", function() {
client.assert(response.status === 400, "Response status is not 400");
});
%}

### Insert link between entities
POST http://127.0.0.1:4000/entities
Content-Type: application/json
Expand Down
Loading