Do not store Optional in ModifiedNode
[yangtools.git] / data / yang-data-tree-ri / src / main / java / org / opendaylight / yangtools / yang / data / tree / impl / AbstractNodeContainerModificationStrategy.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.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.base.MoreObjects.ToStringHelper;
14 import com.google.common.base.Verify;
15 import java.util.Collection;
16 import java.util.Optional;
17 import org.eclipse.jdt.annotation.NonNull;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
20 import org.opendaylight.yangtools.yang.data.api.schema.DistinctNodeContainer;
21 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
22 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
23 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
24 import org.opendaylight.yangtools.yang.data.tree.api.ConflictingModificationAppliedException;
25 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeConfiguration;
26 import org.opendaylight.yangtools.yang.data.tree.api.DataValidationFailedException;
27 import org.opendaylight.yangtools.yang.data.tree.api.ModificationType;
28 import org.opendaylight.yangtools.yang.data.tree.api.ModifiedNodeDoesNotExistException;
29 import org.opendaylight.yangtools.yang.data.tree.api.SchemaValidationFailedException;
30 import org.opendaylight.yangtools.yang.data.tree.api.TreeType;
31 import org.opendaylight.yangtools.yang.data.tree.impl.node.MutableTreeNode;
32 import org.opendaylight.yangtools.yang.data.tree.impl.node.TreeNode;
33 import org.opendaylight.yangtools.yang.data.tree.impl.node.Version;
34 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
35
36 abstract sealed class AbstractNodeContainerModificationStrategy<T extends DataSchemaNode>
37         extends SchemaAwareApplyOperation<T> {
38     abstract static sealed class Invisible<T extends DataSchemaNode>
39             extends AbstractNodeContainerModificationStrategy<T>
40             permits LeafSetModificationStrategy, MapModificationStrategy {
41         private final @NonNull SchemaAwareApplyOperation<T> entryStrategy;
42
43         Invisible(final NormalizedNodeContainerSupport<?, ?> support, final DataTreeConfiguration treeConfig,
44                 final SchemaAwareApplyOperation<T> entryStrategy) {
45             super(support, treeConfig);
46             this.entryStrategy = requireNonNull(entryStrategy);
47         }
48
49         @Override
50         final T getSchema() {
51             return entryStrategy.getSchema();
52         }
53
54         final @NonNull ModificationApplyOperation entryStrategy() {
55             return entryStrategy;
56         }
57
58         @Override
59         ToStringHelper addToStringAttributes(final ToStringHelper helper) {
60             return super.addToStringAttributes(helper).add("entry", entryStrategy);
61         }
62     }
63
64     abstract static sealed class Visible<T extends DataSchemaNode> extends AbstractNodeContainerModificationStrategy<T>
65             permits ChoiceModificationStrategy, DataNodeContainerModificationStrategy {
66         private final @NonNull T schema;
67
68         Visible(final NormalizedNodeContainerSupport<?, ?> support, final DataTreeConfiguration treeConfig,
69                 final T schema) {
70             super(support, treeConfig);
71             this.schema = requireNonNull(schema);
72         }
73
74         @Override
75         final T getSchema() {
76             return schema;
77         }
78
79         @Override
80         ToStringHelper addToStringAttributes(final ToStringHelper helper) {
81             return super.addToStringAttributes(helper).add("schema", schema);
82         }
83     }
84
85     /**
86      * Fake TreeNode version used in
87      * {@link #checkTouchApplicable(ModificationPath, NodeModification, Optional, Version)}
88      * It is okay to use a global constant, as the delegate will ignore it anyway.
89      */
90     private static final Version FAKE_VERSION = Version.initial();
91
92     private final NormalizedNodeContainerSupport<?, ?> support;
93     private final boolean verifyChildrenStructure;
94
95     AbstractNodeContainerModificationStrategy(final NormalizedNodeContainerSupport<?, ?> support,
96             final DataTreeConfiguration treeConfig) {
97         this.support = requireNonNull(support);
98         verifyChildrenStructure = treeConfig.getTreeType() == TreeType.CONFIGURATION;
99     }
100
101     @Override
102     protected final ChildTrackingPolicy getChildPolicy() {
103         return support.childPolicy;
104     }
105
106     @Override
107     final void verifyValue(final NormalizedNode writtenValue) {
108         final Class<?> nodeClass = support.requiredClass;
109         checkArgument(nodeClass.isInstance(writtenValue), "Node %s is not of type %s", writtenValue, nodeClass);
110         checkArgument(writtenValue instanceof NormalizedNodeContainer);
111     }
112
113     @Override
114     final void verifyValueChildren(final NormalizedNode writtenValue) {
115         final var container = (DistinctNodeContainer<?, ?>) writtenValue;
116         if (verifyChildrenStructure) {
117             for (var child : container.body()) {
118                 final var childOp = childByArg(child.name());
119                 if (childOp == null) {
120                     throw new SchemaValidationFailedException(String.format(
121                         "Node %s is not a valid child of %s according to the schema.",
122                         child.name(), container.name()));
123                 }
124                 childOp.fullVerifyStructure(child);
125             }
126
127             optionalVerifyValueChildren(container);
128         }
129         mandatoryVerifyValueChildren(container);
130     }
131
132     /**
133      * Perform additional verification on written value's child structure, like presence of mandatory children and
134      * exclusion. The default implementation does nothing and is not invoked for non-CONFIG data trees.
135      *
136      * @param writtenValue Effective written value
137      */
138     void optionalVerifyValueChildren(final DistinctNodeContainer<?, ?> writtenValue) {
139         // Defaults to no-op
140     }
141
142     /**
143      * Perform additional verification on written value's child structure, like presence of mandatory children.
144      * The default implementation does nothing.
145      *
146      * @param writtenValue Effective written value
147      */
148     void mandatoryVerifyValueChildren(final DistinctNodeContainer<?, ?> writtenValue) {
149         // Defaults to no-op
150     }
151
152     @Override
153     protected final void recursivelyVerifyStructure(final NormalizedNode value) {
154         final var container = (NormalizedNodeContainer<?>) value;
155         for (var child : container.body()) {
156             final var childOp = childByArg(child.name());
157             if (childOp == null) {
158                 throw new SchemaValidationFailedException(
159                     String.format("Node %s is not a valid child of %s according to the schema.",
160                         child.name(), container.name()));
161             }
162
163             childOp.recursivelyVerifyStructure(child);
164         }
165     }
166
167     @Override
168     protected TreeNode applyWrite(final ModifiedNode modification, final NormalizedNode newValue,
169             final Optional<? extends TreeNode> currentMeta, final Version version) {
170         final var newValueMeta = TreeNode.of(newValue, version);
171         if (modification.isEmpty()) {
172             return newValueMeta;
173         }
174
175         /*
176          * This is where things get interesting. The user has performed a write and then she applied some more
177          * modifications to it. So we need to make sense of that and apply the operations on top of the written value.
178          *
179          * We could have done it during the write, but this operation is potentially expensive, so we have left it out
180          * of the fast path.
181          *
182          * As it turns out, once we materialize the written data, we can share the code path with the subtree change. So
183          * let's create an unsealed TreeNode and run the common parts on it -- which end with the node being sealed.
184          *
185          * FIXME: this code needs to be moved out from the prepare() path and into the read() and seal() paths. Merging
186          *        of writes needs to be charged to the code which originated this, not to the code which is attempting
187          *        to make it visible.
188          */
189         final var mutable = newValueMeta.mutable();
190         mutable.setSubtreeVersion(version);
191
192         final var result = mutateChildren(mutable, support.createBuilder(newValue), version,
193             modification.getChildren());
194
195         // We are good to go except one detail: this is a single logical write, but
196         // we have a result TreeNode which has been forced to materialized, e.g. it
197         // is larger than it needs to be. Create a new TreeNode to host the data.
198         return TreeNode.of(result.getData(), version);
199     }
200
201     /**
202      * Applies write/remove diff operation for each modification child in modification subtree.
203      * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
204      *
205      * @param meta MutableTreeNode (IndexTreeNode)
206      * @param data DataBuilder
207      * @param nodeVersion Version of TreeNode
208      * @param modifications modification operations to apply
209      * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
210      */
211     @SuppressWarnings({ "rawtypes", "unchecked" })
212     private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
213             final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
214
215         for (final ModifiedNode mod : modifications) {
216             final PathArgument id = mod.getIdentifier();
217             final Optional<? extends TreeNode> cm = meta.findChildByArg(id);
218
219             final Optional<? extends TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
220             if (result.isPresent()) {
221                 final TreeNode tn = result.orElseThrow();
222                 meta.putChild(tn);
223                 data.addChild(tn.getData());
224             } else {
225                 meta.removeChild(id);
226                 data.removeChild(id);
227             }
228         }
229
230         meta.setData(data.build());
231         return meta.seal();
232     }
233
234     @Override
235     protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
236         /*
237          * The node which we are merging exists. We now need to expand any child operations implied by the value. Once
238          * we do that, ModifiedNode children will look like this node were a TOUCH and we will let applyTouch() do the
239          * heavy lifting of applying the children recursively (either through here or through applyWrite().
240          */
241         final NormalizedNode value = modification.getWrittenValue();
242
243         Verify.verify(value instanceof DistinctNodeContainer, "Attempted to merge non-container %s", value);
244         for (var c : ((DistinctNodeContainer<?, ?>) value).body()) {
245             final var id = c.name();
246             modification.modifyChild(id, resolveChildOperation(id), version);
247         }
248         return applyTouch(modification, currentMeta, version);
249     }
250
251     private void mergeChildrenIntoModification(final ModifiedNode modification,
252             final Collection<? extends NormalizedNode> children, final Version version) {
253         for (final NormalizedNode c : children) {
254             final ModificationApplyOperation childOp = resolveChildOperation(c.name());
255             final ModifiedNode childNode = modification.modifyChild(c.name(), childOp, version);
256             childOp.mergeIntoModifiedNode(childNode, c, version);
257         }
258     }
259
260     @Override
261     final void mergeIntoModifiedNode(final ModifiedNode modification, final NormalizedNode value,
262             final Version version) {
263         final var valueChildren = ((DistinctNodeContainer<?, ?>) value).body();
264         switch (modification.getOperation()) {
265             case NONE:
266                 // Fresh node, just record a MERGE with a value
267                 recursivelyVerifyStructure(value);
268                 modification.updateValue(LogicalOperation.MERGE, value);
269                 return;
270             case TOUCH:
271
272                 mergeChildrenIntoModification(modification, valueChildren, version);
273                 // We record empty merge value, since real children merges are already expanded. This is needed to
274                 // satisfy non-null for merge original merge value can not be used since it mean different order of
275                 // operation - parent changes are always resolved before children ones, and having node in TOUCH means
276                 // children was modified before.
277                 modification.updateValue(LogicalOperation.MERGE, support.createEmptyValue(value));
278                 return;
279             case MERGE:
280                 // Merging into an existing node. Merge data children modifications (maybe recursively) and mark
281                 // as MERGE, invalidating cached snapshot
282                 mergeChildrenIntoModification(modification, valueChildren, version);
283                 modification.updateOperationType(LogicalOperation.MERGE);
284                 return;
285             case DELETE:
286                 // Delete performs a data dependency check on existence of the node. Performing a merge on DELETE means
287                 // we are really performing a write. One thing that ruins that are any child modifications. If there
288                 // are any, we will perform a read() to get the current state of affairs, turn this into into a WRITE
289                 // and then append any child entries.
290                 if (!modification.isEmpty()) {
291                     // Version does not matter here as we'll throw it out
292                     final var current = apply(modification, modification.getOriginal(), Version.initial());
293                     if (current.isPresent()) {
294                         modification.updateValue(LogicalOperation.WRITE, current.orElseThrow().getData());
295                         mergeChildrenIntoModification(modification, valueChildren, version);
296                         return;
297                     }
298                 }
299
300                 modification.updateValue(LogicalOperation.WRITE, value);
301                 return;
302             case WRITE:
303                 // We are augmenting a previous write. We'll just walk value's children, get the corresponding
304                 // ModifiedNode and run recursively on it
305                 mergeChildrenIntoModification(modification, valueChildren, version);
306                 modification.updateOperationType(LogicalOperation.WRITE);
307                 return;
308             default:
309                 throw new IllegalArgumentException("Unsupported operation " + modification.getOperation());
310         }
311     }
312
313     @Override
314     protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
315         /*
316          * The user may have issued an empty merge operation. In this case we:
317          * - do not perform a data tree mutation
318          * - do not pass GO, and
319          * - do not collect useless garbage.
320          * It also means the ModificationType is UNMODIFIED.
321          */
322         if (!modification.isEmpty()) {
323             final var dataBuilder = support.createBuilder(currentMeta.getData());
324             final var newMeta = currentMeta.mutable();
325             newMeta.setSubtreeVersion(version);
326             final var children = modification.getChildren();
327             final var ret = mutateChildren(newMeta, dataBuilder, version, children);
328
329             /*
330              * It is possible that the only modifications under this node were empty merges, which were turned into
331              * UNMODIFIED. If that is the case, we can turn this operation into UNMODIFIED, too, potentially cascading
332              * it up to root. This has the benefit of speeding up any users, who can skip processing child nodes.
333              *
334              * In order to do that, though, we have to check all child operations are UNMODIFIED.
335              *
336              * Let's do precisely that, stopping as soon we find a different result.
337              */
338             for (var child : children) {
339                 if (child.getModificationType() != ModificationType.UNMODIFIED) {
340                     modification.resolveModificationType(ModificationType.SUBTREE_MODIFIED);
341                     return ret;
342                 }
343             }
344         }
345
346         // The merge operation did not have any children, or all of them turned out to be UNMODIFIED, hence do not
347         // replace the metadata node.
348         modification.resolveModificationType(ModificationType.UNMODIFIED);
349         return currentMeta;
350     }
351
352     @Override
353     protected final void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
354             final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
355         final TreeNode currentNode;
356         if (current.isEmpty()) {
357             currentNode = defaultTreeNode();
358             if (currentNode == null) {
359                 if (modification.original() == null) {
360                     final var id = path.toInstanceIdentifier();
361                     throw new ModifiedNodeDoesNotExistException(id,
362                         "Node " + id + " does not exist. Cannot apply modification to its children.");
363                 }
364
365                 throw new ConflictingModificationAppliedException(path.toInstanceIdentifier(),
366                     "Node was deleted by other transaction.");
367             }
368         } else {
369             currentNode = current.orElseThrow();
370         }
371
372         checkChildPreconditions(path, modification, currentNode, version);
373     }
374
375     /**
376      * Return the default tree node. Default implementation does nothing, but can be overridden to call
377      * {@link #defaultTreeNode(NormalizedNode)}.
378      *
379      * @return Default empty tree node, or null if no default is available
380      */
381     @Nullable TreeNode defaultTreeNode() {
382         // Defaults to no recovery
383         return null;
384     }
385
386     static final TreeNode defaultTreeNode(final NormalizedNode emptyNode) {
387         return TreeNode.of(emptyNode, FAKE_VERSION);
388     }
389
390     @Override
391     protected final void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
392             final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
393         if (current.isPresent()) {
394             checkChildPreconditions(path, modification, current.orElseThrow(), version);
395         }
396     }
397
398     /**
399      * Recursively check child preconditions.
400      *
401      * @param path current node path
402      * @param modification current modification
403      * @param current Current data tree node.
404      */
405     private void checkChildPreconditions(final ModificationPath path, final NodeModification modification,
406             final TreeNode current, final Version version) throws DataValidationFailedException {
407         for (final NodeModification childMod : modification.getChildren()) {
408             final PathArgument childId = childMod.getIdentifier();
409             final Optional<? extends TreeNode> childMeta = current.findChildByArg(childId);
410
411             path.push(childId);
412             try {
413                 resolveChildOperation(childId).checkApplicable(path, childMod, childMeta, version);
414             } finally {
415                 path.pop();
416             }
417         }
418     }
419
420     @Override
421     ToStringHelper addToStringAttributes(final ToStringHelper helper) {
422         return helper.add("support", support).add("verifyChildren", verifyChildrenStructure);
423     }
424 }