1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
//! Observed row/name records and retryable pending undo.
use super::*;
impl<T, S, L> GenericTransactionsDecorator<T, S, L>
where
T: LinkReference,
S: LinksStorage<T>,
L: TransitionLogStore,
{
/// Writes one transition per link a single logical write touched.
///
/// A resolved write is not necessarily a single-link change: the
/// upstream uniqueness and usages decorators merge duplicates and
/// cascade through usages, so one `update`/`delete` call can rewrite
/// or remove several links. Each of them needs its own transition,
/// otherwise a rollback (or a version-control branch switch, which
/// replays the same transitions) cannot restore the links the
/// cascade touched.
///
/// The kind is derived from the observed pair rather than taken from
/// the outer operation, because a cascade can delete a link during an
/// `update` — recording that as an `Update` would make the revert a
/// no-op, since the link no longer exists to be updated back.
pub(super) fn record_observed_transitions(
&mut self,
observed: &[ObservedChange<T>],
owns: bool,
names_before: Option<&std::collections::BTreeMap<T, String>>,
) -> Result<(), LinkError> {
let zero = T::from_byte(0);
let changes = observed.iter().map(|(_, before, after)| {
let kind = match (before.index != zero, after.index != zero) {
(false, true) => TransitionKind::Create,
(true, false) => TransitionKind::Delete,
_ => TransitionKind::Update,
};
(kind, *before, *after)
});
self.record_transitions(changes, owns, names_before)
}
pub(super) fn record_transition(
&mut self,
kind: TransitionKind,
before: GenericDoubletLink<T>,
after: GenericDoubletLink<T>,
owns: bool,
names_before: Option<&std::collections::BTreeMap<T, String>>,
) -> Result<(), LinkError> {
self.record_transitions(std::iter::once((kind, before, after)), owns, names_before)
}
pub(super) fn record_transitions(
&mut self,
changes: impl ExactSizeIterator<Item = TransitionChange<T>>,
owns: bool,
names_before: Option<&std::collections::BTreeMap<T, String>>,
) -> Result<(), LinkError> {
// Names may be changed by an inner decorator during a row operation.
// Capture its actual result rather than predicting that every update
// preserves the old name. Keep all observed undo even if this read fails.
let captured = if names_before.is_some() {
self.inner
.capture_names()
.and_then(|names| {
names.ok_or_else(|| {
LinkError::StorageError(
"Named storage lost its name-capture capability.".into(),
)
})
})
.map(Some)
} else {
Ok(None)
};
let (names_after, capture_error) = match captured {
Ok(names) => (names, None),
Err(error) => (None, Some(error)),
};
let records = changes.map(|(kind, before, after)| {
let index = if after.index != T::from_byte(0) {
after.index
} else {
before.index
};
let old_name = names_before.and_then(|names| names.get(&index)).cloned();
let new_name = match &names_after {
Some(names) => names.get(&index).cloned(),
// A failed capture permits undo only; fence the owner below.
None if kind != TransitionKind::Delete => old_name.clone(),
None => None,
};
let names = if old_name.is_some() || new_name.is_some() {
vec![NameChange {
index,
before: old_name,
after: new_name,
}]
} else {
Vec::new()
};
JournalRecord {
transition: GenericTransition {
transaction_id: 0,
sequence: 0,
timestamp_ms: 0,
kind,
before,
after,
},
name_only: false,
names,
}
});
// An inner name reassignment can evict an owner without a row callback.
// Prepare that undo in the SAME batch, before the first fallible append.
if let (Some(before), Some(after)) = (names_before, &names_after) {
let mut records = records.collect::<Vec<_>>();
let observed = records
.iter()
.map(|record| {
if record.after.index != T::from_byte(0) {
record.after.index
} else {
record.before.index
}
})
.collect::<std::collections::BTreeSet<_>>();
let names = before
.keys()
.chain(after.keys())
.copied()
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
.filter(|index| !observed.contains(index))
.filter_map(|index| {
let old = before.get(&index).cloned();
let new = after.get(&index).cloned();
(old != new).then_some(NameChange {
index,
before: old,
after: new,
})
})
.collect::<Vec<_>>();
if !names.is_empty() {
records.push(JournalRecord {
transition: GenericTransition {
transaction_id: 0,
sequence: 0,
timestamp_ms: 0,
kind: TransitionKind::Update,
before: GenericDoubletLink::empty(),
after: GenericDoubletLink::empty(),
},
name_only: true,
names,
});
}
self.record_records(records.into_iter(), owns)?;
} else {
// Keep the unnamed adapter's iterator path without a second batch.
self.record_records(records, owns)?;
}
if let Some(error) = capture_error {
self.current
.as_mut()
.expect("open transaction")
.rollback_only = true;
if owns {
self.rollback()?;
}
return Err(error);
}
Ok(())
}
pub(super) fn record_records(
&mut self,
records: impl ExactSizeIterator<Item = JournalRecord<T>>,
owns: bool,
) -> Result<(), LinkError> {
let transaction_id = self.current.as_ref().map(|tx| tx.id).ok_or_else(|| {
LinkError::Transaction(
"internal: missing open transaction while recording transition".to_string(),
)
})?;
let exhausted = records.len() as u128 > (i64::MAX - self.sequence_counter) as u128;
let mut prepared = Vec::with_capacity(records.len());
for mut transition in records {
let sequence = if exhausted {
0
} else {
self.sequence_counter += 1;
self.sequence_counter
};
transition.transition.transaction_id = transaction_id;
transition.transition.sequence = sequence;
transition.transition.timestamp_ms = now_unix_ms();
self.current
.as_mut()
.expect("open transaction")
.transitions
.push(transition.clone());
if !exhausted {
self.log.push(transition.clone());
}
prepared.push(transition);
}
if exhausted {
// Keep the entire unnumbered undo batch only in pending memory.
// It must never become invalid serialized journal/history entries.
self.current
.as_mut()
.expect("open transaction")
.rollback_only = true;
if owns {
self.rollback()?;
}
return Err(LinkError::Transaction(
"Transaction sequence space is exhausted.".into(),
));
}
self.append_transitions(&prepared, owns)
}
pub(super) fn append_transitions(
&mut self,
transitions: &[JournalRecord<T>],
owns: bool,
) -> Result<(), LinkError> {
// Save every undo record before the first fallible journal write.
for transition in transitions {
if let Err(error) = self.write_transition_to_log(transition) {
self.current
.as_mut()
.expect("open transaction")
.rollback_only = true;
if owns {
self.rollback()?;
}
return Err(error);
}
if self.trace {
crate::diagnostics::stderr!(
"[Transactions] Recorded {:?} seq={} tx={:032x}: ({},{},{}) -> ({},{},{}).",
transition.kind,
transition.sequence,
transition.transaction_id,
transition.before.index,
transition.before.source,
transition.before.target,
transition.after.index,
transition.after.source,
transition.after.target,
);
}
}
Ok(())
}
pub(super) fn write_transition_to_log(
&mut self,
transition: &JournalRecord<T>,
) -> Result<(), LinkError> {
self.log_store.append_log_entry(&format!(
"{TRANSITION_NAME_PREFIX}{}",
transition.serialize()
))
}
}