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