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