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