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