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