Allow dataPUT() to control ETag/Last-Modified
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / rests / transactions / RestconfStrategy.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, s.r.o. 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.restconf.nb.rfc8040.rests.transactions;
9
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.ImmutableSet;
16 import com.google.common.collect.ImmutableSetMultimap;
17 import com.google.common.io.CharSource;
18 import com.google.common.util.concurrent.FutureCallback;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import java.io.IOException;
23 import java.net.URI;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Comparator;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.NoSuchElementException;
32 import java.util.Optional;
33 import java.util.concurrent.CancellationException;
34 import java.util.function.BiFunction;
35 import java.util.function.Function;
36 import java.util.stream.Collectors;
37 import org.eclipse.jdt.annotation.NonNull;
38 import org.eclipse.jdt.annotation.NonNullByDefault;
39 import org.eclipse.jdt.annotation.Nullable;
40 import org.opendaylight.mdsal.common.api.CommitInfo;
41 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
42 import org.opendaylight.mdsal.dom.api.DOMActionException;
43 import org.opendaylight.mdsal.dom.api.DOMActionResult;
44 import org.opendaylight.mdsal.dom.api.DOMActionService;
45 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
46 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
47 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
48 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
49 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
50 import org.opendaylight.mdsal.dom.api.DOMRpcService;
51 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
52 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
53 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
54 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
55 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
56 import org.opendaylight.restconf.api.ApiPath;
57 import org.opendaylight.restconf.api.query.ContentParam;
58 import org.opendaylight.restconf.api.query.WithDefaultsParam;
59 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
60 import org.opendaylight.restconf.common.errors.RestconfError;
61 import org.opendaylight.restconf.common.errors.RestconfFuture;
62 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
63 import org.opendaylight.restconf.common.patch.PatchContext;
64 import org.opendaylight.restconf.common.patch.PatchStatusContext;
65 import org.opendaylight.restconf.common.patch.PatchStatusEntity;
66 import org.opendaylight.restconf.nb.rfc8040.Insert;
67 import org.opendaylight.restconf.nb.rfc8040.databind.ChildBody;
68 import org.opendaylight.restconf.nb.rfc8040.databind.DataPostBody;
69 import org.opendaylight.restconf.nb.rfc8040.databind.OperationInputBody;
70 import org.opendaylight.restconf.nb.rfc8040.databind.PatchBody;
71 import org.opendaylight.restconf.nb.rfc8040.databind.ResourceBody;
72 import org.opendaylight.restconf.nb.rfc8040.legacy.ErrorTags;
73 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
74 import org.opendaylight.restconf.nb.rfc8040.legacy.QueryParameters;
75 import org.opendaylight.restconf.nb.rfc8040.utils.parser.YangInstanceIdentifierSerializer;
76 import org.opendaylight.restconf.server.api.ConfigurationMetadata;
77 import org.opendaylight.restconf.server.api.DataGetParams;
78 import org.opendaylight.restconf.server.api.DataGetResult;
79 import org.opendaylight.restconf.server.api.DataPatchPath;
80 import org.opendaylight.restconf.server.api.DataPostPath;
81 import org.opendaylight.restconf.server.api.DataPostResult;
82 import org.opendaylight.restconf.server.api.DataPostResult.CreateResource;
83 import org.opendaylight.restconf.server.api.DataPostResult.InvokeOperation;
84 import org.opendaylight.restconf.server.api.DataPutPath;
85 import org.opendaylight.restconf.server.api.DataPutResult;
86 import org.opendaylight.restconf.server.api.DatabindContext;
87 import org.opendaylight.restconf.server.api.OperationsGetResult;
88 import org.opendaylight.restconf.server.api.OperationsPostPath;
89 import org.opendaylight.restconf.server.api.OperationsPostResult;
90 import org.opendaylight.restconf.server.spi.ApiPathNormalizer;
91 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.DataPath;
92 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.InstanceReference;
93 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.OperationPath;
94 import org.opendaylight.restconf.server.spi.ApiPathNormalizer.OperationPath.Rpc;
95 import org.opendaylight.restconf.server.spi.OperationInput;
96 import org.opendaylight.restconf.server.spi.RpcImplementation;
97 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.with.defaults.rev110601.WithDefaultsMode;
98 import org.opendaylight.yangtools.yang.common.Empty;
99 import org.opendaylight.yangtools.yang.common.ErrorTag;
100 import org.opendaylight.yangtools.yang.common.ErrorType;
101 import org.opendaylight.yangtools.yang.common.QName;
102 import org.opendaylight.yangtools.yang.common.QNameModule;
103 import org.opendaylight.yangtools.yang.common.Revision;
104 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
105 import org.opendaylight.yangtools.yang.common.XMLNamespace;
106 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
107 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
108 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
109 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
110 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
111 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
112 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
113 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
114 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
115 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
116 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
117 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
118 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
119 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
120 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
121 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
122 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
123 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
124 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
125 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
126 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
127 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
128 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
129 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
130 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
131 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
132 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
133 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
134 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
135 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
136 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
137 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
138 import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
139 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleEffectiveStatement;
140 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
141 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
142 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
143 import org.opendaylight.yangtools.yang.model.repo.api.YinTextSchemaSource;
144 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
145 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
146 import org.slf4j.Logger;
147 import org.slf4j.LoggerFactory;
148
149 /**
150  * Baseline execution strategy for various RESTCONF operations.
151  *
152  * @see NetconfRestconfStrategy
153  * @see MdsalRestconfStrategy
154  */
155 // FIXME: it seems the first three operations deal with lifecycle of a transaction, while others invoke various
156 //        operations. This should be handled through proper allocation indirection.
157 public abstract class RestconfStrategy {
158     @NonNullByDefault
159     public record StrategyAndPath(RestconfStrategy strategy, DataPath path) {
160         public StrategyAndPath {
161             requireNonNull(strategy);
162             requireNonNull(path);
163         }
164     }
165
166     /**
167      * Result of a partial {@link ApiPath} lookup for the purposes of supporting {@code yang-ext:mount}-delimited mount
168      * points with possible nesting.
169      *
170      * @param strategy the strategy to use
171      * @param tail the {@link ApiPath} tail to use with the strategy
172      */
173     @NonNullByDefault
174     public record StrategyAndTail(RestconfStrategy strategy, ApiPath tail) {
175         public StrategyAndTail {
176             requireNonNull(strategy);
177             requireNonNull(tail);
178         }
179     }
180
181     private static final Logger LOG = LoggerFactory.getLogger(RestconfStrategy.class);
182     private static final @NonNull DataPutResult PUT_CREATED = new DataPutResult(true);
183     private static final @NonNull DataPutResult PUT_REPLACED = new DataPutResult(false);
184
185     private final @NonNull ImmutableMap<QName, RpcImplementation> localRpcs;
186     private final @NonNull ApiPathNormalizer pathNormalizer;
187     private final @NonNull DatabindContext databind;
188     private final DOMYangTextSourceProvider sourceProvider;
189     private final DOMMountPointService mountPointService;
190     private final DOMActionService actionService;
191     private final DOMRpcService rpcService;
192
193     RestconfStrategy(final DatabindContext databind, final ImmutableMap<QName, RpcImplementation> localRpcs,
194             final @Nullable DOMRpcService rpcService, final @Nullable DOMActionService actionService,
195             final DOMYangTextSourceProvider sourceProvider, final @Nullable DOMMountPointService mountPointService) {
196         this.databind = requireNonNull(databind);
197         this.localRpcs = requireNonNull(localRpcs);
198         this.rpcService = rpcService;
199         this.actionService = actionService;
200         this.sourceProvider = sourceProvider;
201         this.mountPointService = mountPointService;
202         pathNormalizer = new ApiPathNormalizer(databind);
203     }
204
205     public final @NonNull StrategyAndPath resolveStrategyPath(final ApiPath path) {
206         final var andTail = resolveStrategy(path);
207         final var strategy = andTail.strategy();
208         return new StrategyAndPath(strategy, strategy.pathNormalizer.normalizeDataPath(andTail.tail()));
209     }
210
211     /**
212      * Resolve any and all {@code yang-ext:mount} to the target {@link StrategyAndTail}.
213      *
214      * @param path {@link ApiPath} to resolve
215      * @return A strategy and the remaining path
216      * @throws NullPointerException if {@code path} is {@code null}
217      */
218     public final @NonNull StrategyAndTail resolveStrategy(final ApiPath path) {
219         var mount = path.indexOf("yang-ext", "mount");
220         if (mount == -1) {
221             return new StrategyAndTail(this, path);
222         }
223         if (mountPointService == null) {
224             throw new RestconfDocumentedException("Mount point service is not available",
225                 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
226         }
227         final var mountPath = path.subPath(0, mount);
228         final var dataPath = pathNormalizer.normalizeDataPath(path.subPath(0, mount));
229         final var mountPoint = mountPointService.getMountPoint(dataPath.instance())
230             .orElseThrow(() -> new RestconfDocumentedException("Mount point '" + mountPath + "' does not exist",
231                 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
232
233         return createStrategy(mountPath, mountPoint).resolveStrategy(path.subPath(mount + 1));
234     }
235
236     private static @NonNull RestconfStrategy createStrategy(final ApiPath mountPath, final DOMMountPoint mountPoint) {
237         final var mountSchemaService = mountPoint.getService(DOMSchemaService.class)
238             .orElseThrow(() -> new RestconfDocumentedException(
239                 "Mount point '" + mountPath + "' does not expose DOMSchemaService",
240                 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
241         final var mountModelContext = mountSchemaService.getGlobalContext();
242         if (mountModelContext == null) {
243             throw new RestconfDocumentedException("Mount point '" + mountPath + "' does not have any models",
244                 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT);
245         }
246         final var mountDatabind = DatabindContext.ofModel(mountModelContext);
247         final var mountPointService = mountPoint.getService(DOMMountPointService.class).orElse(null);
248         final var rpcService = mountPoint.getService(DOMRpcService.class).orElse(null);
249         final var actionService = mountPoint.getService(DOMActionService.class).orElse(null);
250         final var sourceProvider = mountPoint.getService(DOMSchemaService.class)
251             .flatMap(schema -> Optional.ofNullable(schema.getExtensions().getInstance(DOMYangTextSourceProvider.class)))
252             .orElse(null);
253
254         final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
255         if (netconfService.isPresent()) {
256             return new NetconfRestconfStrategy(mountDatabind, netconfService.orElseThrow(), rpcService, actionService,
257                 sourceProvider, mountPointService);
258         }
259         final var dataBroker = mountPoint.getService(DOMDataBroker.class);
260         if (dataBroker.isPresent()) {
261             return new MdsalRestconfStrategy(mountDatabind, dataBroker.orElseThrow(), rpcService, actionService,
262                 sourceProvider, mountPointService);
263         }
264         LOG.warn("Mount point {} does not expose a suitable access interface", mountPath);
265         throw new RestconfDocumentedException("Could not find a supported access interface in mount point",
266             ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, mountPoint.getIdentifier());
267     }
268
269     public final @NonNull DatabindContext databind() {
270         return databind;
271     }
272
273     public final @NonNull EffectiveModelContext modelContext() {
274         return databind.modelContext();
275     }
276
277     /**
278      * Lock the entire datastore.
279      *
280      * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
281      *         anything else.
282      */
283     abstract RestconfTransaction prepareWriteExecution();
284
285     /**
286      * Read data from the datastore.
287      *
288      * @param store the logical data store which should be modified
289      * @param path the data object path
290      * @return a ListenableFuture containing the result of the read
291      */
292     abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
293
294     /**
295      * Check if data already exists in the configuration datastore.
296      *
297      * @param path the data object path
298      * @return a ListenableFuture containing the result of the check
299      */
300     // FIXME: this method should be hosted in RestconfTransaction
301     // FIXME: this method should only be needed in MdsalRestconfStrategy
302     abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
303
304     @VisibleForTesting
305     final @NonNull RestconfFuture<Empty> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
306         final var ret = new SettableRestconfFuture<Empty>();
307         merge(ret, requireNonNull(path), requireNonNull(data));
308         return ret;
309     }
310
311     private void merge(final @NonNull SettableRestconfFuture<Empty> future, final @NonNull YangInstanceIdentifier path,
312             final @NonNull NormalizedNode data) {
313         final var tx = prepareWriteExecution();
314         // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
315         tx.ensureParentsByMerge(path);
316         tx.merge(path, data);
317         Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
318             @Override
319             public void onSuccess(final CommitInfo result) {
320                 future.set(Empty.value());
321             }
322
323             @Override
324             public void onFailure(final Throwable cause) {
325                 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path, modelContext()));
326             }
327         }, MoreExecutors.directExecutor());
328     }
329
330     public @NonNull RestconfFuture<DataPutResult> dataPUT(final ApiPath apiPath, final ResourceBody body,
331             final Map<String, String> queryParameters) {
332         final DataPath path;
333         try {
334             path = pathNormalizer.normalizeDataPath(apiPath);
335         } catch (RestconfDocumentedException e) {
336             return RestconfFuture.failed(e);
337         }
338
339         final Insert insert;
340         try {
341             insert = Insert.ofQueryParameters(databind, queryParameters);
342         } catch (IllegalArgumentException e) {
343             return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
344                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
345         }
346         final NormalizedNode data;
347         try {
348             data = body.toNormalizedNode(new DataPutPath(databind, path.inference(), path.instance()));
349         } catch (RestconfDocumentedException e) {
350             return RestconfFuture.failed(e);
351         }
352         return putData(path.instance(), data, insert);
353     }
354
355     /**
356      * Check mount point and prepare variables for put data to DS.
357      *
358      * @param path    path of data
359      * @param data    data
360      * @param insert  {@link Insert}
361      * @return A {@link DataPutResult}
362      */
363     public final @NonNull RestconfFuture<DataPutResult> putData(final YangInstanceIdentifier path,
364             final NormalizedNode data, final @Nullable Insert insert) {
365         final var exists = TransactionUtil.syncAccess(exists(path), path);
366
367         final ListenableFuture<? extends CommitInfo> commitFuture;
368         if (insert != null) {
369             final var parentPath = path.coerceParent();
370             checkListAndOrderedType(parentPath);
371             commitFuture = insertAndCommitPut(path, data, insert, parentPath);
372         } else {
373             commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
374         }
375
376         final var ret = new SettableRestconfFuture<DataPutResult>();
377
378         Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
379             @Override
380             public void onSuccess(final CommitInfo result) {
381                 ret.set(exists ? PUT_REPLACED : PUT_CREATED);
382             }
383
384             @Override
385             public void onFailure(final Throwable cause) {
386                 ret.setFailure(TransactionUtil.decodeException(cause, "PUT", path, modelContext()));
387             }
388         }, MoreExecutors.directExecutor());
389
390         return ret;
391     }
392
393     private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
394             final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
395         final var tx = prepareWriteExecution();
396
397         return switch (insert.insert()) {
398             case FIRST -> {
399                 final var readData = tx.readList(parentPath);
400                 if (readData == null || readData.isEmpty()) {
401                     yield replaceAndCommit(tx, path, data);
402                 }
403                 tx.remove(parentPath);
404                 tx.replace(path, data);
405                 tx.replace(parentPath, readData);
406                 yield tx.commit();
407             }
408             case LAST -> replaceAndCommit(tx, path, data);
409             case BEFORE -> {
410                 final var readData = tx.readList(parentPath);
411                 if (readData == null || readData.isEmpty()) {
412                     yield replaceAndCommit(tx, path, data);
413                 }
414                 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
415                 yield tx.commit();
416             }
417             case AFTER -> {
418                 final var readData = tx.readList(parentPath);
419                 if (readData == null || readData.isEmpty()) {
420                     yield replaceAndCommit(tx, path, data);
421                 }
422                 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
423                 yield tx.commit();
424             }
425         };
426     }
427
428     private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
429             final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
430             final boolean before) {
431         tx.remove(path.getParent());
432
433         int lastItemPosition = 0;
434         for (var nodeChild : readList.body()) {
435             if (nodeChild.name().equals(pointArg)) {
436                 break;
437             }
438             lastItemPosition++;
439         }
440         if (!before) {
441             lastItemPosition++;
442         }
443
444         int lastInsertedPosition = 0;
445         final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext(), path.getParent());
446         tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
447         for (var nodeChild : readList.body()) {
448             if (lastInsertedPosition == lastItemPosition) {
449                 tx.replace(path, data);
450             }
451             final var childPath = path.coerceParent().node(nodeChild.name());
452             tx.replace(childPath, nodeChild);
453             lastInsertedPosition++;
454         }
455     }
456
457     private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
458             final YangInstanceIdentifier path, final NormalizedNode data) {
459         tx.replace(path, data);
460         return tx.commit();
461     }
462
463     private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
464         // FIXME: we have this available in InstanceIdentifierContext
465         final var dataSchemaNode = databind.schemaTree().findChild(path).orElseThrow().dataSchemaNode();
466
467         final String message;
468         if (dataSchemaNode instanceof ListSchemaNode listSchema) {
469             if (listSchema.isUserOrdered()) {
470                 return listSchema;
471             }
472             message = "Insert parameter can be used only with ordered-by user list.";
473         } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
474             if (leafListSchema.isUserOrdered()) {
475                 return leafListSchema;
476             }
477             message = "Insert parameter can be used only with ordered-by user leaf-list.";
478         } else {
479             message = "Insert parameter can be used only with list or leaf-list";
480         }
481         throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
482     }
483
484     /**
485      * Check mount point and prepare variables for post data.
486      *
487      * @param path    path
488      * @param data    data
489      * @param insert  {@link Insert}
490      * @return A {@link RestconfFuture}
491      */
492     public final @NonNull RestconfFuture<CreateResource> postData(final YangInstanceIdentifier path,
493             final NormalizedNode data, final @Nullable Insert insert) {
494         final ListenableFuture<? extends CommitInfo> future;
495         if (insert != null) {
496             final var parentPath = path.coerceParent();
497             checkListAndOrderedType(parentPath);
498             future = insertAndCommitPost(path, data, insert, parentPath);
499         } else {
500             future = createAndCommit(prepareWriteExecution(), path, data);
501         }
502
503         final var ret = new SettableRestconfFuture<CreateResource>();
504         Futures.addCallback(future, new FutureCallback<CommitInfo>() {
505             @Override
506             public void onSuccess(final CommitInfo result) {
507                 ret.set(new CreateResource(new YangInstanceIdentifierSerializer(databind).serializePath(
508                     data instanceof MapNode mapData && !mapData.isEmpty()
509                         ? path.node(mapData.body().iterator().next().name()) : path)));
510             }
511
512             @Override
513             public void onFailure(final Throwable cause) {
514                 ret.setFailure(TransactionUtil.decodeException(cause, "POST", path, modelContext()));
515             }
516
517         }, MoreExecutors.directExecutor());
518         return ret;
519     }
520
521     private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
522             final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parent) {
523         final var grandParent = parent.coerceParent();
524         final var tx = prepareWriteExecution();
525
526         return switch (insert.insert()) {
527             case FIRST -> {
528                 final var readData = tx.readList(grandParent);
529                 if (readData == null || readData.isEmpty()) {
530                     tx.replace(path, data);
531                 } else {
532                     checkItemDoesNotExists(exists(path), path);
533                     tx.remove(grandParent);
534                     tx.replace(path, data);
535                     tx.replace(grandParent, readData);
536                 }
537                 yield tx.commit();
538             }
539             case LAST -> createAndCommit(tx, path, data);
540             case BEFORE -> {
541                 final var readData = tx.readList(grandParent);
542                 if (readData == null || readData.isEmpty()) {
543                     tx.replace(path, data);
544                 } else {
545                     checkItemDoesNotExists(exists(path), path);
546                     insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, true);
547                 }
548                 yield tx.commit();
549             }
550             case AFTER -> {
551                 final var readData = tx.readList(grandParent);
552                 if (readData == null || readData.isEmpty()) {
553                     tx.replace(path, data);
554                 } else {
555                     checkItemDoesNotExists(exists(path), path);
556                     insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, false);
557                 }
558                 yield tx.commit();
559             }
560         };
561     }
562
563     /**
564      * Merge data into the configuration datastore, as outlined in
565      * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
566      *
567      * @param apiPath Path to merge
568      * @param body Data to merge
569      * @return A {@link RestconfFuture}
570      * @throws NullPointerException if any argument is {@code null}
571      */
572     public final @NonNull RestconfFuture<Empty> dataPATCH(final ApiPath apiPath, final ResourceBody body) {
573         final DataPath path;
574         try {
575             path = pathNormalizer.normalizeDataPath(apiPath);
576         } catch (RestconfDocumentedException e) {
577             return RestconfFuture.failed(e);
578         }
579
580         final NormalizedNode data;
581         try {
582             data = body.toNormalizedNode(new DataPutPath(databind, path.inference(), path.instance()));
583         } catch (RestconfDocumentedException e) {
584             return RestconfFuture.failed(e);
585         }
586
587         return merge(path.instance(), data);
588     }
589
590     public final @NonNull RestconfFuture<PatchStatusContext> dataPATCH(final ApiPath apiPath, final PatchBody body) {
591         final DataPath path;
592         try {
593             path = pathNormalizer.normalizeDataPath(apiPath);
594         } catch (RestconfDocumentedException e) {
595             return RestconfFuture.failed(e);
596         }
597
598         final PatchContext patch;
599         try {
600             patch = body.toPatchContext(new DataPatchPath(databind, path.instance()));
601         } catch (IOException e) {
602             LOG.debug("Error parsing YANG Patch input", e);
603             return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
604                 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
605         }
606         return patchData(patch);
607     }
608
609     /**
610      * Process edit operations of one {@link PatchContext}.
611      *
612      * @param patch Patch context to be processed
613      * @return {@link PatchStatusContext}
614      */
615     public final @NonNull RestconfFuture<PatchStatusContext> patchData(final PatchContext patch) {
616         final var editCollection = new ArrayList<PatchStatusEntity>();
617         final var tx = prepareWriteExecution();
618
619         boolean noError = true;
620         for (var patchEntity : patch.entities()) {
621             if (noError) {
622                 final var targetNode = patchEntity.getTargetNode();
623                 final var editId = patchEntity.getEditId();
624
625                 switch (patchEntity.getOperation()) {
626                     case Create:
627                         try {
628                             tx.create(targetNode, patchEntity.getNode());
629                             editCollection.add(new PatchStatusEntity(editId, true, null));
630                         } catch (RestconfDocumentedException e) {
631                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
632                             noError = false;
633                         }
634                         break;
635                     case Delete:
636                         try {
637                             tx.delete(targetNode);
638                             editCollection.add(new PatchStatusEntity(editId, true, null));
639                         } catch (RestconfDocumentedException e) {
640                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
641                             noError = false;
642                         }
643                         break;
644                     case Merge:
645                         try {
646                             tx.ensureParentsByMerge(targetNode);
647                             tx.merge(targetNode, patchEntity.getNode());
648                             editCollection.add(new PatchStatusEntity(editId, true, null));
649                         } catch (RestconfDocumentedException e) {
650                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
651                             noError = false;
652                         }
653                         break;
654                     case Replace:
655                         try {
656                             tx.replace(targetNode, patchEntity.getNode());
657                             editCollection.add(new PatchStatusEntity(editId, true, null));
658                         } catch (RestconfDocumentedException e) {
659                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
660                             noError = false;
661                         }
662                         break;
663                     case Remove:
664                         try {
665                             tx.remove(targetNode);
666                             editCollection.add(new PatchStatusEntity(editId, true, null));
667                         } catch (RestconfDocumentedException e) {
668                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
669                             noError = false;
670                         }
671                         break;
672                     default:
673                         editCollection.add(new PatchStatusEntity(editId, false, List.of(
674                             new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
675                                 "Not supported Yang Patch operation"))));
676                         noError = false;
677                         break;
678                 }
679             } else {
680                 break;
681             }
682         }
683
684         final var ret = new SettableRestconfFuture<PatchStatusContext>();
685         // We have errors
686         if (!noError) {
687             tx.cancel();
688             ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false, null));
689             return ret;
690         }
691
692         Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
693             @Override
694             public void onSuccess(final CommitInfo result) {
695                 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), true,
696                     null));
697             }
698
699             @Override
700             public void onFailure(final Throwable cause) {
701                 // if errors occurred during transaction commit then patch failed and global errors are reported
702                 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false,
703                     TransactionUtil.decodeException(cause, "PATCH", null, modelContext()).getErrors()));
704             }
705         }, MoreExecutors.directExecutor());
706
707         return ret;
708     }
709
710     private void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
711             final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
712             final YangInstanceIdentifier grandParentPath, final boolean before) {
713         tx.remove(grandParentPath);
714
715         int lastItemPosition = 0;
716         for (var nodeChild : readList.body()) {
717             if (nodeChild.name().equals(pointArg)) {
718                 break;
719             }
720             lastItemPosition++;
721         }
722         if (!before) {
723             lastItemPosition++;
724         }
725
726         int lastInsertedPosition = 0;
727         final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext(), grandParentPath);
728         tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
729         for (var nodeChild : readList.body()) {
730             if (lastInsertedPosition == lastItemPosition) {
731                 tx.replace(path, data);
732             }
733             tx.replace(grandParentPath.node(nodeChild.name()), nodeChild);
734             lastInsertedPosition++;
735         }
736     }
737
738     private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
739             final YangInstanceIdentifier path, final NormalizedNode data) {
740         try {
741             tx.create(path, data);
742         } catch (RestconfDocumentedException e) {
743             // close transaction if any and pass exception further
744             tx.cancel();
745             throw e;
746         }
747
748         return tx.commit();
749     }
750
751     /**
752      * Check if items do NOT already exists at specified {@code path}.
753      *
754      * @param existsFuture if checked data exists
755      * @param path         Path to be checked
756      * @throws RestconfDocumentedException if data already exists.
757      */
758     static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
759             final YangInstanceIdentifier path) {
760         if (TransactionUtil.syncAccess(existsFuture, path)) {
761             LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
762             throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
763                 path);
764         }
765     }
766
767     /**
768      * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
769      * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
770      *
771      * @param apiPath Path to delete
772      * @return A {@link RestconfFuture}
773      * @throws NullPointerException if {@code apiPath} is {@code null}
774      */
775     @SuppressWarnings("checkstyle:abbreviationAsWordInName")
776     public final @NonNull RestconfFuture<Empty> dataDELETE(final ApiPath apiPath) {
777         final DataPath path;
778         try {
779             path = pathNormalizer.normalizeDataPath(apiPath);
780         } catch (RestconfDocumentedException e) {
781             return RestconfFuture.failed(e);
782         }
783
784         // FIXME: reject empty YangInstanceIdentifier, as datastores may not be deleted
785         final var ret = new SettableRestconfFuture<Empty>();
786         delete(ret, path.instance());
787         return ret;
788     }
789
790     abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
791
792     public final @NonNull RestconfFuture<DataGetResult> dataGET(final ApiPath apiPath,
793             final DataGetParams params) {
794         final DataPath path;
795         try {
796             path = pathNormalizer.normalizeDataPath(apiPath);
797         } catch (RestconfDocumentedException e) {
798             return RestconfFuture.failed(e);
799         }
800         return dataGET(path, params);
801     }
802
803     abstract @NonNull RestconfFuture<DataGetResult> dataGET(DataPath path, DataGetParams params);
804
805     static final @NonNull RestconfFuture<DataGetResult> completeDataGET(final Inference inference,
806             final QueryParameters queryParams, final @Nullable NormalizedNode node,
807             final @Nullable ConfigurationMetadata metadata) {
808         if (node == null) {
809             return RestconfFuture.failed(new RestconfDocumentedException(
810                 "Request could not be completed because the relevant data model content does not exist",
811                 ErrorType.PROTOCOL, ErrorTag.DATA_MISSING));
812         }
813
814         final var payload = new NormalizedNodePayload(inference, node, queryParams);
815         return RestconfFuture.of(metadata == null ? new DataGetResult(payload)
816             : new DataGetResult(payload, metadata.entityTag(), metadata.lastModified()));
817     }
818
819     /**
820      * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
821      * inside of object {@link RestconfStrategy} provided as a parameter.
822      *
823      * @param content      type of data to read (config, state, all)
824      * @param path         the path to read
825      * @param defaultsMode value of with-defaults parameter
826      * @return {@link NormalizedNode}
827      */
828     // FIXME: NETCONF-1155: this method should asynchronous
829     public final @Nullable NormalizedNode readData(final @NonNull ContentParam content,
830             final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
831         return switch (content) {
832             case ALL -> {
833                 // PREPARE STATE DATA NODE
834                 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
835                 // PREPARE CONFIG DATA NODE
836                 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
837
838                 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
839                     : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
840             }
841             case CONFIG -> {
842                 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
843                 yield defaultsMode == null ? read
844                     : prepareDataByParamWithDef(read, path, defaultsMode.mode());
845             }
846             case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
847         };
848     }
849
850     private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
851             final YangInstanceIdentifier path) {
852         return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
853     }
854
855     final NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
856             final WithDefaultsMode defaultsMode) {
857         final boolean trim = switch (defaultsMode) {
858             case Trim -> true;
859             case Explicit -> false;
860             case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
861                 "Unsupported with-defaults value " + defaultsMode.getName());
862         };
863
864         // FIXME: we have this readily available in InstanceIdentifierContext
865         final var ctxNode = databind.schemaTree().findChild(path).orElseThrow();
866         if (readData instanceof ContainerNode container) {
867             final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
868             buildCont(builder, container.body(), ctxNode, trim);
869             return builder.build();
870         } else if (readData instanceof MapEntryNode mapEntry) {
871             if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
872                 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
873             }
874
875             final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
876             buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
877             return builder.build();
878         } else {
879             throw new IllegalStateException("Unhandled data contract " + readData.contract());
880         }
881     }
882
883     private static void buildMapEntryBuilder(
884             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
885             final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
886             final boolean trim, final List<QName> keys) {
887         for (var child : children) {
888             final var childCtx = getChildContext(ctxNode, child);
889
890             if (child instanceof ContainerNode container) {
891                 appendContainer(builder, container, childCtx, trim);
892             } else if (child instanceof MapNode map) {
893                 appendMap(builder, map, childCtx, trim);
894             } else if (child instanceof LeafNode<?> leaf) {
895                 appendLeaf(builder, leaf, childCtx, trim, keys);
896             } else {
897                 // FIXME: we should never hit this, throw an ISE if this ever happens
898                 LOG.debug("Ignoring unhandled child contract {}", child.contract());
899             }
900         }
901     }
902
903     private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
904             final DataSchemaContext ctxNode, final boolean trim) {
905         final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
906         buildCont(childBuilder, container.body(), ctxNode, trim);
907         builder.withChild(childBuilder.build());
908     }
909
910     private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
911             final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
912         if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
913             throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
914         }
915
916         // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
917         final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
918
919         // This is a combined check for when we need to emit the leaf.
920         if (
921             // We always have to emit key leaf values
922             keys.contains(leafSchema.getQName())
923             // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
924             //
925             //            When data is retrieved with a <with-defaults> parameter equal to
926             //            'trim', data nodes MUST NOT be reported if they contain the schema
927             //            default value.  Non-configuration data nodes containing the schema
928             //            default value MUST NOT be reported.
929             //
930             || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
931             // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
932             // grasp what we are doing here... emit only if it matches default ???!!!
933             // FIXME: The WithDefaultsParam.EXPLICIT says:
934             //
935             //            Data nodes set to the YANG default by the client are reported.
936             //
937             //        and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
938             //
939             //            If the "with-defaults" parameter is set to "explicit", then the
940             //            server MUST adhere to the default-reporting behavior defined in
941             //            Section 3.3 of [RFC6243].
942             //
943             //        and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
944             //
945             //            When data is retrieved with a <with-defaults> parameter equal to
946             //            'explicit', a data node that was set by a client to its schema
947             //            default value MUST be reported.  A conceptual data node that would be
948             //            set by the server to the schema default value MUST NOT be reported.
949             //            Non-configuration data nodes containing the schema default value MUST
950             //            be reported.
951             //
952             // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
953             //            This seems to disregard the 'trim = true' case semantics (see above).
954             //            Combining the above, though, these checks are missing the 'non-config' check, which would
955             //            distinguish, but barring that this check is superfluous and results in the wrong semantics.
956             //            Without that input, this really should be  covered by the previous case.
957                 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
958             builder.withChild(leaf);
959         }
960     }
961
962     private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
963             final DataSchemaContext childCtx, final boolean trim) {
964         if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
965             throw new IllegalStateException("Input " + map + " does not match " + childCtx);
966         }
967
968         final var childBuilder = switch (map.ordering()) {
969             case SYSTEM -> Builders.mapBuilder();
970             case USER -> Builders.orderedMapBuilder();
971         };
972         buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
973             listSchema.getKeyDefinition());
974         builder.withChild(childBuilder.build());
975     }
976
977     private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
978             final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
979             final List<@NonNull QName> keys) {
980         for (var entry : entries) {
981             final var childCtx = getChildContext(ctxNode, entry);
982             final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
983             buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
984             builder.withChild(mapEntryBuilder.build());
985         }
986     }
987
988     private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
989             final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
990         for (var child : children) {
991             final var childCtx = getChildContext(ctxNode, child);
992             if (child instanceof ContainerNode container) {
993                 appendContainer(builder, container, childCtx, trim);
994             } else if (child instanceof MapNode map) {
995                 appendMap(builder, map, childCtx, trim);
996             } else if (child instanceof LeafNode<?> leaf) {
997                 appendLeaf(builder, leaf, childCtx, trim, List.of());
998             }
999         }
1000     }
1001
1002     private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
1003             final NormalizedNode child) {
1004         final var childId = child.name();
1005         final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
1006             : null;
1007         if (childCtx == null) {
1008             throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
1009         }
1010         return childCtx;
1011     }
1012
1013     static final NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
1014             final NormalizedNode configDataNode) {
1015         // if no data exists
1016         if (stateDataNode == null && configDataNode == null) {
1017             return null;
1018         }
1019
1020         // return config data
1021         if (stateDataNode == null) {
1022             return configDataNode;
1023         }
1024
1025         // return state data
1026         if (configDataNode == null) {
1027             return stateDataNode;
1028         }
1029
1030         // merge data from config and state
1031         return mergeStateAndConfigData(stateDataNode, configDataNode);
1032     }
1033
1034     /**
1035      * Merge state and config data into a single NormalizedNode.
1036      *
1037      * @param stateDataNode  data node of state data
1038      * @param configDataNode data node of config data
1039      * @return {@link NormalizedNode}
1040      */
1041     private static @NonNull NormalizedNode mergeStateAndConfigData(
1042             final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
1043         validateNodeMerge(stateDataNode, configDataNode);
1044         // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
1045         if (configDataNode instanceof RpcDefinition) {
1046             return prepareRpcData(configDataNode, stateDataNode);
1047         } else {
1048             return prepareData(configDataNode, stateDataNode);
1049         }
1050     }
1051
1052     /**
1053      * Validates whether the two NormalizedNodes can be merged.
1054      *
1055      * @param stateDataNode  data node of state data
1056      * @param configDataNode data node of config data
1057      */
1058     private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
1059                                           final @NonNull NormalizedNode configDataNode) {
1060         final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
1061         final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
1062         if (!moduleOfStateData.equals(moduleOfConfigData)) {
1063             throw new RestconfDocumentedException("Unable to merge data from different modules.");
1064         }
1065     }
1066
1067     /**
1068      * Prepare and map data for rpc.
1069      *
1070      * @param configDataNode data node of config data
1071      * @param stateDataNode  data node of state data
1072      * @return {@link NormalizedNode}
1073      */
1074     private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
1075                                                           final @NonNull NormalizedNode stateDataNode) {
1076         final var mapEntryBuilder = Builders.mapEntryBuilder()
1077             .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
1078
1079         // MAP CONFIG DATA
1080         mapRpcDataNode(configDataNode, mapEntryBuilder);
1081         // MAP STATE DATA
1082         mapRpcDataNode(stateDataNode, mapEntryBuilder);
1083
1084         return Builders.mapBuilder()
1085             .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
1086             .addChild(mapEntryBuilder.build())
1087             .build();
1088     }
1089
1090     /**
1091      * Map node to map entry builder.
1092      *
1093      * @param dataNode        data node
1094      * @param mapEntryBuilder builder for mapping data
1095      */
1096     private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
1097             final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
1098         ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
1099     }
1100
1101     /**
1102      * Prepare and map all data from DS.
1103      *
1104      * @param configDataNode data node of config data
1105      * @param stateDataNode  data node of state data
1106      * @return {@link NormalizedNode}
1107      */
1108     @SuppressWarnings("unchecked")
1109     private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
1110                                                        final @NonNull NormalizedNode stateDataNode) {
1111         if (configDataNode instanceof UserMapNode configMap) {
1112             final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
1113             mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
1114             return builder.build();
1115         } else if (configDataNode instanceof SystemMapNode configMap) {
1116             final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
1117             mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
1118             return builder.build();
1119         } else if (configDataNode instanceof MapEntryNode configEntry) {
1120             final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
1121             mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
1122             return builder.build();
1123         } else if (configDataNode instanceof ContainerNode configContaienr) {
1124             final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
1125             mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
1126             return builder.build();
1127         } else if (configDataNode instanceof ChoiceNode configChoice) {
1128             final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
1129             mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
1130             return builder.build();
1131         } else if (configDataNode instanceof LeafNode configLeaf) {
1132             // config trumps oper
1133             return configLeaf;
1134         } else if (configDataNode instanceof UserLeafSetNode) {
1135             final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
1136             final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
1137             mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
1138             return builder.build();
1139         } else if (configDataNode instanceof SystemLeafSetNode) {
1140             final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
1141             final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
1142             mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
1143             return builder.build();
1144         } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
1145             // config trumps oper
1146             return configEntry;
1147         } else if (configDataNode instanceof UnkeyedListNode configList) {
1148             final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
1149             mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
1150             return builder.build();
1151         } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
1152             final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
1153             mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
1154             return builder.build();
1155         } else {
1156             throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
1157         }
1158     }
1159
1160     /**
1161      * Map value from container node to builder.
1162      *
1163      * @param configData collection of config data nodes
1164      * @param stateData  collection of state data nodes
1165      * @param builder    builder
1166      */
1167     private static <T extends NormalizedNode> void mapValueToBuilder(
1168             final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1169             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1170         final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1171         final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1172
1173         // merge config and state data of children with different identifiers
1174         mapDataToBuilder(configMap, stateMap, builder);
1175
1176         // merge config and state data of children with the same identifiers
1177         mergeDataToBuilder(configMap, stateMap, builder);
1178     }
1179
1180     /**
1181      * Map data with different identifiers to builder. Data with different identifiers can be just added
1182      * as childs to parent node.
1183      *
1184      * @param configMap map of config data nodes
1185      * @param stateMap  map of state data nodes
1186      * @param builder   - builder
1187      */
1188     private static <T extends NormalizedNode> void mapDataToBuilder(
1189             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1190             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1191         configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1192             y -> builder.addChild(y.getValue()));
1193         stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1194             y -> builder.addChild(y.getValue()));
1195     }
1196
1197     /**
1198      * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1199      * go one level down with {@code prepareData} method.
1200      *
1201      * @param configMap immutable config data
1202      * @param stateMap  immutable state data
1203      * @param builder   - builder
1204      */
1205     @SuppressWarnings("unchecked")
1206     private static <T extends NormalizedNode> void mergeDataToBuilder(
1207             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1208             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1209         // it is enough to process only config data because operational contains the same data
1210         configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1211             y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1212     }
1213
1214     public @NonNull RestconfFuture<OperationsGetResult> operationsGET() {
1215         final var modelContext = modelContext();
1216         final var modules = modelContext.getModuleStatements();
1217         if (modules.isEmpty()) {
1218             // No modules, or defensive return empty content
1219             return RestconfFuture.of(new OperationsGetResult.Container(modelContext, ImmutableSetMultimap.of()));
1220         }
1221
1222         // RPC QNames by their XMLNamespace/Revision. This should be a Table, but Revision can be null, which wrecks us.
1223         final var table = new HashMap<XMLNamespace, Map<Revision, ImmutableSet<QName>>>();
1224         for (var entry : modules.entrySet()) {
1225             final var module = entry.getValue();
1226             final var rpcNames = module.streamEffectiveSubstatements(RpcEffectiveStatement.class)
1227                 .map(RpcEffectiveStatement::argument)
1228                 .collect(ImmutableSet.toImmutableSet());
1229             if (!rpcNames.isEmpty()) {
1230                 final var namespace = entry.getKey();
1231                 table.computeIfAbsent(namespace.getNamespace(), ignored -> new HashMap<>())
1232                     .put(namespace.getRevision().orElse(null), rpcNames);
1233             }
1234         }
1235
1236         // Now pick the latest revision for each namespace
1237         final var rpcs = ImmutableSetMultimap.<QNameModule, QName>builder();
1238         for (var entry : table.entrySet()) {
1239             entry.getValue().entrySet().stream()
1240             .sorted(Comparator.comparing(Entry::getKey, (first, second) -> Revision.compare(second, first)))
1241             .findFirst()
1242             .ifPresent(row -> rpcs.putAll(QNameModule.create(entry.getKey(), row.getKey()), row.getValue()));
1243         }
1244         return RestconfFuture.of(new OperationsGetResult.Container(modelContext, rpcs.build()));
1245     }
1246
1247     public @NonNull RestconfFuture<OperationsGetResult> operationsGET(final ApiPath apiPath) {
1248         if (apiPath.steps().isEmpty()) {
1249             return operationsGET();
1250         }
1251
1252         final Rpc rpc;
1253         try {
1254             rpc = pathNormalizer.normalizeRpcPath(apiPath);
1255         } catch (RestconfDocumentedException e) {
1256             return RestconfFuture.failed(e);
1257         }
1258
1259         return RestconfFuture.of(
1260             new OperationsGetResult.Leaf(rpc.inference().getEffectiveModelContext(), rpc.rpc().argument()));
1261     }
1262
1263     public @NonNull RestconfFuture<OperationsPostResult> operationsPOST(final URI restconfURI, final ApiPath apiPath,
1264             final OperationInputBody body) {
1265         final OperationPath.Rpc path;
1266         try {
1267             path = pathNormalizer.normalizeRpcPath(apiPath);
1268         } catch (RestconfDocumentedException e) {
1269             return RestconfFuture.failed(e);
1270         }
1271
1272         final var postPath = new OperationsPostPath(databind, path.inference());
1273         final ContainerNode data;
1274         try {
1275             data = body.toContainerNode(postPath);
1276         } catch (IOException e) {
1277             LOG.debug("Error reading input", e);
1278             return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1279                 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1280         }
1281
1282         final var type = path.rpc().argument();
1283         final var local = localRpcs.get(type);
1284         if (local != null) {
1285             return local.invoke(restconfURI, new OperationInput(databind, postPath.operation(), data));
1286         }
1287         if (rpcService == null) {
1288             LOG.debug("RPC invocation is not available");
1289             return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1290                 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1291         }
1292
1293         final var ret = new SettableRestconfFuture<OperationsPostResult>();
1294         Futures.addCallback(rpcService.invokeRpc(type, data), new FutureCallback<DOMRpcResult>() {
1295             @Override
1296             public void onSuccess(final DOMRpcResult response) {
1297                 final var errors = response.errors();
1298                 if (errors.isEmpty()) {
1299                     ret.set(new OperationsPostResult(databind, postPath.operation(), response.value()));
1300                 } else {
1301                     LOG.debug("RPC invocation reported {}", response.errors());
1302                     ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1303                         response.errors()));
1304                 }
1305             }
1306
1307             @Override
1308             public void onFailure(final Throwable cause) {
1309                 LOG.debug("RPC invocation failed, cause");
1310                 if (cause instanceof RestconfDocumentedException ex) {
1311                     ret.setFailure(ex);
1312                 } else {
1313                     // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1314                     ret.setFailure(new RestconfDocumentedException(cause,
1315                         new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1316                 }
1317             }
1318         }, MoreExecutors.directExecutor());
1319         return ret;
1320     }
1321
1322     public @NonNull RestconfFuture<CharSource> resolveSource(final SourceIdentifier source,
1323             final Class<? extends SchemaSourceRepresentation> representation) {
1324         final var src = requireNonNull(source);
1325         if (YangTextSchemaSource.class.isAssignableFrom(representation)) {
1326             if (sourceProvider != null) {
1327                 final var ret = new SettableRestconfFuture<CharSource>();
1328                 Futures.addCallback(sourceProvider.getSource(src), new FutureCallback<YangTextSchemaSource>() {
1329                     @Override
1330                     public void onSuccess(final YangTextSchemaSource result) {
1331                         ret.set(result);
1332                     }
1333
1334                     @Override
1335                     public void onFailure(final Throwable cause) {
1336                         ret.setFailure(cause instanceof RestconfDocumentedException e ? e
1337                             : new RestconfDocumentedException(cause.getMessage(), ErrorType.RPC,
1338                                 ErrorTag.OPERATION_FAILED, cause));
1339                     }
1340                 }, MoreExecutors.directExecutor());
1341                 return ret;
1342             }
1343             return exportSource(modelContext(), src, YangCharSource::new, YangCharSource::new);
1344         }
1345         if (YinTextSchemaSource.class.isAssignableFrom(representation)) {
1346             return exportSource(modelContext(), src, YinCharSource.OfModule::new, YinCharSource.OfSubmodule::new);
1347         }
1348         return RestconfFuture.failed(new RestconfDocumentedException(
1349             "Unsupported source representation " + representation.getName()));
1350     }
1351
1352     private static @NonNull RestconfFuture<CharSource> exportSource(final EffectiveModelContext modelContext,
1353             final SourceIdentifier source, final Function<ModuleEffectiveStatement, CharSource> moduleCtor,
1354             final BiFunction<ModuleEffectiveStatement, SubmoduleEffectiveStatement, CharSource> submoduleCtor) {
1355         // If the source identifies a module, things are easy
1356         final var name = source.name().getLocalName();
1357         final var optRevision = Optional.ofNullable(source.revision());
1358         final var optModule = modelContext.findModule(name, optRevision);
1359         if (optModule.isPresent()) {
1360             return RestconfFuture.of(moduleCtor.apply(optModule.orElseThrow().asEffectiveStatement()));
1361         }
1362
1363         // The source could be a submodule, which we need to hunt down
1364         for (var module : modelContext.getModules()) {
1365             for (var submodule : module.getSubmodules()) {
1366                 if (name.equals(submodule.getName()) && optRevision.equals(submodule.getRevision())) {
1367                     return RestconfFuture.of(submoduleCtor.apply(module.asEffectiveStatement(),
1368                         submodule.asEffectiveStatement()));
1369                 }
1370             }
1371         }
1372
1373         final var sb = new StringBuilder().append("Source ").append(source.name().getLocalName());
1374         optRevision.ifPresent(rev -> sb.append('@').append(rev));
1375         sb.append(" not found");
1376         return RestconfFuture.failed(new RestconfDocumentedException(sb.toString(),
1377             ErrorType.APPLICATION, ErrorTag.DATA_MISSING));
1378     }
1379
1380     public final @NonNull RestconfFuture<? extends DataPostResult> dataPOST(final ApiPath apiPath,
1381             final DataPostBody body, final Map<String, String> queryParameters) {
1382         if (apiPath.steps().isEmpty()) {
1383             return dataCreatePOST(body.toResource(), queryParameters);
1384         }
1385         final InstanceReference path;
1386         try {
1387             path = pathNormalizer.normalizeDataOrActionPath(apiPath);
1388         } catch (RestconfDocumentedException e) {
1389             return RestconfFuture.failed(e);
1390         }
1391         if (path instanceof DataPath dataPath) {
1392             try (var resourceBody = body.toResource()) {
1393                 return dataCreatePOST(new DataPostPath(databind, dataPath.inference(), dataPath.instance()),
1394                     resourceBody, queryParameters);
1395             }
1396         }
1397         if (path instanceof OperationPath.Action actionPath) {
1398             try (var inputBody = body.toOperationInput()) {
1399                 return dataInvokePOST(actionPath, inputBody);
1400             }
1401         }
1402         // Note: this should never happen
1403         // FIXME: we should be able to eliminate this path with Java 21+ pattern matching
1404         return RestconfFuture.failed(new RestconfDocumentedException("Unhandled path " + path));
1405     }
1406
1407     public @NonNull RestconfFuture<CreateResource> dataCreatePOST(final ChildBody body,
1408             final Map<String, String> queryParameters) {
1409         return dataCreatePOST(new DataPostPath(databind,
1410             SchemaInferenceStack.of(databind.modelContext()).toInference(), YangInstanceIdentifier.of()), body,
1411             queryParameters);
1412     }
1413
1414     private @NonNull RestconfFuture<CreateResource> dataCreatePOST(final DataPostPath path, final ChildBody body,
1415             final Map<String, String> queryParameters) {
1416         final Insert insert;
1417         try {
1418             insert = Insert.ofQueryParameters(path.databind(), queryParameters);
1419         } catch (IllegalArgumentException e) {
1420             return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
1421                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
1422         }
1423
1424         final var payload = body.toPayload(path);
1425         return postData(concat(path.instance(), payload.prefix()), payload.body(), insert);
1426     }
1427
1428     private static YangInstanceIdentifier concat(final YangInstanceIdentifier parent, final List<PathArgument> args) {
1429         var ret = parent;
1430         for (var arg : args) {
1431             ret = ret.node(arg);
1432         }
1433         return ret;
1434     }
1435
1436     private @NonNull RestconfFuture<InvokeOperation> dataInvokePOST(final OperationPath.Action path,
1437             final OperationInputBody body) {
1438         final var inference = path.inference();
1439         final ContainerNode input;
1440         try {
1441             input = body.toContainerNode(new OperationsPostPath(databind, inference));
1442         } catch (IOException e) {
1443             LOG.debug("Error reading input", e);
1444             return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1445                 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1446         }
1447
1448         if (actionService == null) {
1449             return RestconfFuture.failed(new RestconfDocumentedException("DOMActionService is missing."));
1450         }
1451
1452         final var future = dataInvokePOST(actionService, path, input);
1453         return future.transform(result -> result.getOutput()
1454             .flatMap(output -> output.isEmpty() ? Optional.empty()
1455                 : Optional.of(new InvokeOperation(new NormalizedNodePayload(inference, output))))
1456             .orElse(InvokeOperation.EMPTY));
1457     }
1458
1459     /**
1460      * Invoke Action via ActionServiceHandler.
1461      *
1462      * @param input input data
1463      * @param yangIId invocation context
1464      * @param schemaPath schema path of data
1465      * @param actionService action service to invoke action
1466      * @return {@link DOMActionResult}
1467      */
1468     private static RestconfFuture<DOMActionResult> dataInvokePOST(final DOMActionService actionService,
1469             final OperationPath.Action path, final @NonNull ContainerNode input) {
1470         final var ret = new SettableRestconfFuture<DOMActionResult>();
1471
1472         Futures.addCallback(actionService.invokeAction(
1473             path.inference().toSchemaInferenceStack().toSchemaNodeIdentifier(),
1474             new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, path.instance()), input),
1475             new FutureCallback<DOMActionResult>() {
1476                 @Override
1477                 public void onSuccess(final DOMActionResult result) {
1478                     final var errors = result.getErrors();
1479                     LOG.debug("InvokeAction Error Message {}", errors);
1480                     if (errors.isEmpty()) {
1481                         ret.set(result);
1482                     } else {
1483                         ret.setFailure(new RestconfDocumentedException("InvokeAction Error Message ", null, errors));
1484                     }
1485                 }
1486
1487                 @Override
1488                 public void onFailure(final Throwable cause) {
1489                     if (cause instanceof DOMActionException) {
1490                         ret.set(new SimpleDOMActionResult(List.of(RpcResultBuilder.newError(
1491                             ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage()))));
1492                     } else if (cause instanceof RestconfDocumentedException e) {
1493                         ret.setFailure(e);
1494                     } else if (cause instanceof CancellationException) {
1495                         ret.setFailure(new RestconfDocumentedException("Action cancelled while executing",
1496                             ErrorType.RPC, ErrorTag.PARTIAL_OPERATION, cause));
1497                     } else {
1498                         ret.setFailure(new RestconfDocumentedException("Invocation failed", cause));
1499                     }
1500                 }
1501             }, MoreExecutors.directExecutor());
1502
1503         return ret;
1504     }
1505 }