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