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