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