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