Debian Codegraph @

src/main/org/h2/mvstore/tx/TxDecisionMaker.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.mvstore.tx;
7
8 import java.util.function.Function;
9 import org.h2.mvstore.DataUtils;
10 import org.h2.mvstore.MVMap;
11 import org.h2.mvstore.MVMap.Decision;
12 import org.h2.mvstore.type.DataType;
13 import org.h2.value.VersionedValue;
14
15 /**
16 * Class TxDecisionMaker is a base implementation of MVMap.DecisionMaker
17 * to be used for TransactionMap modification.
18 *
19 * @author <a href='mailto:[email protected]'>Andrei Tokar</a>
20 */
21 class TxDecisionMaker<K,V> extends MVMap.DecisionMaker<VersionedValue<V>> {
22 /**
23 * Map to decide upon
24 */
25 private final int mapId;
26
27 /**
28 * Key for the map entry to decide upon
29 */
30 protected K key;
31
32 /**
33 * Value for the map entry
34 */
35 private V value;
36
37 /**
38 * Transaction we are operating within
39 */
40 private final Transaction transaction;
41
42 /**
43 * Id for the undo log entry created for this modification
44 */
45 private long undoKey;
46
47 /**
48 * Id of the last operation, we decided to
49 * {@link org.h2.mvstore.MVMap.Decision#REPEAT}.
50 */
51 private long lastOperationId;
52
53 private Transaction blockingTransaction;
54 private MVMap.Decision decision;
55 private V lastValue;
56
57 TxDecisionMaker(int mapId, Transaction transaction) {
58 this.mapId = mapId;
59 this.transaction = transaction;
60 }
61
62 void initialize(K key, V value) {
63 this.key = key;
64 this.value = value;
65 decision = null;
66 reset();
67 }
68
69 @Override
70 public MVMap.Decision decide(VersionedValue<V> existingValue, VersionedValue<V> providedValue) {
71 assert decision == null;
72 long id;
73 int blockingId;
74 // if map does not have that entry yet
75 if (existingValue == null ||
76 // or entry is a committed one
77 (id = existingValue.getOperationId()) == 0 ||
78 // or it came from the same transaction
79 isThisTransaction(blockingId = TransactionStore.getTransactionId(id))) {
80 logAndDecideToPut(existingValue, existingValue == null ? null : existingValue.getCommittedValue());
81 } else if (isCommitted(blockingId)) {
82 // Condition above means that entry belongs to a committing transaction.
83 // We assume that we are looking at the final value for this transaction,
84 // and if it's not the case, then it will fail later,
85 // because a tree root has definitely been changed.
86 V currentValue = existingValue.getCurrentValue();
87 logAndDecideToPut(currentValue == null ? null : VersionedValueCommitted.getInstance(currentValue),
88 currentValue);
89 } else if (getBlockingTransaction() != null) {
90 // this entry comes from a different transaction, and this
91 // transaction is not committed yet
92 // should wait on blockingTransaction that was determined earlier
93 lastValue = existingValue.getCurrentValue();
94 decision = MVMap.Decision.ABORT;
95 } else if (isRepeatedOperation(id)) {
96 // There is no transaction with that id, and we've tried it just
97 // before, but map root has not changed (which must be the case if
98 // we just missed a closed transaction), therefore we came back here
99 // again.
100 // Now we assume it's a leftover after unclean shutdown (map update
101 // was written but not undo log), and will effectively roll it back
102 // (just assume committed value and overwrite).
103 V committedValue = existingValue.getCommittedValue();
104 logAndDecideToPut(committedValue == null ? null : VersionedValueCommitted.getInstance(committedValue),
105 committedValue);
106 } else {
107 // transaction has been committed/rolled back and is closed by now, so
108 // we can retry immediately and either that entry become committed
109 // or we'll hit case above
110 decision = MVMap.Decision.REPEAT;
111 }
112 return decision;
113 }
114
115 @Override
116 public final void reset() {
117 if (decision != MVMap.Decision.REPEAT) {
118 lastOperationId = 0;
119 if (decision == MVMap.Decision.PUT) {
120 // positive decision has been made already and undo record created,
121 // but map was updated afterwards and undo record deletion required
122 transaction.logUndo();
123 }
124 }
125 blockingTransaction = null;
126 decision = null;
127 lastValue = null;
128 }
129
130 @SuppressWarnings("unchecked")
131 @Override
132 // always return value (ignores existingValue)
133 public <T extends VersionedValue<V>> T selectValue(T existingValue, T providedValue) {
134 return (T) VersionedValueUncommitted.getInstance(undoKey, getNewValue(existingValue), lastValue);
135 }
136
137 /**
138 * Get the new value.
139 * This implementation always return the current value (ignores the parameter).
140 *
141 * @param existingValue the parameter value
142 * @return the current value.
143 */
144 V getNewValue(VersionedValue<V> existingValue) {
145 return value;
146 }
147
148 /**
149 * Create undo log entry and record for future references
150 * {@link org.h2.mvstore.MVMap.Decision#PUT} decision along with last known
151 * committed value
152 *
153 * @param valueToLog previous value to be logged
154 * @param lastValue last known committed value
155 * @return {@link org.h2.mvstore.MVMap.Decision#PUT}
156 */
157 MVMap.Decision logAndDecideToPut(VersionedValue<V> valueToLog, V lastValue) {
158 undoKey = transaction.log(new Record<>(mapId, key, valueToLog));
159 this.lastValue = lastValue;
160 return setDecision(MVMap.Decision.PUT);
161 }
162
163 final MVMap.Decision decideToAbort(V lastValue) {
164 this.lastValue = lastValue;
165 return setDecision(Decision.ABORT);
166 }
167
168 final boolean allowNonRepeatableRead() {
169 return transaction.allowNonRepeatableRead();
170 }
171
172 final MVMap.Decision getDecision() {
173 return decision;
174 }
175
176 final Transaction getBlockingTransaction() {
177 return blockingTransaction;
178 }
179
180 final V getLastValue() {
181 return lastValue;
182 }
183
184 /**
185 * Check whether specified transaction id belongs to "current" transaction
186 * (transaction we are acting within).
187 *
188 * @param transactionId to check
189 * @return true it it is "current" transaction's id, false otherwise
190 */
191 final boolean isThisTransaction(int transactionId) {
192 return transactionId == transaction.transactionId;
193 }
194
195 /**
196 * Determine whether specified id corresponds to a logically committed transaction.
197 * In case of pending transaction, reference to actual Transaction object (if any)
198 * is preserved for future use.
199 *
200 * @param transactionId to use
201 * @return true if transaction should be considered as committed, false otherwise
202 */
203 final boolean isCommitted(int transactionId) {
204 Transaction blockingTx;
205 boolean result;
206 TransactionStore store = transaction.store;
207 do {
208 blockingTx = store.getTransaction(transactionId);
209 result = store.committingTransactions.get().get(transactionId);
210 } while (blockingTx != store.getTransaction(transactionId));
211
212 if (!result) {
213 blockingTransaction = blockingTx;
214 }
215 return result;
216 }
217
218 /**
219 * Store operation id provided, but before that, compare it against last stored one.
220 * This is to prevent an infinite loop in case of uncommitted "leftover" entry
221 * (one without a corresponding undo log entry, most likely as a result of unclean shutdown).
222 *
223 * @param id
224 * for the operation we decided to
225 * {@link org.h2.mvstore.MVMap.Decision#REPEAT}
226 * @return true if the same as last operation id, false otherwise
227 */
228 final boolean isRepeatedOperation(long id) {
229 if (id == lastOperationId) {
230 return true;
231 }
232 lastOperationId = id;
233 return false;
234 }
235
236 /**
237 * Record for future references specified value as a decision that has been made.
238 *
239 * @param decision made
240 * @return argument provided
241 */
242 final MVMap.Decision setDecision(MVMap.Decision decision) {
243 return this.decision = decision;
244 }
245
246 @Override
247 public final String toString() {
248 return "txdm " + transaction.transactionId;
249 }
250
251
252
253 public static final class PutIfAbsentDecisionMaker<K,V> extends TxDecisionMaker<K,V> {
254 private final Function<K, V> oldValueSupplier;
255
256 PutIfAbsentDecisionMaker(int mapId, Transaction transaction, Function<K, V> oldValueSupplier) {
257 super(mapId, transaction);
258 this.oldValueSupplier = oldValueSupplier;
259 }
260
261 @Override
262 public MVMap.Decision decide(VersionedValue<V> existingValue, VersionedValue<V> providedValue) {
263 assert getDecision() == null;
264 int blockingId;
265 // if map does not have that entry yet
266 if (existingValue == null) {
267 V snapshotValue = getValueInSnapshot();
268 if (snapshotValue != null) {
269 // value exists in a snapshot but not in current map, therefore
270 // it was removed and committed by another transaction
271 return decideToAbort(snapshotValue);
272 }
273 return logAndDecideToPut(null, null);
274 } else {
275 long id = existingValue.getOperationId();
276 if (id == 0 // entry is a committed one
277 // or it came from the same transaction
278 || isThisTransaction(blockingId = TransactionStore.getTransactionId(id))) {
279 if(existingValue.getCurrentValue() != null) {
280 return decideToAbort(existingValue.getCurrentValue());
281 }
282 if (id == 0) {
283 V snapshotValue = getValueInSnapshot();
284 if (snapshotValue != null) {
285 return decideToAbort(snapshotValue);
286 }
287 }
288 return logAndDecideToPut(existingValue, existingValue.getCommittedValue());
289 } else if (isCommitted(blockingId)) {
290 // entry belongs to a committing transaction
291 // and therefore will be committed soon
292 if(existingValue.getCurrentValue() != null) {
293 return decideToAbort(existingValue.getCurrentValue());
294 }
295 // even if that commit will result in entry removal
296 // current operation should fail within repeatable read transaction
297 // if initial snapshot carries some value
298 V snapshotValue = getValueInSnapshot();
299 if (snapshotValue != null) {
300 return decideToAbort(snapshotValue);
301 }
302 return logAndDecideToPut(null, null);
303 } else if (getBlockingTransaction() != null) {
304 // this entry comes from a different transaction, and this
305 // transaction is not committed yet
306 // should wait on blockingTransaction that was determined
307 // earlier and then try again
308 return decideToAbort(existingValue.getCurrentValue());
309 } else if (isRepeatedOperation(id)) {
310 // There is no transaction with that id, and we've tried it
311 // just before, but map root has not changed (which must be
312 // the case if we just missed a closed transaction),
313 // therefore we came back here again.
314 // Now we assume it's a leftover after unclean shutdown (map
315 // update was written but not undo log), and will
316 // effectively roll it back (just assume committed value and
317 // overwrite).
318 V committedValue = existingValue.getCommittedValue();
319 if (committedValue != null) {
320 return decideToAbort(committedValue);
321 }
322 return logAndDecideToPut(null, null);
323 } else {
324 // transaction has been committed/rolled back and is closed
325 // by now, so we can retry immediately and either that entry
326 // become committed or we'll hit case above
327 return setDecision(MVMap.Decision.REPEAT);
328 }
329 }
330 }
331
332 private V getValueInSnapshot() {
333 return allowNonRepeatableRead() ? null : oldValueSupplier.apply(key);
334 }
335 }
336
337
338 public static class LockDecisionMaker<K,V> extends TxDecisionMaker<K,V> {
339
340 LockDecisionMaker(int mapId, Transaction transaction) {
341 super(mapId, transaction);
342 }
343
344 @Override
345 public MVMap.Decision decide(VersionedValue<V> existingValue, VersionedValue<V> providedValue) {
346 MVMap.Decision decision = super.decide(existingValue, providedValue);
347 if (existingValue == null) {
348 assert decision == MVMap.Decision.PUT;
349 decision = setDecision(MVMap.Decision.REMOVE);
350 }
351 return decision;
352 }
353
354 @Override
355 V getNewValue(VersionedValue<V> existingValue) {
356 return existingValue == null ? null : existingValue.getCurrentValue();
357 }
358 }
359
360 public static final class RepeatableReadLockDecisionMaker<K,V> extends LockDecisionMaker<K,V> {
361
362 private final DataType<VersionedValue<V>> valueType;
363
364 private final Function<K,V> snapshotValueSupplier;
365
366 RepeatableReadLockDecisionMaker(int mapId, Transaction transaction,
367 DataType<VersionedValue<V>> valueType, Function<K,V> snapshotValueSupplier) {
368 super(mapId, transaction);
369 this.valueType = valueType;
370 this.snapshotValueSupplier = snapshotValueSupplier;
371 }
372
373 @Override
374 Decision logAndDecideToPut(VersionedValue<V> valueToLog, V value) {
375 V snapshotValue = snapshotValueSupplier.apply(key);
376 if (snapshotValue != null && (valueToLog == null
377 || valueType.compare(VersionedValueCommitted.getInstance(snapshotValue), valueToLog) != 0)) {
378 throw DataUtils.newMVStoreException(DataUtils.ERROR_TRANSACTIONS_DEADLOCK, "");
379 }
380 return super.logAndDecideToPut(valueToLog, value);
381 }
382 }
383 }