1use nibkeep_base::{EntityId, SpaceId, StatementId};
6use std::collections::BTreeMap;
7
8use nibkeep_model::storage::Statements as _;
9use nibkeep_model::{FieldName, Qualifiers, Value, fields};
10use nibkeep_time::{Day, Edtf, Timestamp};
11
12use super::entities::{EntityView, display_name, entity_view};
13use super::links::{Links, links_to};
14use super::{Author, Library};
15use crate::NodeError;
16
17#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct History {
20 pub id: EntityId,
22 pub name: Option<String>,
24 pub fields: Vec<FieldHistory>,
26}
27
28#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct FieldHistory {
31 pub field: FieldName,
33 pub values: Vec<PastValue>,
35}
36
37#[derive(Clone, Debug, PartialEq, Eq)]
39pub struct PastValue {
40 pub statement: StatementId,
42 pub value: Value,
44 pub valid_time: Option<Edtf>,
46 pub language: Option<String>,
48 pub recorded: Timestamp,
50 pub restated: Option<Timestamp>,
52 pub replaced: Option<Timestamp>,
54 pub author: Option<Author>,
56 pub carried: Option<Carried>,
59}
60
61#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct Carried {
67 pub from: Option<SpaceId>,
69 pub from_name: Option<String>,
71 pub author: Option<Author>,
74 pub recorded: Option<u64>,
76 pub replaced: Option<u64>,
78}
79
80#[derive(Default)]
83struct Noted {
84 authors: BTreeMap<String, Option<Author>>,
85 spaces: BTreeMap<SpaceId, Option<String>>,
86}
87
88impl Library {
89 pub fn history(
99 &self,
100 space: SpaceId,
101 entity: EntityId,
102 field: Option<&FieldName>,
103 ) -> Result<Option<History>, NodeError> {
104 let open = self.space(space)?;
105 open.stored.reading(|stored| {
106 let log = stored.log();
107 let state = log.state();
108 let storage = state.storage();
109 let entity = state.canonical(entity)?;
110 if state.fields(entity)?.is_empty() && state.merged(entity)?.len() <= 1 {
111 let none = storage
112 .of_entity(entity)?
113 .iter()
114 .all(|(_, ids)| ids.is_empty());
115 if none {
116 return Ok(None);
117 }
118 }
119 let mut authors: BTreeMap<String, Option<Author>> = BTreeMap::new();
121 let mut noted = Noted::default();
123 let mut by_field: BTreeMap<FieldName, Vec<PastValue>> = BTreeMap::new();
124 for member in state.merged(entity)? {
125 for (name, ids) in storage.of_entity(member)? {
126 if field.is_some_and(|wanted| *wanted != name) {
127 continue;
128 }
129 for id in ids {
130 let Some(recorded) = storage.get(id)? else {
131 continue;
132 };
133 let author = match log.author_of(id)? {
134 Some(key) => {
135 let text = key.to_text();
136 if let Some(author) = authors.get(&text) {
137 author.clone()
138 } else {
139 let author = self.author_with_key(open, stored, &key)?;
140 authors.insert(text, author.clone());
141 author
142 }
143 }
144 None => None,
145 };
146 let statement = recorded.statement;
147 let carried =
148 self.carried(open, stored, &statement.qualifiers, &mut noted)?;
149 by_field.entry(name.clone()).or_default().push(PastValue {
150 statement: statement.id,
151 value: statement.value.clone(),
152 valid_time: statement.qualifiers.valid_time().cloned(),
153 language: statement.qualifiers.language().map(str::to_owned),
154 recorded: recorded.at,
155 restated: recorded.restated,
156 replaced: storage.superseded_at(id)?,
157 author,
158 carried,
159 });
160 }
161 }
162 }
163 let mut fields = Vec::new();
164 for (field, mut values) in by_field {
165 values.sort_by_key(|value| {
167 let noted = value.carried.as_ref().and_then(|carried| carried.recorded);
168 (
169 noted.unwrap_or_else(|| value.recorded.millis()),
170 value.recorded,
171 value.statement,
172 )
173 });
174 fields.push(FieldHistory { field, values });
175 }
176 Ok(Some(History {
177 id: entity,
178 name: display_name(state, &open.types, &self.languages, entity)?,
179 fields,
180 }))
181 })
182 }
183
184 fn carried(
187 &self,
188 open: &super::Space,
189 stored: &nibkeep_store::StoredLog,
190 qualifiers: &Qualifiers,
191 noted: &mut Noted,
192 ) -> Result<Option<Carried>, NodeError> {
193 let millis = |field: &FieldName| match qualifiers.get(field) {
194 Some(Value::Integer(millis)) => u64::try_from(*millis).ok(),
195 _ => None,
196 };
197 let from = qualifiers
198 .get(&fields::CARRIED_FROM)
199 .and_then(Value::as_text)
200 .and_then(|text| text.parse::<SpaceId>().ok());
201 let key = qualifiers
202 .get(&fields::CARRIED_BY)
203 .and_then(Value::as_text)
204 .and_then(nibkeep_crypto::VerifyingKey::from_text);
205 let (recorded, replaced) = (
206 millis(&fields::CARRIED_AT),
207 millis(&fields::CARRIED_REPLACED),
208 );
209 if from.is_none() && key.is_none() && recorded.is_none() && replaced.is_none() {
210 return Ok(None);
211 }
212 let mut author = None;
213 if let Some(key) = &key {
214 let text = key.to_text();
215 if let Some(known) = noted.authors.get(&text) {
216 author.clone_from(known);
217 } else {
218 author = self.author_with_key(open, stored, key)?;
219 if author.is_none() {
220 let personal = self.space(self.info.personal)?;
221 author = self.author_with_key(personal, &personal.stored, key)?;
222 }
223 noted.authors.insert(text, author.clone());
224 }
225 }
226 let from_name = match from {
227 Some(space) if self.spaces.contains_key(&space) => {
228 if let Some(name) = noted.spaces.get(&space) {
229 name.clone()
230 } else {
231 let name = self.space_name(space)?;
232 noted.spaces.insert(space, name.clone());
233 name
234 }
235 }
236 _ => None,
237 };
238 Ok(Some(Carried {
239 from,
240 from_name,
241 author,
242 recorded,
243 replaced,
244 }))
245 }
246
247 pub fn name_as_of(
254 &self,
255 space: SpaceId,
256 entity: EntityId,
257 millis: u64,
258 ) -> Result<Option<String>, NodeError> {
259 let open = self.space(space)?;
260 open.stored.reading(|stored| {
261 let state = stored.log().state_as_of(millis);
262 let entity = state.canonical(entity)?;
263 display_name(&state, &open.types, &self.languages, entity)
264 })
265 }
266
267 pub fn entity_as_of(
276 &self,
277 space: SpaceId,
278 entity: EntityId,
279 day: Day,
280 millis: u64,
281 ) -> Result<Option<EntityView>, NodeError> {
282 let open = self.space(space)?;
283 open.stored.reading(|stored| {
284 let state = stored.log().state_as_of(millis);
285 entity_view(&state, &open.types, &self.languages, entity, day)
286 })
287 }
288
289 pub fn links_to_as_of(
296 &self,
297 space: SpaceId,
298 entity: EntityId,
299 day: Day,
300 millis: u64,
301 limit: usize,
302 ) -> Result<Vec<Links>, NodeError> {
303 let open = self.space(space)?;
304 open.stored.reading(|stored| {
305 let state = stored.log().state_as_of(millis);
306 links_to(
307 &state,
308 &open.types,
309 &self.languages,
310 (entity, Some(day)),
311 (day, limit),
312 )
313 })
314 }
315}