use std::collections::{BTreeMap, BTreeSet};
use nibkeep_base::{EntityId, SpaceId};
use nibkeep_model::schema::{FIELD_DEFINITION, TYPE_DEFINITION};
use nibkeep_model::storage::Statements;
use nibkeep_model::{FieldDef, FieldName, Languages, Resolution, State, TypeName, Types, Value};
use nibkeep_time::Day;
use super::Library;
use super::entities::{Listed, More, Searched, defines_types, display_name, resolve};
use crate::NodeError;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Links {
pub field: FieldName,
pub reverse: Option<FieldName>,
pub role: bool,
pub count: usize,
pub entities: Vec<Linking>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Linking {
pub id: EntityId,
pub name: Option<String>,
pub types: Vec<TypeName>,
pub participants: Vec<(FieldName, Vec<EntityId>)>,
}
impl Library {
pub fn links_to(
&self,
space: SpaceId,
entity: EntityId,
day: Day,
limit: usize,
) -> Result<Vec<Links>, NodeError> {
let open = self.space(space)?;
open.stored.reading(|_| {
links_to(
open.stored.log().state(),
&open.types,
&self.languages,
(entity, Some(day)),
(day, limit),
)
})
}
pub fn links_to_on_any_day(
&self,
space: SpaceId,
entity: EntityId,
day: Day,
limit: usize,
) -> Result<Vec<Links>, NodeError> {
let open = self.space(space)?;
open.stored.reading(|_| {
links_to(
open.stored.log().state(),
&open.types,
&self.languages,
(entity, None),
(day, limit),
)
})
}
pub fn same_relationship(
&self,
space: SpaceId,
kinds: &[TypeName],
values: &[(FieldName, Value)],
) -> Result<Vec<EntityId>, NodeError> {
let open = self.space(space)?;
let state = open.stored.log().state();
let types = &open.types;
let mut roles: BTreeMap<&FieldName, BTreeSet<EntityId>> = BTreeMap::new();
for (field, value) in values {
if let Some(participant) = value.as_reference()
&& types.field(field).is_some_and(|field| field.is_role())
{
roles
.entry(field)
.or_default()
.insert(state.canonical(participant)?);
}
}
let Some((first_role, first_participants)) = roles.first_key_value() else {
return Ok(Vec::new());
};
let Some(&first) = first_participants.first() else {
return Ok(Vec::new());
};
let mut same = BTreeSet::new();
for statement in state.referrers(first)? {
if statement.field != **first_role {
continue;
}
let candidate = state.canonical(statement.entity)?;
if same.contains(&candidate) || !may_link(state, candidate, first)? {
continue;
}
let held = state.types(candidate)?;
if !kinds.iter().all(|kind| held.contains(kind)) {
continue;
}
let mut holds_all = true;
for (field, participants) in &roles {
let mut current = BTreeSet::new();
for statement in state.current(candidate, field)? {
if let Some(reference) = statement.value.as_reference() {
current.insert(state.canonical(reference)?);
}
}
if !participants.is_subset(¤t) {
holds_all = false;
break;
}
}
if holds_all {
same.insert(candidate);
}
}
Ok(same.into_iter().collect())
}
}
pub(crate) fn may_link<S: Statements>(
state: &State<S>,
holder: EntityId,
entity: EntityId,
) -> Result<bool, NodeError>
where
NodeError: From<S::Error>,
{
Ok(holder != entity && !state.is_deleted(holder)? && !defines_types(state, holder)?)
}
fn refers_to<S: Statements>(
state: &State<S>,
shown: &[std::borrow::Cow<'_, nibkeep_model::Statement>],
entity: EntityId,
) -> Result<bool, NodeError>
where
NodeError: From<S::Error>,
{
for statement in shown {
if let Some(reference) = statement.value.as_reference()
&& state.canonical(reference)? == entity
{
return Ok(true);
}
}
Ok(false)
}
fn participants<S: Statements>(
state: &State<S>,
types: &Types,
languages: &Languages,
relationship: EntityId,
through: &FieldName,
day: Day,
) -> Result<Vec<(FieldName, Vec<EntityId>)>, NodeError>
where
NodeError: From<S::Error>,
{
let mut participants = Vec::new();
for field in state.fields(relationship)? {
if field == *through || !types.field(&field).is_some_and(|field| field.is_role()) {
continue;
}
let (shown, _) = resolve(state, types, languages, relationship, &field, day)?;
let mut entities = Vec::new();
for statement in &shown {
if let Some(reference) = statement.value.as_reference() {
let reference = state.canonical(reference)?;
if !entities.contains(&reference) {
entities.push(reference);
}
}
}
if !entities.is_empty() {
participants.push((field, entities));
}
}
Ok(participants)
}
pub(crate) fn searched_through<S: Statements>(
state: &State<S>,
(types, languages): (&Types, &Languages),
(hits, first): (&[EntityId], usize),
keep: &mut Keep<'_>,
) -> Result<Searched, NodeError>
where
NodeError: From<S::Error>,
{
let listed = |id: EntityId,
kinds: BTreeSet<TypeName>,
via: Option<EntityId>|
-> Result<Listed, NodeError> {
Ok(Listed {
id,
name: display_name(state, types, languages, id)?,
types: kinds.into_iter().collect(),
via,
})
};
let mut seen: BTreeSet<EntityId> = hits.iter().copied().collect();
let by_words = found_by_words(state, hits, &mut seen)?;
let mut found = Vec::new();
let mut kept = 0_usize;
for (entity, kinds) in &by_words {
if keep(*entity, kinds)? {
kept += 1;
if found.len() < first {
found.push(listed(*entity, kinds.clone(), None)?);
}
}
}
if kept > first {
return Ok(Searched {
listed: found,
more: More::AtLeast(kept - first),
});
}
let searched = types.searched_fields();
let mut add = |entities: Vec<EntityId>,
via: EntityId,
(found, kept): (&mut Vec<Listed>, &mut usize)|
-> Result<Vec<EntityId>, NodeError> {
let mut new = Vec::new();
let mut listing = Vec::new();
for entity in entities {
if !seen.insert(entity) {
continue;
}
new.push(entity);
let kinds = state.types(entity)?;
if keep(entity, &kinds)? {
*kept += 1;
if found.len() < first {
listing.push(listed(entity, kinds, Some(via))?);
}
}
}
listing.sort_by_cached_key(|entity| by_name(entity.name.as_deref(), entity.id));
found.extend(listing);
Ok(new)
};
for (hit, _) in by_words {
let (stand_ins, linked) = linking_for_search(state, (types, &searched), hit)?;
let both: Vec<EntityId> = stand_ins.iter().chain(&linked).copied().collect();
let listed_before = found.len();
let added = add(both, hit, (&mut found, &mut kept))?;
let mut through: Vec<EntityId> = added
.into_iter()
.filter(|entity| stand_ins.contains(entity))
.collect();
if found.len() < first && through.len() > 1 {
let mut ordered = Vec::with_capacity(through.len());
for entity in through {
let name = match found[listed_before..]
.iter()
.find(|listed| listed.id == entity)
{
Some(listed) => listed.name.clone(),
None => display_name(state, types, languages, entity)?,
};
ordered.push((by_name(name.as_deref(), entity), entity));
}
ordered.sort();
through = ordered.into_iter().map(|(_, entity)| entity).collect();
}
for stand_in in through {
let (_, linked) = linking_for_search(state, (types, &searched), stand_in)?;
add(
linked.into_iter().collect(),
stand_in,
(&mut found, &mut kept),
)?;
}
}
found.truncate(first);
Ok(Searched {
more: More::Exactly(kept - found.len()),
listed: found,
})
}
fn by_name(name: Option<&str>, id: EntityId) -> (bool, Option<String>, EntityId) {
let name = name.map(str::to_lowercase);
(name.is_none(), name, id)
}
pub(crate) type Keep<'a> = dyn FnMut(EntityId, &BTreeSet<TypeName>) -> Result<bool, NodeError> + 'a;
fn found_by_words<S: Statements>(
state: &State<S>,
hits: &[EntityId],
seen: &mut BTreeSet<EntityId>,
) -> Result<Vec<(EntityId, BTreeSet<TypeName>)>, NodeError>
where
NodeError: From<S::Error>,
{
let mut found = Vec::with_capacity(hits.len());
for &hit in hits {
let kinds = state.types(hit)?;
if kinds.contains(&TYPE_DEFINITION)
|| kinds.contains(&FIELD_DEFINITION)
|| kinds.contains(&nibkeep_std::THUMBNAIL)
|| kinds.contains(&nibkeep_governance::SPACE_NAMES)
{
continue;
}
let of = if kinds.contains(&nibkeep_std::ORIGIN) {
nibkeep_std::ORIGIN_OF
} else if kinds.contains(&nibkeep_std::CHECKOUT) {
nibkeep_std::CHECKOUT_OF
} else {
found.push((hit, kinds));
continue;
};
for file in super::files::found_at(state, (hit, &of))? {
if !seen.insert(file) || state.is_deleted(file)? {
continue;
}
let kinds = state.types(file)?;
if kinds.contains(&nibkeep_std::FILE) {
found.push((file, kinds));
}
}
}
Ok(found)
}
fn linking_for_search<S: Statements>(
state: &State<S>,
(types, searched): (&Types, &BTreeSet<FieldName>),
entity: EntityId,
) -> Result<(BTreeSet<EntityId>, BTreeSet<EntityId>), NodeError>
where
NodeError: From<S::Error>,
{
let mut stand_ins = BTreeSet::new();
let mut linked = BTreeSet::new();
for field in searched {
let stands_for = types
.field(field)
.is_some_and(|definition| definition.is_stands_for());
for statement in state.referrers_in(entity, field)? {
let holder = state.canonical(statement.entity)?;
if !may_link(state, holder, entity)? {
continue;
}
if stands_for {
stand_ins.insert(holder);
} else {
linked.insert(holder);
}
}
}
linked.retain(|holder| !stand_ins.contains(holder));
Ok((stand_ins, linked))
}
pub(crate) fn links_to<S: Statements>(
state: &State<S>,
types: &Types,
languages: &Languages,
(entity, shown): (EntityId, Option<Day>),
(day, limit): (Day, usize),
) -> Result<Vec<Links>, NodeError>
where
NodeError: From<S::Error>,
{
let entity = state.canonical(entity)?;
let mut linking: BTreeMap<FieldName, BTreeSet<EntityId>> = BTreeMap::new();
let mut checked: BTreeSet<(EntityId, FieldName)> = BTreeSet::new();
for statement in state.referrers(entity)? {
let holder = state.canonical(statement.entity)?;
if !checked.insert((holder, statement.field.clone())) || !may_link(state, holder, entity)? {
continue;
}
let counts = if let Some(day) = shown {
let (shown, _) = resolve(state, types, languages, holder, &statement.field, day)?;
refers_to(state, &shown, entity)?
} else {
let definition = types.field(&statement.field);
let (Resolution::Values(shown) | Resolution::Competing(shown)) =
state.resolve(holder, &statement.field, definition.as_ref())?;
refers_to(state, &shown, entity)?
};
if counts {
linking
.entry(statement.field.clone())
.or_default()
.insert(holder);
}
}
let mut links = Vec::new();
for (field, holders) in linking {
let definition = types.field(&field);
let role = definition.as_ref().is_some_and(FieldDef::is_role);
let mut entities = Vec::new();
for id in &holders {
entities.push(Linking {
id: *id,
name: display_name(state, types, languages, *id)?,
types: Vec::new(),
participants: Vec::new(),
});
}
entities.sort_by_cached_key(|linking| by_name(linking.name.as_deref(), linking.id));
entities.truncate(limit);
for linking in &mut entities {
linking.types = state.types(linking.id)?.into_iter().collect();
if role {
linking.participants =
participants(state, types, languages, linking.id, &field, day)?;
}
}
links.push(Links {
reverse: definition.and_then(|field| field.reverse().cloned()),
field,
role,
count: holders.len(),
entities,
});
}
Ok(links)
}