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