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