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