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