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