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