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