Refactor ModificationApplyOperation
[yangtools.git] / data / yang-data-tree-ri / src / main / java / org / opendaylight / yangtools / yang / data / tree / impl / ModifiedNode.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.data.tree.impl;
9
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.MoreObjects.ToStringHelper;
15 import java.util.Collection;
16 import java.util.Map;
17 import java.util.Objects;
18 import java.util.Optional;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
22 import org.opendaylight.yangtools.yang.data.api.schema.DistinctNodeContainer;
23 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNode;
25 import org.opendaylight.yangtools.yang.data.tree.api.ModificationType;
26 import org.opendaylight.yangtools.yang.data.tree.impl.node.TreeNode;
27 import org.opendaylight.yangtools.yang.data.tree.impl.node.Version;
28
29 /**
30  * Node Modification Node and Tree.
31  *
32  * <p>
33  * Tree which structurally resembles data tree and captures client modifications to the data store tree. This tree is
34  * lazily created and populated via {@link #modifyChild(PathArgument, ModificationApplyOperation, Version)} and
35  * {@link TreeNode} which represents original state as tracked by {@link #getOriginal()}.
36  *
37  * <p>
38  * The contract is that the state information exposed here preserves the temporal ordering of whatever modifications
39  * were executed. A child's effects pertain to data node as modified by its ancestors. This means that in order to
40  * reconstruct the effective data node presentation, it is sufficient to perform a depth-first pre-order traversal of
41  * the tree.
42  */
43 final class ModifiedNode extends NodeModification implements StoreTreeNode<ModifiedNode> {
44     private final Map<PathArgument, ModifiedNode> children;
45     private final @Nullable TreeNode original;
46     private final @NonNull PathArgument identifier;
47
48     private LogicalOperation operation = LogicalOperation.NONE;
49     private Optional<TreeNode> snapshotCache;
50     private NormalizedNode value;
51     private ModificationType modType;
52
53     // Alternative history introduced in WRITE nodes. Instantiated when we touch any child underneath such a node.
54     private TreeNode writtenOriginal;
55
56     // Internal cache for TreeNodes created as part of validation
57     private ModificationApplyOperation validatedOp;
58     private @Nullable TreeNode validatedCurrent;
59     private ValidatedTreeNode validatedNode;
60
61     private ModifiedNode(final PathArgument identifier, final @Nullable TreeNode original,
62             final ChildTrackingPolicy childPolicy) {
63         this.identifier = requireNonNull(identifier);
64         this.original = original;
65         children = childPolicy.createMap();
66     }
67
68     @Override
69     public PathArgument getIdentifier() {
70         return identifier;
71     }
72
73     @Override
74     LogicalOperation getOperation() {
75         return operation;
76     }
77
78     @Override
79     TreeNode original() {
80         return original;
81     }
82
83     /**
84      * Return the value which was written to this node. The returned object is only valid for
85      * {@link LogicalOperation#MERGE} and {@link LogicalOperation#WRITE}.
86      * operations. It should only be consulted when this modification is going to end up being
87      * {@link ModificationType#WRITE}.
88      *
89      * @return Currently-written value
90      */
91     @NonNull NormalizedNode getWrittenValue() {
92         return verifyNotNull(value);
93     }
94
95     /**
96      * Returns child modification if child was modified.
97      *
98      * @return Child modification if direct child or it's subtree was modified.
99      */
100     @Override
101     public ModifiedNode childByArg(final PathArgument arg) {
102         return children.get(arg);
103     }
104
105     private @Nullable TreeNode metadataFromSnapshot(final @NonNull PathArgument child) {
106         final var local = original;
107         return local != null ? local.childByArg(child) : null;
108     }
109
110     private @Nullable TreeNode metadataFromData(final @NonNull PathArgument child, final Version modVersion) {
111         if (writtenOriginal == null) {
112             // Lazy instantiation, as we do not want do this for all writes. We are using the modification's version
113             // here, as that version is what the SchemaAwareApplyOperation will see when dealing with the resulting
114             // modifications.
115             writtenOriginal = TreeNode.of(value, modVersion);
116         }
117
118         return writtenOriginal.childByArg(child);
119     }
120
121     /**
122      * Determine the base tree node we are going to apply the operation to. This is not entirely trivial because
123      * both DELETE and WRITE operations unconditionally detach their descendants from the original snapshot, so we need
124      * to take the current node's operation into account.
125      *
126      * @param child Child we are looking to modify
127      * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
128      * @return Before-image tree node as observed by that child.
129      */
130     private @Nullable TreeNode originalMetadata(final @NonNull PathArgument child, final Version modVersion) {
131         return switch (operation) {
132             case DELETE ->
133                 // DELETE implies non-presence
134                 null;
135             case NONE, TOUCH, MERGE -> metadataFromSnapshot(child);
136             case WRITE ->
137                 // WRITE implies presence based on written data
138                 metadataFromData(child, modVersion);
139         };
140     }
141
142     /**
143      * Returns child modification if child was modified, creates {@link ModifiedNode}
144      * for child otherwise. If this node's {@link ModificationType} is {@link ModificationType#UNMODIFIED}
145      * changes modification type to {@link ModificationType#SUBTREE_MODIFIED}.
146      *
147      * @param child child identifier, may not be null
148      * @param childOper Child operation
149      * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
150      * @return {@link ModifiedNode} for specified child, with {@link #getOriginal()}
151      *         containing child metadata if child was present in original data.
152      */
153     ModifiedNode modifyChild(final @NonNull PathArgument child, final @NonNull ModificationApplyOperation childOper,
154             final @NonNull Version modVersion) {
155         clearSnapshot();
156         if (operation == LogicalOperation.NONE) {
157             updateOperationType(LogicalOperation.TOUCH);
158         }
159         final var potential = children.get(child);
160         if (potential != null) {
161             return potential;
162         }
163
164         final var newlyCreated = new ModifiedNode(child, originalMetadata(child, modVersion),
165             childOper.getChildPolicy());
166         if (operation == LogicalOperation.MERGE && value != null) {
167             /*
168              * We are attempting to modify a previously-unmodified part of a MERGE node. If the
169              * value contains this component, we need to materialize it as a MERGE modification.
170              */
171             @SuppressWarnings({ "rawtypes", "unchecked" })
172             final var childData = ((DistinctNodeContainer) value).childByArg(child);
173             if (childData != null) {
174                 childOper.mergeIntoModifiedNode(newlyCreated, childData, modVersion);
175             }
176         }
177
178         children.put(child, newlyCreated);
179         return newlyCreated;
180     }
181
182     /**
183      * Returns all recorded direct child modifications.
184      *
185      * @return all recorded direct child modifications
186      */
187     @Override
188     Collection<ModifiedNode> getChildren() {
189         return children.values();
190     }
191
192     @Override
193     boolean isEmpty() {
194         return children.isEmpty();
195     }
196
197     /**
198      * Records a delete for associated node.
199      */
200     void delete() {
201         final LogicalOperation newType = switch (operation) {
202             case DELETE, NONE ->
203                 // We need to record this delete.
204                 LogicalOperation.DELETE;
205             case MERGE ->
206                 // In case of merge - delete needs to be recored and must not to be changed into NONE, because lazy
207                 // expansion of parent MERGE node would reintroduce it again.
208                 LogicalOperation.DELETE;
209             case TOUCH, WRITE ->
210                 // We are canceling a previous modification. This is a bit tricky, as the original write may have just
211                 // introduced the data, or it may have modified it.
212                 //
213                 // As documented in BUG-2470, a delete of data introduced in this transaction needs to be turned into
214                 // a no-op.
215                 original != null ? LogicalOperation.DELETE : LogicalOperation.NONE;
216         };
217
218         clearSnapshot();
219         children.clear();
220         value = null;
221         updateOperationType(newType);
222     }
223
224     /**
225      * Records a write for associated node.
226      *
227      * @param newValue new value
228      */
229     void write(final NormalizedNode newValue) {
230         updateValue(LogicalOperation.WRITE, newValue);
231         children.clear();
232     }
233
234     /**
235      * Seal the modification node and prune any children which has not been modified.
236      *
237      * @param schema associated apply operation
238      * @param version target version
239      */
240     void seal(final ModificationApplyOperation schema, final Version version) {
241         clearSnapshot();
242         writtenOriginal = null;
243
244         switch (operation) {
245             case TOUCH -> {
246                 // A TOUCH node without any children is a no-op
247                 if (children.isEmpty()) {
248                     updateOperationType(LogicalOperation.NONE);
249                 }
250             }
251             case WRITE -> {
252                 // A WRITE can collapse all of its children
253                 if (!children.isEmpty()) {
254                     value = schema.apply(this, original(), version).map(TreeNode::getData).orElse(null);
255                     children.clear();
256                 }
257
258                 if (value == null) {
259                     // The write has ended up being empty, such as a write of an empty list.
260                     updateOperationType(LogicalOperation.DELETE);
261                 } else {
262                     schema.fullVerifyStructure(value);
263                 }
264             }
265             default -> {
266                 // No-op
267             }
268         }
269     }
270
271     private void clearSnapshot() {
272         snapshotCache = null;
273     }
274
275     Optional<TreeNode> getSnapshot() {
276         return snapshotCache;
277     }
278
279     Optional<TreeNode> setSnapshot(final Optional<TreeNode> snapshot) {
280         snapshotCache = requireNonNull(snapshot);
281         return snapshot;
282     }
283
284     void updateOperationType(final LogicalOperation type) {
285         operation = type;
286         modType = null;
287
288         // Make sure we do not reuse previously-instantiated data-derived metadata
289         writtenOriginal = null;
290         clearSnapshot();
291     }
292
293     @Override
294     public String toString() {
295         final ToStringHelper helper = MoreObjects.toStringHelper(this).omitNullValues()
296                 .add("identifier", identifier).add("operation", operation).add("modificationType", modType);
297         if (!children.isEmpty()) {
298             helper.add("childModification", children);
299         }
300         return helper.toString();
301     }
302
303     void resolveModificationType(final @NonNull ModificationType type) {
304         modType = type;
305     }
306
307     /**
308      * Update this node's value and operation type without disturbing any of its child modifications.
309      *
310      * @param type New operation type
311      * @param newValue New node value
312      */
313     void updateValue(final LogicalOperation type, final NormalizedNode newValue) {
314         value = requireNonNull(newValue);
315         updateOperationType(type);
316     }
317
318     /**
319      * Return the physical modification done to data. May return null if the
320      * operation has not been applied to the underlying tree. This is different
321      * from the logical operation in that it can actually be a no-op if the
322      * operation has no side-effects (like an empty merge on a container).
323      *
324      * @return Modification type.
325      */
326     ModificationType getModificationType() {
327         return modType;
328     }
329
330     public static ModifiedNode createUnmodified(final TreeNode metadataTree, final ChildTrackingPolicy childPolicy) {
331         return new ModifiedNode(metadataTree.getIdentifier(), requireNonNull(metadataTree), childPolicy);
332     }
333
334     void setValidatedNode(final ModificationApplyOperation op, final @Nullable TreeNode currentMeta,
335             final Optional<? extends TreeNode> node) {
336         validatedOp = requireNonNull(op);
337         validatedCurrent = currentMeta;
338         validatedNode = new ValidatedTreeNode(node);
339     }
340
341     /**
342      * Acquire pre-validated node assuming a previous operation and node. This is a counterpart to
343      * {@link #setValidatedNode(ModificationApplyOperation, Optional, Optional)}.
344      *
345      * @param op Currently-executing operation
346      * @param storeMeta Currently-used tree node
347      * @return {@code null} if there is a mismatch with previously-validated node (if present) or the result of previous
348      *         validation.
349      */
350     @Nullable ValidatedTreeNode validatedNode(final ModificationApplyOperation op, final @Nullable TreeNode storeMeta) {
351         return op.equals(validatedOp) && Objects.equals(storeMeta, validatedCurrent) ? validatedNode : null;
352     }
353 }