Allow odl-pretty-print to be configured to true
[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.io.CharSource;
17 import com.google.common.util.concurrent.FutureCallback;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import com.google.common.util.concurrent.MoreExecutors;
21 import java.io.IOException;
22 import java.net.URI;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.NoSuchElementException;
28 import java.util.Optional;
29 import java.util.concurrent.CancellationException;
30 import java.util.function.BiFunction;
31 import java.util.function.Function;
32 import java.util.stream.Collectors;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.opendaylight.mdsal.common.api.CommitInfo;
37 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
38 import org.opendaylight.mdsal.dom.api.DOMActionException;
39 import org.opendaylight.mdsal.dom.api.DOMActionResult;
40 import org.opendaylight.mdsal.dom.api.DOMActionService;
41 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
42 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
43 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
44 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
45 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
46 import org.opendaylight.mdsal.dom.api.DOMRpcService;
47 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
48 import org.opendaylight.mdsal.dom.api.DOMSchemaService.YangTextSourceExtension;
49 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
50 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
51 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
52 import org.opendaylight.restconf.api.ApiPath;
53 import org.opendaylight.restconf.api.FormattableBody;
54 import org.opendaylight.restconf.api.query.ContentParam;
55 import org.opendaylight.restconf.api.query.WithDefaultsParam;
56 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
57 import org.opendaylight.restconf.common.errors.RestconfError;
58 import org.opendaylight.restconf.common.errors.RestconfFuture;
59 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
60 import org.opendaylight.restconf.common.patch.PatchContext;
61 import org.opendaylight.restconf.nb.rfc8040.Insert;
62 import org.opendaylight.restconf.nb.rfc8040.legacy.ErrorTags;
63 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
64 import org.opendaylight.restconf.nb.rfc8040.legacy.WriterParameters;
65 import org.opendaylight.restconf.server.api.ChildBody;
66 import org.opendaylight.restconf.server.api.ConfigurationMetadata;
67 import org.opendaylight.restconf.server.api.CreateResourceResult;
68 import org.opendaylight.restconf.server.api.DataGetParams;
69 import org.opendaylight.restconf.server.api.DataGetResult;
70 import org.opendaylight.restconf.server.api.DataPatchResult;
71 import org.opendaylight.restconf.server.api.DataPostBody;
72 import org.opendaylight.restconf.server.api.DataPostResult;
73 import org.opendaylight.restconf.server.api.DataPutResult;
74 import org.opendaylight.restconf.server.api.DataYangPatchParams;
75 import org.opendaylight.restconf.server.api.DataYangPatchResult;
76 import org.opendaylight.restconf.server.api.DatabindContext;
77 import org.opendaylight.restconf.server.api.DatabindPath;
78 import org.opendaylight.restconf.server.api.DatabindPath.Action;
79 import org.opendaylight.restconf.server.api.DatabindPath.Data;
80 import org.opendaylight.restconf.server.api.DatabindPath.InstanceReference;
81 import org.opendaylight.restconf.server.api.DatabindPath.OperationPath;
82 import org.opendaylight.restconf.server.api.DatabindPath.Rpc;
83 import org.opendaylight.restconf.server.api.InvokeParams;
84 import org.opendaylight.restconf.server.api.InvokeResult;
85 import org.opendaylight.restconf.server.api.OperationInputBody;
86 import org.opendaylight.restconf.server.api.PatchBody;
87 import org.opendaylight.restconf.server.api.PatchStatusContext;
88 import org.opendaylight.restconf.server.api.PatchStatusEntity;
89 import org.opendaylight.restconf.server.api.QueryParams;
90 import org.opendaylight.restconf.server.api.ResourceBody;
91 import org.opendaylight.restconf.server.spi.ApiPathCanonizer;
92 import org.opendaylight.restconf.server.spi.ApiPathNormalizer;
93 import org.opendaylight.restconf.server.spi.DefaultResourceContext;
94 import org.opendaylight.restconf.server.spi.OperationInput;
95 import org.opendaylight.restconf.server.spi.OperationOutputBody;
96 import org.opendaylight.restconf.server.spi.OperationsResource;
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.RpcResultBuilder;
105 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
106 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
107 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
108 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
109 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
110 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
111 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
112 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
113 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
114 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
115 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
116 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
117 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
118 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
119 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
120 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
121 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
122 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
123 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
124 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
125 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
126 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
127 import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
128 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
129 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
130 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
131 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
132 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
133 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
134 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
135 import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
136 import org.opendaylight.yangtools.yang.model.api.source.SourceRepresentation;
137 import org.opendaylight.yangtools.yang.model.api.source.YangTextSource;
138 import org.opendaylight.yangtools.yang.model.api.source.YinTextSource;
139 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
140 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleEffectiveStatement;
141 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
142 import org.slf4j.Logger;
143 import org.slf4j.LoggerFactory;
144
145 /**
146  * Baseline execution strategy for various RESTCONF operations.
147  *
148  * @see NetconfRestconfStrategy
149  * @see MdsalRestconfStrategy
150  */
151 // FIXME: it seems the first three operations deal with lifecycle of a transaction, while others invoke various
152 //        operations. This should be handled through proper allocation indirection.
153 public abstract class RestconfStrategy {
154     @NonNullByDefault
155     public record StrategyAndPath(RestconfStrategy strategy, Data path) {
156         public StrategyAndPath {
157             requireNonNull(strategy);
158             requireNonNull(path);
159         }
160     }
161
162     /**
163      * Result of a partial {@link ApiPath} lookup for the purposes of supporting {@code yang-ext:mount}-delimited mount
164      * points with possible nesting.
165      *
166      * @param strategy the strategy to use
167      * @param tail the {@link ApiPath} tail to use with the strategy
168      */
169     @NonNullByDefault
170     public record StrategyAndTail(RestconfStrategy strategy, ApiPath tail) {
171         public StrategyAndTail {
172             requireNonNull(strategy);
173             requireNonNull(tail);
174         }
175     }
176
177     private static final Logger LOG = LoggerFactory.getLogger(RestconfStrategy.class);
178     private static final @NonNull DataPutResult PUT_CREATED = new DataPutResult(true);
179     private static final @NonNull DataPutResult PUT_REPLACED = new DataPutResult(false);
180     private static final @NonNull DataPatchResult PATCH_EMPTY = new DataPatchResult();
181
182     private final @NonNull ImmutableMap<QName, RpcImplementation> localRpcs;
183     private final @NonNull ApiPathNormalizer pathNormalizer;
184     private final @NonNull DatabindContext databind;
185     private final YangTextSourceExtension sourceProvider;
186     private final DOMMountPointService mountPointService;
187     private final DOMActionService actionService;
188     private final DOMRpcService rpcService;
189     private final OperationsResource operations;
190
191     RestconfStrategy(final DatabindContext databind, final ImmutableMap<QName, RpcImplementation> localRpcs,
192             final @Nullable DOMRpcService rpcService, final @Nullable DOMActionService actionService,
193             final @Nullable YangTextSourceExtension sourceProvider,
194             final @Nullable DOMMountPointService mountPointService) {
195         this.databind = requireNonNull(databind);
196         this.localRpcs = requireNonNull(localRpcs);
197         this.rpcService = rpcService;
198         this.actionService = actionService;
199         this.sourceProvider = sourceProvider;
200         this.mountPointService = mountPointService;
201         pathNormalizer = new ApiPathNormalizer(databind);
202         operations = new OperationsResource(pathNormalizer);
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(), ImmutableMap.of(), rpcService,
262                 actionService, 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 QueryParams params,
332             final ResourceBody body) {
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.of(databind, params);
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<CreateResourceResult> 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<CreateResourceResult>();
511         Futures.addCallback(future, new FutureCallback<CommitInfo>() {
512             @Override
513             public void onSuccess(final CommitInfo result) {
514                 ret.set(new CreateResourceResult(new ApiPathCanonizer(databind).dataToApiPath(
515                     data instanceof MapNode mapData && !mapData.isEmpty()
516                         ? path.node(mapData.body().iterator().next().name()) : path)));
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 QueryParams params,
597             final PatchBody body) {
598         final DataYangPatchParams patchParams;
599         try {
600             patchParams = DataYangPatchParams.of(params);
601         } catch (IllegalArgumentException e) {
602             return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
603                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
604         }
605
606         final Data path;
607         try {
608             path = pathNormalizer.normalizeDataPath(apiPath);
609         } catch (RestconfDocumentedException e) {
610             return RestconfFuture.failed(e);
611         }
612
613         final PatchContext patch;
614         try {
615             patch = body.toPatchContext(new DefaultResourceContext(path));
616         } catch (IOException e) {
617             LOG.debug("Error parsing YANG Patch input", e);
618             return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
619                 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
620         }
621         return patchData(patchParams, patch);
622     }
623
624     /**
625      * Process edit operations of one {@link PatchContext}.
626      *
627      * @param patch Patch context to be processed
628      * @return {@link PatchStatusContext}
629      */
630     @VisibleForTesting
631     public final @NonNull RestconfFuture<DataYangPatchResult> patchData(final DataYangPatchParams params,
632             final PatchContext patch) {
633         final var editCollection = new ArrayList<PatchStatusEntity>();
634         final var tx = prepareWriteExecution();
635
636         boolean noError = true;
637         for (var patchEntity : patch.entities()) {
638             if (noError) {
639                 final var targetNode = patchEntity.getTargetNode();
640                 final var editId = patchEntity.getEditId();
641
642                 switch (patchEntity.getOperation()) {
643                     case Create:
644                         try {
645                             tx.create(targetNode, patchEntity.getNode());
646                             editCollection.add(new PatchStatusEntity(editId, true, null));
647                         } catch (RestconfDocumentedException e) {
648                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
649                             noError = false;
650                         }
651                         break;
652                     case Delete:
653                         try {
654                             tx.delete(targetNode);
655                             editCollection.add(new PatchStatusEntity(editId, true, null));
656                         } catch (RestconfDocumentedException e) {
657                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
658                             noError = false;
659                         }
660                         break;
661                     case Merge:
662                         try {
663                             tx.ensureParentsByMerge(targetNode);
664                             tx.merge(targetNode, patchEntity.getNode());
665                             editCollection.add(new PatchStatusEntity(editId, true, null));
666                         } catch (RestconfDocumentedException e) {
667                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
668                             noError = false;
669                         }
670                         break;
671                     case Replace:
672                         try {
673                             tx.replace(targetNode, patchEntity.getNode());
674                             editCollection.add(new PatchStatusEntity(editId, true, null));
675                         } catch (RestconfDocumentedException e) {
676                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
677                             noError = false;
678                         }
679                         break;
680                     case Remove:
681                         try {
682                             tx.remove(targetNode);
683                             editCollection.add(new PatchStatusEntity(editId, true, null));
684                         } catch (RestconfDocumentedException e) {
685                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
686                             noError = false;
687                         }
688                         break;
689                     default:
690                         editCollection.add(new PatchStatusEntity(editId, false, List.of(
691                             new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
692                                 "Not supported Yang Patch operation"))));
693                         noError = false;
694                         break;
695                 }
696             } else {
697                 break;
698             }
699         }
700
701         final var ret = new SettableRestconfFuture<DataYangPatchResult>();
702         // We have errors
703         if (!noError) {
704             tx.cancel();
705             ret.set(new DataYangPatchResult(params,
706                 new PatchStatusContext(databind(), patch.patchId(), List.copyOf(editCollection), false, null)));
707             return ret;
708         }
709
710         Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
711             @Override
712             public void onSuccess(final CommitInfo result) {
713                 ret.set(new DataYangPatchResult(params,
714                     new PatchStatusContext(databind(), patch.patchId(), List.copyOf(editCollection), true, null)));
715             }
716
717             @Override
718             public void onFailure(final Throwable cause) {
719                 // if errors occurred during transaction commit then patch failed and global errors are reported
720                 ret.set(new DataYangPatchResult(params,
721                     new PatchStatusContext(databind(), patch.patchId(), List.copyOf(editCollection), false,
722                         TransactionUtil.decodeException(cause, "PATCH", null, modelContext()).getErrors())));
723             }
724         }, MoreExecutors.directExecutor());
725
726         return ret;
727     }
728
729     private static void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
730             final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
731             final boolean before) {
732         tx.remove(path);
733
734         int lastItemPosition = 0;
735         for (var nodeChild : readList.body()) {
736             if (nodeChild.name().equals(pointArg)) {
737                 break;
738             }
739             lastItemPosition++;
740         }
741         if (!before) {
742             lastItemPosition++;
743         }
744
745         int lastInsertedPosition = 0;
746         for (var nodeChild : readList.body()) {
747             if (lastInsertedPosition == lastItemPosition) {
748                 tx.replace(path, data);
749             }
750             tx.replace(path.node(nodeChild.name()), nodeChild);
751             lastInsertedPosition++;
752         }
753
754         // In case we are inserting after last element
755         if (!before) {
756             if (lastInsertedPosition == lastItemPosition) {
757                 tx.replace(path, data);
758             }
759         }
760     }
761
762     private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
763             final YangInstanceIdentifier path, final NormalizedNode data) {
764         try {
765             tx.create(path, data);
766         } catch (RestconfDocumentedException e) {
767             // close transaction if any and pass exception further
768             tx.cancel();
769             throw e;
770         }
771
772         return tx.commit();
773     }
774
775     /**
776      * Check if child items do NOT already exists in List at specified {@code path}.
777      *
778      * @param data Data to be checked
779      * @param path Path to be checked
780      * @throws RestconfDocumentedException if data already exists.
781      */
782     private void checkListDataDoesNotExist(final YangInstanceIdentifier path, final NormalizedNode data) {
783         if (data instanceof NormalizedNodeContainer<?> dataNode) {
784             for (final var node : dataNode.body()) {
785                 checkItemDoesNotExists(exists(path.node(node.name())), path.node(node.name()));
786             }
787         } else {
788             throw new RestconfDocumentedException("Unexpected node type: " + data.getClass().getName());
789         }
790     }
791
792     /**
793      * Check if items do NOT already exists at specified {@code path}.
794      *
795      * @param existsFuture if checked data exists
796      * @param path         Path to be checked
797      * @throws RestconfDocumentedException if data already exists.
798      */
799     static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
800             final YangInstanceIdentifier path) {
801         if (TransactionUtil.syncAccess(existsFuture, path)) {
802             LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
803             throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
804                 path);
805         }
806     }
807
808     /**
809      * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
810      * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
811      *
812      * @param apiPath Path to delete
813      * @return A {@link RestconfFuture}
814      * @throws NullPointerException if {@code apiPath} is {@code null}
815      */
816     @SuppressWarnings("checkstyle:abbreviationAsWordInName")
817     public final @NonNull RestconfFuture<Empty> dataDELETE(final ApiPath apiPath) {
818         final Data path;
819         try {
820             path = pathNormalizer.normalizeDataPath(apiPath);
821         } catch (RestconfDocumentedException e) {
822             return RestconfFuture.failed(e);
823         }
824
825         // FIXME: reject empty YangInstanceIdentifier, as datastores may not be deleted
826         final var ret = new SettableRestconfFuture<Empty>();
827         delete(ret, path.instance());
828         return ret;
829     }
830
831     abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
832
833     public final @NonNull RestconfFuture<DataGetResult> dataGET(final ApiPath apiPath, final QueryParams params) {
834         final Data path;
835         try {
836             path = pathNormalizer.normalizeDataPath(apiPath);
837         } catch (RestconfDocumentedException e) {
838             return RestconfFuture.failed(e);
839         }
840
841         final DataGetParams getParams;
842         try {
843             getParams = DataGetParams.of(params);
844         } catch (IllegalArgumentException e) {
845             return RestconfFuture.failed(new RestconfDocumentedException(e,
846                 new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, "Invalid GET /data parameters", null,
847                     e.getMessage())));
848         }
849         return dataGET(path, getParams);
850     }
851
852     abstract @NonNull RestconfFuture<DataGetResult> dataGET(Data path, DataGetParams params);
853
854     static final @NonNull RestconfFuture<DataGetResult> completeDataGET(final Inference inference,
855             final WriterParameters writerParams, final @Nullable NormalizedNode node,
856             final @Nullable ConfigurationMetadata metadata) {
857         if (node == null) {
858             return RestconfFuture.failed(new RestconfDocumentedException(
859                 "Request could not be completed because the relevant data model content does not exist",
860                 ErrorType.PROTOCOL, ErrorTag.DATA_MISSING));
861         }
862
863         final var payload = new NormalizedNodePayload(inference, node, writerParams);
864         return RestconfFuture.of(metadata == null ? new DataGetResult(payload)
865             : new DataGetResult(payload, metadata.entityTag(), metadata.lastModified()));
866     }
867
868     /**
869      * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
870      * inside of object {@link RestconfStrategy} provided as a parameter.
871      *
872      * @param content      type of data to read (config, state, all)
873      * @param path         the path to read
874      * @param defaultsMode value of with-defaults parameter
875      * @return {@link NormalizedNode}
876      */
877     // FIXME: NETCONF-1155: this method should asynchronous
878     @VisibleForTesting
879     final @Nullable NormalizedNode readData(final @NonNull ContentParam content,
880             final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
881         return switch (content) {
882             case ALL -> {
883                 // PREPARE STATE DATA NODE
884                 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
885                 // PREPARE CONFIG DATA NODE
886                 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
887
888                 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
889                     : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
890             }
891             case CONFIG -> {
892                 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
893                 yield defaultsMode == null ? read
894                     : prepareDataByParamWithDef(read, path, defaultsMode.mode());
895             }
896             case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
897         };
898     }
899
900     private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
901             final YangInstanceIdentifier path) {
902         return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
903     }
904
905     final NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
906             final WithDefaultsMode defaultsMode) {
907         final boolean trim = switch (defaultsMode) {
908             case Trim -> true;
909             case Explicit -> false;
910             case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
911                 "Unsupported with-defaults value " + defaultsMode.getName());
912         };
913
914         // FIXME: we have this readily available in InstanceIdentifierContext
915         final var ctxNode = databind.schemaTree().findChild(path).orElseThrow();
916         if (readData instanceof ContainerNode container) {
917             final var builder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(container.name());
918             buildCont(builder, container.body(), ctxNode, trim);
919             return builder.build();
920         } else if (readData instanceof MapEntryNode mapEntry) {
921             if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
922                 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
923             }
924
925             final var builder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(mapEntry.name());
926             buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
927             return builder.build();
928         } else {
929             throw new IllegalStateException("Unhandled data contract " + readData.contract());
930         }
931     }
932
933     private static void buildMapEntryBuilder(
934             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
935             final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
936             final boolean trim, final List<QName> keys) {
937         for (var child : children) {
938             final var childCtx = getChildContext(ctxNode, child);
939
940             if (child instanceof ContainerNode container) {
941                 appendContainer(builder, container, childCtx, trim);
942             } else if (child instanceof MapNode map) {
943                 appendMap(builder, map, childCtx, trim);
944             } else if (child instanceof LeafNode<?> leaf) {
945                 appendLeaf(builder, leaf, childCtx, trim, keys);
946             } else {
947                 // FIXME: we should never hit this, throw an ISE if this ever happens
948                 LOG.debug("Ignoring unhandled child contract {}", child.contract());
949             }
950         }
951     }
952
953     private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
954             final DataSchemaContext ctxNode, final boolean trim) {
955         final var childBuilder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(container.name());
956         buildCont(childBuilder, container.body(), ctxNode, trim);
957         builder.withChild(childBuilder.build());
958     }
959
960     private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
961             final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
962         if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
963             throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
964         }
965
966         // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
967         final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
968
969         // This is a combined check for when we need to emit the leaf.
970         if (
971             // We always have to emit key leaf values
972             keys.contains(leafSchema.getQName())
973             // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
974             //
975             //            When data is retrieved with a <with-defaults> parameter equal to
976             //            'trim', data nodes MUST NOT be reported if they contain the schema
977             //            default value.  Non-configuration data nodes containing the schema
978             //            default value MUST NOT be reported.
979             //
980             || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
981             // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
982             // grasp what we are doing here... emit only if it matches default ???!!!
983             // FIXME: The WithDefaultsParam.EXPLICIT says:
984             //
985             //            Data nodes set to the YANG default by the client are reported.
986             //
987             //        and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
988             //
989             //            If the "with-defaults" parameter is set to "explicit", then the
990             //            server MUST adhere to the default-reporting behavior defined in
991             //            Section 3.3 of [RFC6243].
992             //
993             //        and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
994             //
995             //            When data is retrieved with a <with-defaults> parameter equal to
996             //            'explicit', a data node that was set by a client to its schema
997             //            default value MUST be reported.  A conceptual data node that would be
998             //            set by the server to the schema default value MUST NOT be reported.
999             //            Non-configuration data nodes containing the schema default value MUST
1000             //            be reported.
1001             //
1002             // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
1003             //            This seems to disregard the 'trim = true' case semantics (see above).
1004             //            Combining the above, though, these checks are missing the 'non-config' check, which would
1005             //            distinguish, but barring that this check is superfluous and results in the wrong semantics.
1006             //            Without that input, this really should be  covered by the previous case.
1007                 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
1008             builder.withChild(leaf);
1009         }
1010     }
1011
1012     private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
1013             final DataSchemaContext childCtx, final boolean trim) {
1014         if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
1015             throw new IllegalStateException("Input " + map + " does not match " + childCtx);
1016         }
1017
1018         final var childBuilder = switch (map.ordering()) {
1019             case SYSTEM -> ImmutableNodes.newSystemMapBuilder();
1020             case USER -> ImmutableNodes.newUserMapBuilder();
1021         };
1022         buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
1023             listSchema.getKeyDefinition());
1024         builder.withChild(childBuilder.build());
1025     }
1026
1027     private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
1028             final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
1029             final List<@NonNull QName> keys) {
1030         for (var entry : entries) {
1031             final var childCtx = getChildContext(ctxNode, entry);
1032             final var mapEntryBuilder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(entry.name());
1033             buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
1034             builder.withChild(mapEntryBuilder.build());
1035         }
1036     }
1037
1038     private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
1039             final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
1040         for (var child : children) {
1041             final var childCtx = getChildContext(ctxNode, child);
1042             if (child instanceof ContainerNode container) {
1043                 appendContainer(builder, container, childCtx, trim);
1044             } else if (child instanceof MapNode map) {
1045                 appendMap(builder, map, childCtx, trim);
1046             } else if (child instanceof LeafNode<?> leaf) {
1047                 appendLeaf(builder, leaf, childCtx, trim, List.of());
1048             }
1049         }
1050     }
1051
1052     private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
1053             final NormalizedNode child) {
1054         final var childId = child.name();
1055         final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
1056             : null;
1057         if (childCtx == null) {
1058             throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
1059         }
1060         return childCtx;
1061     }
1062
1063     static final NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
1064             final NormalizedNode configDataNode) {
1065         if (stateDataNode == null) {
1066             // No state, return config
1067             return configDataNode;
1068         }
1069         if (configDataNode == null) {
1070             // No config, return state
1071             return stateDataNode;
1072         }
1073         // merge config and state
1074         return mergeStateAndConfigData(stateDataNode, configDataNode);
1075     }
1076
1077     /**
1078      * Merge state and config data into a single NormalizedNode.
1079      *
1080      * @param stateDataNode  data node of state data
1081      * @param configDataNode data node of config data
1082      * @return {@link NormalizedNode}
1083      */
1084     private static @NonNull NormalizedNode mergeStateAndConfigData(
1085             final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
1086         validateNodeMerge(stateDataNode, configDataNode);
1087         // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
1088         if (configDataNode instanceof RpcDefinition) {
1089             return prepareRpcData(configDataNode, stateDataNode);
1090         } else {
1091             return prepareData(configDataNode, stateDataNode);
1092         }
1093     }
1094
1095     /**
1096      * Validates whether the two NormalizedNodes can be merged.
1097      *
1098      * @param stateDataNode  data node of state data
1099      * @param configDataNode data node of config data
1100      */
1101     private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
1102                                           final @NonNull NormalizedNode configDataNode) {
1103         final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
1104         final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
1105         if (!moduleOfStateData.equals(moduleOfConfigData)) {
1106             throw new RestconfDocumentedException("Unable to merge data from different modules.");
1107         }
1108     }
1109
1110     /**
1111      * Prepare and map data for rpc.
1112      *
1113      * @param configDataNode data node of config data
1114      * @param stateDataNode  data node of state data
1115      * @return {@link NormalizedNode}
1116      */
1117     private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
1118                                                           final @NonNull NormalizedNode stateDataNode) {
1119         final var mapEntryBuilder = ImmutableNodes.newMapEntryBuilder()
1120             .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
1121
1122         // MAP CONFIG DATA
1123         mapRpcDataNode(configDataNode, mapEntryBuilder);
1124         // MAP STATE DATA
1125         mapRpcDataNode(stateDataNode, mapEntryBuilder);
1126
1127         return ImmutableNodes.newSystemMapBuilder()
1128             .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
1129             .addChild(mapEntryBuilder.build())
1130             .build();
1131     }
1132
1133     /**
1134      * Map node to map entry builder.
1135      *
1136      * @param dataNode        data node
1137      * @param mapEntryBuilder builder for mapping data
1138      */
1139     private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
1140             final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
1141         ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
1142     }
1143
1144     /**
1145      * Prepare and map all data from DS.
1146      *
1147      * @param configDataNode data node of config data
1148      * @param stateDataNode  data node of state data
1149      * @return {@link NormalizedNode}
1150      */
1151     @SuppressWarnings("unchecked")
1152     private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
1153                                                        final @NonNull NormalizedNode stateDataNode) {
1154         if (configDataNode instanceof UserMapNode configMap) {
1155             final var builder = ImmutableNodes.newUserMapBuilder().withNodeIdentifier(configMap.name());
1156             mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
1157             return builder.build();
1158         } else if (configDataNode instanceof SystemMapNode configMap) {
1159             final var builder = ImmutableNodes.newSystemMapBuilder().withNodeIdentifier(configMap.name());
1160             mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
1161             return builder.build();
1162         } else if (configDataNode instanceof MapEntryNode configEntry) {
1163             final var builder = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(configEntry.name());
1164             mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
1165             return builder.build();
1166         } else if (configDataNode instanceof ContainerNode configContaienr) {
1167             final var builder = ImmutableNodes.newContainerBuilder().withNodeIdentifier(configContaienr.name());
1168             mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
1169             return builder.build();
1170         } else if (configDataNode instanceof ChoiceNode configChoice) {
1171             final var builder = ImmutableNodes.newChoiceBuilder().withNodeIdentifier(configChoice.name());
1172             mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
1173             return builder.build();
1174         } else if (configDataNode instanceof LeafNode configLeaf) {
1175             // config trumps oper
1176             return configLeaf;
1177         } else if (configDataNode instanceof UserLeafSetNode) {
1178             final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
1179             final var builder = ImmutableNodes.<Object>newUserLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
1180             mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
1181             return builder.build();
1182         } else if (configDataNode instanceof SystemLeafSetNode) {
1183             final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
1184             final var builder = ImmutableNodes.<Object>newSystemLeafSetBuilder()
1185                 .withNodeIdentifier(configLeafSet.name());
1186             mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
1187             return builder.build();
1188         } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
1189             // config trumps oper
1190             return configEntry;
1191         } else if (configDataNode instanceof UnkeyedListNode configList) {
1192             final var builder = ImmutableNodes.newUnkeyedListBuilder().withNodeIdentifier(configList.name());
1193             mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
1194             return builder.build();
1195         } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
1196             final var builder = ImmutableNodes.newUnkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
1197             mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
1198             return builder.build();
1199         } else {
1200             throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
1201         }
1202     }
1203
1204     /**
1205      * Map value from container node to builder.
1206      *
1207      * @param configData collection of config data nodes
1208      * @param stateData  collection of state data nodes
1209      * @param builder    builder
1210      */
1211     private static <T extends NormalizedNode> void mapValueToBuilder(
1212             final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1213             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1214         final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1215         final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1216
1217         // merge config and state data of children with different identifiers
1218         mapDataToBuilder(configMap, stateMap, builder);
1219
1220         // merge config and state data of children with the same identifiers
1221         mergeDataToBuilder(configMap, stateMap, builder);
1222     }
1223
1224     /**
1225      * Map data with different identifiers to builder. Data with different identifiers can be just added
1226      * as childs to parent node.
1227      *
1228      * @param configMap map of config data nodes
1229      * @param stateMap  map of state data nodes
1230      * @param builder   - builder
1231      */
1232     private static <T extends NormalizedNode> void mapDataToBuilder(
1233             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1234             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1235         configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1236             y -> builder.addChild(y.getValue()));
1237         stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1238             y -> builder.addChild(y.getValue()));
1239     }
1240
1241     /**
1242      * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1243      * go one level down with {@code prepareData} method.
1244      *
1245      * @param configMap immutable config data
1246      * @param stateMap  immutable state data
1247      * @param builder   - builder
1248      */
1249     @SuppressWarnings("unchecked")
1250     private static <T extends NormalizedNode> void mergeDataToBuilder(
1251             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1252             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1253         // it is enough to process only config data because operational contains the same data
1254         configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1255             y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1256     }
1257
1258     public @NonNull RestconfFuture<FormattableBody> operationsGET() {
1259         return operations.httpGET();
1260     }
1261
1262     public @NonNull RestconfFuture<FormattableBody> operationsGET(final ApiPath apiPath) {
1263         return operations.httpGET(apiPath);
1264     }
1265
1266     public @NonNull RestconfFuture<InvokeResult> operationsPOST(final URI restconfURI, final ApiPath apiPath,
1267             final QueryParams params, final OperationInputBody body) {
1268         final Rpc path;
1269         try {
1270             path = pathNormalizer.normalizeRpcPath(apiPath);
1271         } catch (RestconfDocumentedException e) {
1272             return RestconfFuture.failed(e);
1273         }
1274
1275         final InvokeParams invokeParams;
1276         try {
1277             invokeParams = InvokeParams.of(params);
1278         } catch (IllegalArgumentException e) {
1279             return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
1280                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
1281         }
1282
1283         final ContainerNode data;
1284         try {
1285             data = body.toContainerNode(path);
1286         } catch (IOException e) {
1287             LOG.debug("Error reading input", e);
1288             return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1289                 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1290         }
1291
1292         final var type = path.rpc().argument();
1293         final var local = localRpcs.get(type);
1294         if (local != null) {
1295             return local.invoke(restconfURI, new OperationInput(path, data))
1296                 .transform(output -> outputToInvokeResult(path, invokeParams, output));
1297         }
1298         if (rpcService == null) {
1299             LOG.debug("RPC invocation is not available");
1300             return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1301                 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1302         }
1303
1304         final var ret = new SettableRestconfFuture<InvokeResult>();
1305         Futures.addCallback(rpcService.invokeRpc(type, data), new FutureCallback<DOMRpcResult>() {
1306             @Override
1307             public void onSuccess(final DOMRpcResult response) {
1308                 final var errors = response.errors();
1309                 if (errors.isEmpty()) {
1310                     ret.set(outputToInvokeResult(path, invokeParams, response.value()));
1311                 } else {
1312                     LOG.debug("RPC invocation reported {}", response.errors());
1313                     ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1314                         response.errors()));
1315                 }
1316             }
1317
1318             @Override
1319             public void onFailure(final Throwable cause) {
1320                 LOG.debug("RPC invocation failed, cause");
1321                 if (cause instanceof RestconfDocumentedException ex) {
1322                     ret.setFailure(ex);
1323                 } else {
1324                     // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1325                     ret.setFailure(new RestconfDocumentedException(cause,
1326                         new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1327                 }
1328             }
1329         }, MoreExecutors.directExecutor());
1330         return ret;
1331     }
1332
1333     private static @NonNull InvokeResult outputToInvokeResult(final @NonNull OperationPath path,
1334             final @NonNull InvokeParams params, final @Nullable ContainerNode value) {
1335         return value == null || value.isEmpty() ? InvokeResult.EMPTY
1336             : new InvokeResult(new OperationOutputBody(params, path, value));
1337     }
1338
1339     public @NonNull RestconfFuture<CharSource> resolveSource(final SourceIdentifier source,
1340             final Class<? extends SourceRepresentation> representation) {
1341         final var src = requireNonNull(source);
1342         if (YangTextSource.class.isAssignableFrom(representation)) {
1343             if (sourceProvider != null) {
1344                 final var ret = new SettableRestconfFuture<CharSource>();
1345                 Futures.addCallback(sourceProvider.getYangTexttSource(src), new FutureCallback<>() {
1346                     @Override
1347                     public void onSuccess(final YangTextSource result) {
1348                         ret.set(result);
1349                     }
1350
1351                     @Override
1352                     public void onFailure(final Throwable cause) {
1353                         ret.setFailure(cause instanceof RestconfDocumentedException e ? e
1354                             : new RestconfDocumentedException(cause.getMessage(), ErrorType.RPC,
1355                                 ErrorTag.OPERATION_FAILED, cause));
1356                     }
1357                 }, MoreExecutors.directExecutor());
1358                 return ret;
1359             }
1360             return exportSource(modelContext(), src, YangCharSource::new, YangCharSource::new);
1361         }
1362         if (YinTextSource.class.isAssignableFrom(representation)) {
1363             return exportSource(modelContext(), src, YinCharSource.OfModule::new, YinCharSource.OfSubmodule::new);
1364         }
1365         return RestconfFuture.failed(new RestconfDocumentedException(
1366             "Unsupported source representation " + representation.getName()));
1367     }
1368
1369     private static @NonNull RestconfFuture<CharSource> exportSource(final EffectiveModelContext modelContext,
1370             final SourceIdentifier source, final Function<ModuleEffectiveStatement, CharSource> moduleCtor,
1371             final BiFunction<ModuleEffectiveStatement, SubmoduleEffectiveStatement, CharSource> submoduleCtor) {
1372         // If the source identifies a module, things are easy
1373         final var name = source.name().getLocalName();
1374         final var optRevision = Optional.ofNullable(source.revision());
1375         final var optModule = modelContext.findModule(name, optRevision);
1376         if (optModule.isPresent()) {
1377             return RestconfFuture.of(moduleCtor.apply(optModule.orElseThrow().asEffectiveStatement()));
1378         }
1379
1380         // The source could be a submodule, which we need to hunt down
1381         for (var module : modelContext.getModules()) {
1382             for (var submodule : module.getSubmodules()) {
1383                 if (name.equals(submodule.getName()) && optRevision.equals(submodule.getRevision())) {
1384                     return RestconfFuture.of(submoduleCtor.apply(module.asEffectiveStatement(),
1385                         submodule.asEffectiveStatement()));
1386                 }
1387             }
1388         }
1389
1390         final var sb = new StringBuilder().append("Source ").append(source.name().getLocalName());
1391         optRevision.ifPresent(rev -> sb.append('@').append(rev));
1392         sb.append(" not found");
1393         return RestconfFuture.failed(new RestconfDocumentedException(sb.toString(),
1394             ErrorType.APPLICATION, ErrorTag.DATA_MISSING));
1395     }
1396
1397     public final @NonNull RestconfFuture<? extends DataPostResult> dataPOST(final ApiPath apiPath,
1398             final QueryParams params, final DataPostBody body) {
1399         if (apiPath.steps().isEmpty()) {
1400             return dataCreatePOST(params, body.toResource());
1401         }
1402         final InstanceReference path;
1403         try {
1404             path = pathNormalizer.normalizeDataOrActionPath(apiPath);
1405         } catch (RestconfDocumentedException e) {
1406             return RestconfFuture.failed(e);
1407         }
1408         if (path instanceof Data dataPath) {
1409             try (var resourceBody = body.toResource()) {
1410                 return dataCreatePOST(dataPath, params, resourceBody);
1411             }
1412         }
1413         if (path instanceof Action actionPath) {
1414             try (var inputBody = body.toOperationInput()) {
1415                 return dataInvokePOST(actionPath, params, inputBody);
1416             }
1417         }
1418         // Note: this should never happen
1419         // FIXME: we should be able to eliminate this path with Java 21+ pattern matching
1420         return RestconfFuture.failed(new RestconfDocumentedException("Unhandled path " + path));
1421     }
1422
1423     public @NonNull RestconfFuture<CreateResourceResult> dataCreatePOST(final QueryParams params,
1424             final ChildBody body) {
1425         return dataCreatePOST(new DatabindPath.Data(databind), params, body);
1426     }
1427
1428     private @NonNull RestconfFuture<CreateResourceResult> dataCreatePOST(final DatabindPath.Data path,
1429             final QueryParams params, final ChildBody body) {
1430         final Insert insert;
1431         try {
1432             insert = Insert.of(path.databind(), params);
1433         } catch (IllegalArgumentException e) {
1434             return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
1435                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
1436         }
1437
1438         final var payload = body.toPayload(path);
1439         return postData(concat(path.instance(), payload.prefix()), payload.body(), insert);
1440     }
1441
1442     private static YangInstanceIdentifier concat(final YangInstanceIdentifier parent, final List<PathArgument> args) {
1443         var ret = parent;
1444         for (var arg : args) {
1445             ret = ret.node(arg);
1446         }
1447         return ret;
1448     }
1449
1450     private @NonNull RestconfFuture<InvokeResult> dataInvokePOST(final @NonNull Action path,
1451             final @NonNull QueryParams params, final @NonNull OperationInputBody body) {
1452         final InvokeParams invokeParams;
1453         try {
1454             invokeParams = InvokeParams.of(params);
1455         } catch (IllegalArgumentException e) {
1456             return RestconfFuture.failed(new RestconfDocumentedException(e.getMessage(),
1457                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e));
1458         }
1459
1460         final ContainerNode input;
1461         try {
1462             input = body.toContainerNode(path);
1463         } catch (IOException e) {
1464             LOG.debug("Error reading input", e);
1465             return RestconfFuture.failed(new RestconfDocumentedException("Error parsing input: " + e.getMessage(),
1466                 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, e));
1467         }
1468
1469         if (actionService == null) {
1470             return RestconfFuture.failed(new RestconfDocumentedException("DOMActionService is missing."));
1471         }
1472
1473         return dataInvokePOST(actionService, path, input)
1474             .transform(result -> outputToInvokeResult(path, invokeParams, result.getOutput().orElse(null)));
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 }