Eliminate DOMDatabindProvider
[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.collect.ImmutableMap;
14 import com.google.common.io.CharSource;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import com.google.common.util.concurrent.ListenableFuture;
18 import com.google.common.util.concurrent.MoreExecutors;
19 import java.net.URI;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.NoSuchElementException;
25 import java.util.Optional;
26 import java.util.function.BiFunction;
27 import java.util.function.Function;
28 import java.util.stream.Collectors;
29 import org.eclipse.jdt.annotation.NonNull;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.opendaylight.mdsal.common.api.CommitInfo;
32 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
33 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
34 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
35 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
36 import org.opendaylight.mdsal.dom.api.DOMRpcService;
37 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
38 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
39 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
40 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
41 import org.opendaylight.restconf.api.query.ContentParam;
42 import org.opendaylight.restconf.api.query.WithDefaultsParam;
43 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
44 import org.opendaylight.restconf.common.errors.RestconfError;
45 import org.opendaylight.restconf.common.errors.RestconfFuture;
46 import org.opendaylight.restconf.common.errors.SettableRestconfFuture;
47 import org.opendaylight.restconf.common.patch.PatchContext;
48 import org.opendaylight.restconf.common.patch.PatchStatusContext;
49 import org.opendaylight.restconf.common.patch.PatchStatusEntity;
50 import org.opendaylight.restconf.nb.rfc8040.Insert;
51 import org.opendaylight.restconf.nb.rfc8040.databind.DatabindContext;
52 import org.opendaylight.restconf.nb.rfc8040.utils.parser.IdentifierCodec;
53 import org.opendaylight.restconf.server.api.DataPostResult.CreateResource;
54 import org.opendaylight.restconf.server.api.DataPutResult;
55 import org.opendaylight.restconf.server.spi.OperationInput;
56 import org.opendaylight.restconf.server.spi.OperationOutput;
57 import org.opendaylight.restconf.server.spi.RpcImplementation;
58 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.with.defaults.rev110601.WithDefaultsMode;
59 import org.opendaylight.yangtools.yang.common.Empty;
60 import org.opendaylight.yangtools.yang.common.ErrorTag;
61 import org.opendaylight.yangtools.yang.common.ErrorType;
62 import org.opendaylight.yangtools.yang.common.QName;
63 import org.opendaylight.yangtools.yang.common.QNameModule;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
68 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
71 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
76 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
77 import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
79 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
80 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
81 import org.opendaylight.yangtools.yang.data.api.schema.UserLeafSetNode;
82 import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
83 import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
84 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
85 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
86 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
87 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
88 import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
89 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
91 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
95 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
96 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleEffectiveStatement;
97 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
98 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
99 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
100 import org.opendaylight.yangtools.yang.model.repo.api.YinTextSchemaSource;
101 import org.slf4j.Logger;
102 import org.slf4j.LoggerFactory;
103
104 /**
105  * Baseline execution strategy for various RESTCONF operations.
106  *
107  * @see NetconfRestconfStrategy
108  * @see MdsalRestconfStrategy
109  */
110 // FIXME: it seems the first three operations deal with lifecycle of a transaction, while others invoke various
111 //        operations. This should be handled through proper allocation indirection.
112 public abstract class RestconfStrategy {
113     private static final Logger LOG = LoggerFactory.getLogger(RestconfStrategy.class);
114
115     private final @NonNull DatabindContext databind;
116     private final @NonNull ImmutableMap<QName, RpcImplementation> localRpcs;
117     private final DOMYangTextSourceProvider sourceProvider;
118     private final DOMRpcService rpcService;
119
120     RestconfStrategy(final EffectiveModelContext modelContext, final ImmutableMap<QName, RpcImplementation> localRpcs,
121             final @Nullable DOMRpcService rpcService, final DOMYangTextSourceProvider sourceProvider) {
122         // FIXME: pass this down
123         databind = DatabindContext.ofModel(modelContext);
124         this.localRpcs = requireNonNull(localRpcs);
125         this.rpcService = rpcService;
126         this.sourceProvider = sourceProvider;
127     }
128
129     /**
130      * Look up the appropriate strategy for a particular mount point.
131      *
132      * @param modelContext {@link EffectiveModelContext} of target mount point
133      * @param mountPoint Target mount point
134      * @return A strategy, or null if the mount point does not expose a supported interface
135      * @throws NullPointerException if any argument is {@code null}
136      */
137     public static @Nullable RestconfStrategy forMountPoint(final EffectiveModelContext modelContext,
138             final DOMMountPoint mountPoint) {
139         final var rpcService = mountPoint.getService(DOMRpcService.class).orElse(null);
140         final var sourceProvider = mountPoint.getService(DOMSchemaService.class)
141             .flatMap(schema -> Optional.ofNullable(schema.getExtensions().getInstance(DOMYangTextSourceProvider.class)))
142             .orElse(null);
143
144         final var netconfService = mountPoint.getService(NetconfDataTreeService.class);
145         if (netconfService.isPresent()) {
146             return new NetconfRestconfStrategy(modelContext, netconfService.orElseThrow(), rpcService, sourceProvider);
147         }
148         final var dataBroker = mountPoint.getService(DOMDataBroker.class);
149         if (dataBroker.isPresent()) {
150             return new MdsalRestconfStrategy(modelContext, dataBroker.orElseThrow(), rpcService, sourceProvider);
151         }
152         return null;
153     }
154
155     public final @NonNull DatabindContext databind() {
156         return databind;
157     }
158
159     public final @NonNull EffectiveModelContext modelContext() {
160         return databind.modelContext();
161     }
162
163     /**
164      * Lock the entire datastore.
165      *
166      * @return A {@link RestconfTransaction}. This transaction needs to be either committed or canceled before doing
167      *         anything else.
168      */
169     abstract RestconfTransaction prepareWriteExecution();
170
171     /**
172      * Read data from the datastore.
173      *
174      * @param store the logical data store which should be modified
175      * @param path the data object path
176      * @return a ListenableFuture containing the result of the read
177      */
178     abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path);
179
180     /**
181      * Read data selected using fields from the datastore.
182      *
183      * @param store the logical data store which should be modified
184      * @param path the parent data object path
185      * @param fields paths to selected fields relative to parent path
186      * @return a ListenableFuture containing the result of the read
187      */
188     abstract ListenableFuture<Optional<NormalizedNode>> read(LogicalDatastoreType store, YangInstanceIdentifier path,
189         List<YangInstanceIdentifier> fields);
190
191     /**
192      * Check if data already exists in the configuration datastore.
193      *
194      * @param path the data object path
195      * @return a ListenableFuture containing the result of the check
196      */
197     // FIXME: this method should be hosted in RestconfTransaction
198     // FIXME: this method should only be needed in MdsalRestconfStrategy
199     abstract ListenableFuture<Boolean> exists(YangInstanceIdentifier path);
200
201     /**
202      * Delete data from the configuration datastore. If the data does not exist, this operation will fail, as outlined
203      * in <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.7">RFC8040 section 4.7</a>
204      *
205      * @param path Path to delete
206      * @return A {@link RestconfFuture}
207      * @throws NullPointerException if {@code path} is {@code null}
208      */
209     public final @NonNull RestconfFuture<Empty> delete(final YangInstanceIdentifier path) {
210         final var ret = new SettableRestconfFuture<Empty>();
211         delete(ret, requireNonNull(path));
212         return ret;
213     }
214
215     abstract void delete(@NonNull SettableRestconfFuture<Empty> future, @NonNull YangInstanceIdentifier path);
216
217     /**
218      * Merge data into the configuration datastore, as outlined in
219      * <a href="https://www.rfc-editor.org/rfc/rfc8040#section-4.6.1">RFC8040 section 4.6.1</a>.
220      *
221      * @param path Path to merge
222      * @param data Data to merge
223      * @return A {@link RestconfFuture}
224      * @throws NullPointerException if any argument is {@code null}
225      */
226     public final @NonNull RestconfFuture<Empty> merge(final YangInstanceIdentifier path, final NormalizedNode data) {
227         final var ret = new SettableRestconfFuture<Empty>();
228         merge(ret, requireNonNull(path), requireNonNull(data));
229         return ret;
230     }
231
232     private void merge(final @NonNull SettableRestconfFuture<Empty> future, final @NonNull YangInstanceIdentifier path,
233             final @NonNull NormalizedNode data) {
234         final var tx = prepareWriteExecution();
235         // FIXME: this method should be further specialized to eliminate this call -- it is only needed for MD-SAL
236         tx.ensureParentsByMerge(path);
237         tx.merge(path, data);
238         Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
239             @Override
240             public void onSuccess(final CommitInfo result) {
241                 future.set(Empty.value());
242             }
243
244             @Override
245             public void onFailure(final Throwable cause) {
246                 future.setFailure(TransactionUtil.decodeException(cause, "MERGE", path, modelContext()));
247             }
248         }, MoreExecutors.directExecutor());
249     }
250
251     /**
252      * Check mount point and prepare variables for put data to DS.
253      *
254      * @param path    path of data
255      * @param data    data
256      * @param insert  {@link Insert}
257      * @return A {@link DataPutResult}
258      */
259     public final RestconfFuture<DataPutResult> putData(final YangInstanceIdentifier path,
260             final NormalizedNode data, final @Nullable Insert insert) {
261         final var exists = TransactionUtil.syncAccess(exists(path), path);
262
263         final ListenableFuture<? extends CommitInfo> commitFuture;
264         if (insert != null) {
265             final var parentPath = path.coerceParent();
266             checkListAndOrderedType(parentPath);
267             commitFuture = insertAndCommitPut(path, data, insert, parentPath);
268         } else {
269             commitFuture = replaceAndCommit(prepareWriteExecution(), path, data);
270         }
271
272         final var ret = new SettableRestconfFuture<DataPutResult>();
273
274         Futures.addCallback(commitFuture, new FutureCallback<CommitInfo>() {
275             @Override
276             public void onSuccess(final CommitInfo result) {
277                 ret.set(exists ? DataPutResult.REPLACED : DataPutResult.CREATED);
278             }
279
280             @Override
281             public void onFailure(final Throwable cause) {
282                 ret.setFailure(TransactionUtil.decodeException(cause, "PUT", path, modelContext()));
283             }
284         }, MoreExecutors.directExecutor());
285
286         return ret;
287     }
288
289     private ListenableFuture<? extends CommitInfo> insertAndCommitPut(final YangInstanceIdentifier path,
290             final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parentPath) {
291         final var tx = prepareWriteExecution();
292
293         return switch (insert.insert()) {
294             case FIRST -> {
295                 final var readData = tx.readList(parentPath);
296                 if (readData == null || readData.isEmpty()) {
297                     yield replaceAndCommit(tx, path, data);
298                 }
299                 tx.remove(parentPath);
300                 tx.replace(path, data);
301                 tx.replace(parentPath, readData);
302                 yield tx.commit();
303             }
304             case LAST -> replaceAndCommit(tx, path, data);
305             case BEFORE -> {
306                 final var readData = tx.readList(parentPath);
307                 if (readData == null || readData.isEmpty()) {
308                     yield replaceAndCommit(tx, path, data);
309                 }
310                 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, true);
311                 yield tx.commit();
312             }
313             case AFTER -> {
314                 final var readData = tx.readList(parentPath);
315                 if (readData == null || readData.isEmpty()) {
316                     yield replaceAndCommit(tx, path, data);
317                 }
318                 insertWithPointPut(tx, path, data, verifyNotNull(insert.pointArg()), readData, false);
319                 yield tx.commit();
320             }
321         };
322     }
323
324     private void insertWithPointPut(final RestconfTransaction tx, final YangInstanceIdentifier path,
325             final NormalizedNode data, final @NonNull PathArgument pointArg, final NormalizedNodeContainer<?> readList,
326             final boolean before) {
327         tx.remove(path.getParent());
328
329         int lastItemPosition = 0;
330         for (var nodeChild : readList.body()) {
331             if (nodeChild.name().equals(pointArg)) {
332                 break;
333             }
334             lastItemPosition++;
335         }
336         if (!before) {
337             lastItemPosition++;
338         }
339
340         int lastInsertedPosition = 0;
341         final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext(), path.getParent());
342         tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
343         for (var nodeChild : readList.body()) {
344             if (lastInsertedPosition == lastItemPosition) {
345                 tx.replace(path, data);
346             }
347             final var childPath = path.coerceParent().node(nodeChild.name());
348             tx.replace(childPath, nodeChild);
349             lastInsertedPosition++;
350         }
351     }
352
353     private static ListenableFuture<? extends CommitInfo> replaceAndCommit(final RestconfTransaction tx,
354             final YangInstanceIdentifier path, final NormalizedNode data) {
355         tx.replace(path, data);
356         return tx.commit();
357     }
358
359     private DataSchemaNode checkListAndOrderedType(final YangInstanceIdentifier path) {
360         // FIXME: we have this available in InstanceIdentifierContext
361         final var dataSchemaNode = databind.schemaTree().findChild(path).orElseThrow().dataSchemaNode();
362
363         final String message;
364         if (dataSchemaNode instanceof ListSchemaNode listSchema) {
365             if (listSchema.isUserOrdered()) {
366                 return listSchema;
367             }
368             message = "Insert parameter can be used only with ordered-by user list.";
369         } else if (dataSchemaNode instanceof LeafListSchemaNode leafListSchema) {
370             if (leafListSchema.isUserOrdered()) {
371                 return leafListSchema;
372             }
373             message = "Insert parameter can be used only with ordered-by user leaf-list.";
374         } else {
375             message = "Insert parameter can be used only with list or leaf-list";
376         }
377         throw new RestconfDocumentedException(message, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT);
378     }
379
380     /**
381      * Check mount point and prepare variables for post data.
382      *
383      * @param path    path
384      * @param data    data
385      * @param insert  {@link Insert}
386      * @return A {@link RestconfFuture}
387      */
388     public final @NonNull RestconfFuture<CreateResource> postData(final YangInstanceIdentifier path,
389             final NormalizedNode data, final @Nullable Insert insert) {
390         final ListenableFuture<? extends CommitInfo> future;
391         if (insert != null) {
392             final var parentPath = path.coerceParent();
393             checkListAndOrderedType(parentPath);
394             future = insertAndCommitPost(path, data, insert, parentPath);
395         } else {
396             future = createAndCommit(prepareWriteExecution(), path, data);
397         }
398
399         final var ret = new SettableRestconfFuture<CreateResource>();
400         Futures.addCallback(future, new FutureCallback<CommitInfo>() {
401             @Override
402             public void onSuccess(final CommitInfo result) {
403                 ret.set(new CreateResource(IdentifierCodec.serialize(
404                     data instanceof MapNode mapData && !mapData.isEmpty()
405                         ? path.node(mapData.body().iterator().next().name()) : path,
406                     modelContext())));
407             }
408
409             @Override
410             public void onFailure(final Throwable cause) {
411                 ret.setFailure(TransactionUtil.decodeException(cause, "POST", path, modelContext()));
412             }
413
414         }, MoreExecutors.directExecutor());
415         return ret;
416     }
417
418     private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
419             final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parent) {
420         final var grandParent = parent.coerceParent();
421         final var tx = prepareWriteExecution();
422
423         return switch (insert.insert()) {
424             case FIRST -> {
425                 final var readData = tx.readList(grandParent);
426                 if (readData == null || readData.isEmpty()) {
427                     tx.replace(path, data);
428                 } else {
429                     checkItemDoesNotExists(exists(path), path);
430                     tx.remove(grandParent);
431                     tx.replace(path, data);
432                     tx.replace(grandParent, readData);
433                 }
434                 yield tx.commit();
435             }
436             case LAST -> createAndCommit(tx, path, data);
437             case BEFORE -> {
438                 final var readData = tx.readList(grandParent);
439                 if (readData == null || readData.isEmpty()) {
440                     tx.replace(path, data);
441                 } else {
442                     checkItemDoesNotExists(exists(path), path);
443                     insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, true);
444                 }
445                 yield tx.commit();
446             }
447             case AFTER -> {
448                 final var readData = tx.readList(grandParent);
449                 if (readData == null || readData.isEmpty()) {
450                     tx.replace(path, data);
451                 } else {
452                     checkItemDoesNotExists(exists(path), path);
453                     insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, false);
454                 }
455                 yield tx.commit();
456             }
457         };
458     }
459
460     /**
461      * Process edit operations of one {@link PatchContext}.
462      *
463      * @param patch Patch context to be processed
464      * @return {@link PatchStatusContext}
465      */
466     public final @NonNull RestconfFuture<PatchStatusContext> patchData(final PatchContext patch) {
467         final var editCollection = new ArrayList<PatchStatusEntity>();
468         final var tx = prepareWriteExecution();
469
470         boolean noError = true;
471         for (var patchEntity : patch.entities()) {
472             if (noError) {
473                 final var targetNode = patchEntity.getTargetNode();
474                 final var editId = patchEntity.getEditId();
475
476                 switch (patchEntity.getOperation()) {
477                     case Create:
478                         try {
479                             tx.create(targetNode, patchEntity.getNode());
480                             editCollection.add(new PatchStatusEntity(editId, true, null));
481                         } catch (RestconfDocumentedException e) {
482                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
483                             noError = false;
484                         }
485                         break;
486                     case Delete:
487                         try {
488                             tx.delete(targetNode);
489                             editCollection.add(new PatchStatusEntity(editId, true, null));
490                         } catch (RestconfDocumentedException e) {
491                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
492                             noError = false;
493                         }
494                         break;
495                     case Merge:
496                         try {
497                             tx.ensureParentsByMerge(targetNode);
498                             tx.merge(targetNode, patchEntity.getNode());
499                             editCollection.add(new PatchStatusEntity(editId, true, null));
500                         } catch (RestconfDocumentedException e) {
501                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
502                             noError = false;
503                         }
504                         break;
505                     case Replace:
506                         try {
507                             tx.replace(targetNode, patchEntity.getNode());
508                             editCollection.add(new PatchStatusEntity(editId, true, null));
509                         } catch (RestconfDocumentedException e) {
510                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
511                             noError = false;
512                         }
513                         break;
514                     case Remove:
515                         try {
516                             tx.remove(targetNode);
517                             editCollection.add(new PatchStatusEntity(editId, true, null));
518                         } catch (RestconfDocumentedException e) {
519                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
520                             noError = false;
521                         }
522                         break;
523                     default:
524                         editCollection.add(new PatchStatusEntity(editId, false, List.of(
525                             new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
526                                 "Not supported Yang Patch operation"))));
527                         noError = false;
528                         break;
529                 }
530             } else {
531                 break;
532             }
533         }
534
535         final var ret = new SettableRestconfFuture<PatchStatusContext>();
536         // We have errors
537         if (!noError) {
538             tx.cancel();
539             ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false, null));
540             return ret;
541         }
542
543         Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
544             @Override
545             public void onSuccess(final CommitInfo result) {
546                 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), true,
547                     null));
548             }
549
550             @Override
551             public void onFailure(final Throwable cause) {
552                 // if errors occurred during transaction commit then patch failed and global errors are reported
553                 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false,
554                     TransactionUtil.decodeException(cause, "PATCH", null, modelContext()).getErrors()));
555             }
556         }, MoreExecutors.directExecutor());
557
558         return ret;
559     }
560
561     private void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
562             final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
563             final YangInstanceIdentifier grandParentPath, final boolean before) {
564         tx.remove(grandParentPath);
565
566         int lastItemPosition = 0;
567         for (var nodeChild : readList.body()) {
568             if (nodeChild.name().equals(pointArg)) {
569                 break;
570             }
571             lastItemPosition++;
572         }
573         if (!before) {
574             lastItemPosition++;
575         }
576
577         int lastInsertedPosition = 0;
578         final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext(), grandParentPath);
579         tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
580         for (var nodeChild : readList.body()) {
581             if (lastInsertedPosition == lastItemPosition) {
582                 tx.replace(path, data);
583             }
584             tx.replace(grandParentPath.node(nodeChild.name()), nodeChild);
585             lastInsertedPosition++;
586         }
587     }
588
589     private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
590             final YangInstanceIdentifier path, final NormalizedNode data) {
591         try {
592             tx.create(path, data);
593         } catch (RestconfDocumentedException e) {
594             // close transaction if any and pass exception further
595             tx.cancel();
596             throw e;
597         }
598
599         return tx.commit();
600     }
601
602     /**
603      * Check if items do NOT already exists at specified {@code path}.
604      *
605      * @param existsFuture if checked data exists
606      * @param path         Path to be checked
607      * @throws RestconfDocumentedException if data already exists.
608      */
609     static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
610             final YangInstanceIdentifier path) {
611         if (TransactionUtil.syncAccess(existsFuture, path)) {
612             LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
613             throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
614                 path);
615         }
616     }
617
618     /**
619      * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
620      * inside of object {@link RestconfStrategy} provided as a parameter.
621      *
622      * @param content      type of data to read (config, state, all)
623      * @param path         the path to read
624      * @param defaultsMode value of with-defaults parameter
625      * @return {@link NormalizedNode}
626      */
627     // FIXME: NETCONF-1155: this method should asynchronous
628     public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
629             final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
630         return switch (content) {
631             case ALL -> {
632                 // PREPARE STATE DATA NODE
633                 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
634                 // PREPARE CONFIG DATA NODE
635                 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
636
637                 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
638                     : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
639             }
640             case CONFIG -> {
641                 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
642                 yield defaultsMode == null ? read
643                     : prepareDataByParamWithDef(read, path, defaultsMode.mode());
644             }
645             case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
646         };
647     }
648
649     /**
650      * Read specific type of data from data store via transaction with specified subtrees that should only be read.
651      * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
652      *
653      * @param content  type of data to read (config, state, all)
654      * @param path     the parent path to read
655      * @param withDefa value of with-defaults parameter
656      * @param fields   paths to selected subtrees which should be read, relative to to the parent path
657      * @return {@link NormalizedNode}
658      */
659     // FIXME: NETCONF-1155: this method should asynchronous
660     public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
661             final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParam withDefa,
662             final @NonNull List<YangInstanceIdentifier> fields) {
663         return switch (content) {
664             case ALL -> {
665                 // PREPARE STATE DATA NODE
666                 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
667                 // PREPARE CONFIG DATA NODE
668                 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
669
670                 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, withDefa == null ? configDataNode
671                     : prepareDataByParamWithDef(configDataNode, path, withDefa.mode()));
672             }
673             case CONFIG -> {
674                 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
675                 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa.mode());
676             }
677             case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
678         };
679     }
680
681     private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
682             final YangInstanceIdentifier path) {
683         return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
684     }
685
686     /**
687      * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
688      * specified subtrees that should only be read.
689      *
690      * @param store                 datastore type
691      * @param path                  parent path to selected fields
692      * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
693      *                              in {@link RestconfStrategy} if any
694      * @param fields                paths to selected subtrees which should be read, relative to to the parent path
695      * @return {@link NormalizedNode}
696      */
697     private @Nullable NormalizedNode readDataViaTransaction(final @NonNull LogicalDatastoreType store,
698             final @NonNull YangInstanceIdentifier path, final @NonNull List<YangInstanceIdentifier> fields) {
699         return TransactionUtil.syncAccess(read(store, path, fields), path).orElse(null);
700     }
701
702     private NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
703             final WithDefaultsMode defaultsMode) {
704         final boolean trim = switch (defaultsMode) {
705             case Trim -> true;
706             case Explicit -> false;
707             case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
708                 "Unsupported with-defaults value " + defaultsMode.getName());
709         };
710
711         // FIXME: we have this readily available in InstanceIdentifierContext
712         final var ctxNode = databind.schemaTree().findChild(path).orElseThrow();
713         if (readData instanceof ContainerNode container) {
714             final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
715             buildCont(builder, container.body(), ctxNode, trim);
716             return builder.build();
717         } else if (readData instanceof MapEntryNode mapEntry) {
718             if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
719                 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
720             }
721
722             final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
723             buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
724             return builder.build();
725         } else {
726             throw new IllegalStateException("Unhandled data contract " + readData.contract());
727         }
728     }
729
730     private static void buildMapEntryBuilder(
731             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
732             final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
733             final boolean trim, final List<QName> keys) {
734         for (var child : children) {
735             final var childCtx = getChildContext(ctxNode, child);
736
737             if (child instanceof ContainerNode container) {
738                 appendContainer(builder, container, childCtx, trim);
739             } else if (child instanceof MapNode map) {
740                 appendMap(builder, map, childCtx, trim);
741             } else if (child instanceof LeafNode<?> leaf) {
742                 appendLeaf(builder, leaf, childCtx, trim, keys);
743             } else {
744                 // FIXME: we should never hit this, throw an ISE if this ever happens
745                 LOG.debug("Ignoring unhandled child contract {}", child.contract());
746             }
747         }
748     }
749
750     private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
751             final DataSchemaContext ctxNode, final boolean trim) {
752         final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
753         buildCont(childBuilder, container.body(), ctxNode, trim);
754         builder.withChild(childBuilder.build());
755     }
756
757     private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
758             final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
759         if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
760             throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
761         }
762
763         // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
764         final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
765
766         // This is a combined check for when we need to emit the leaf.
767         if (
768             // We always have to emit key leaf values
769             keys.contains(leafSchema.getQName())
770             // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
771             //
772             //            When data is retrieved with a <with-defaults> parameter equal to
773             //            'trim', data nodes MUST NOT be reported if they contain the schema
774             //            default value.  Non-configuration data nodes containing the schema
775             //            default value MUST NOT be reported.
776             //
777             || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
778             // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
779             // grasp what we are doing here... emit only if it matches default ???!!!
780             // FIXME: The WithDefaultsParam.EXPLICIT says:
781             //
782             //            Data nodes set to the YANG default by the client are reported.
783             //
784             //        and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
785             //
786             //            If the "with-defaults" parameter is set to "explicit", then the
787             //            server MUST adhere to the default-reporting behavior defined in
788             //            Section 3.3 of [RFC6243].
789             //
790             //        and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
791             //
792             //            When data is retrieved with a <with-defaults> parameter equal to
793             //            'explicit', a data node that was set by a client to its schema
794             //            default value MUST be reported.  A conceptual data node that would be
795             //            set by the server to the schema default value MUST NOT be reported.
796             //            Non-configuration data nodes containing the schema default value MUST
797             //            be reported.
798             //
799             // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
800             //            This seems to disregard the 'trim = true' case semantics (see above).
801             //            Combining the above, though, these checks are missing the 'non-config' check, which would
802             //            distinguish, but barring that this check is superfluous and results in the wrong semantics.
803             //            Without that input, this really should be  covered by the previous case.
804                 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
805             builder.withChild(leaf);
806         }
807     }
808
809     private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
810             final DataSchemaContext childCtx, final boolean trim) {
811         if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
812             throw new IllegalStateException("Input " + map + " does not match " + childCtx);
813         }
814
815         final var childBuilder = switch (map.ordering()) {
816             case SYSTEM -> Builders.mapBuilder();
817             case USER -> Builders.orderedMapBuilder();
818         };
819         buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
820             listSchema.getKeyDefinition());
821         builder.withChild(childBuilder.build());
822     }
823
824     private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
825             final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
826             final List<@NonNull QName> keys) {
827         for (var entry : entries) {
828             final var childCtx = getChildContext(ctxNode, entry);
829             final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
830             buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
831             builder.withChild(mapEntryBuilder.build());
832         }
833     }
834
835     private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
836             final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
837         for (var child : children) {
838             final var childCtx = getChildContext(ctxNode, child);
839             if (child instanceof ContainerNode container) {
840                 appendContainer(builder, container, childCtx, trim);
841             } else if (child instanceof MapNode map) {
842                 appendMap(builder, map, childCtx, trim);
843             } else if (child instanceof LeafNode<?> leaf) {
844                 appendLeaf(builder, leaf, childCtx, trim, List.of());
845             }
846         }
847     }
848
849     private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
850             final NormalizedNode child) {
851         final var childId = child.name();
852         final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
853             : null;
854         if (childCtx == null) {
855             throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
856         }
857         return childCtx;
858     }
859
860     private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
861                                                                   final NormalizedNode configDataNode) {
862         // if no data exists
863         if (stateDataNode == null && configDataNode == null) {
864             return null;
865         }
866
867         // return config data
868         if (stateDataNode == null) {
869             return configDataNode;
870         }
871
872         // return state data
873         if (configDataNode == null) {
874             return stateDataNode;
875         }
876
877         // merge data from config and state
878         return mergeStateAndConfigData(stateDataNode, configDataNode);
879     }
880
881     /**
882      * Merge state and config data into a single NormalizedNode.
883      *
884      * @param stateDataNode  data node of state data
885      * @param configDataNode data node of config data
886      * @return {@link NormalizedNode}
887      */
888     private static @NonNull NormalizedNode mergeStateAndConfigData(
889             final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
890         validateNodeMerge(stateDataNode, configDataNode);
891         // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
892         if (configDataNode instanceof RpcDefinition) {
893             return prepareRpcData(configDataNode, stateDataNode);
894         } else {
895             return prepareData(configDataNode, stateDataNode);
896         }
897     }
898
899     /**
900      * Validates whether the two NormalizedNodes can be merged.
901      *
902      * @param stateDataNode  data node of state data
903      * @param configDataNode data node of config data
904      */
905     private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
906                                           final @NonNull NormalizedNode configDataNode) {
907         final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
908         final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
909         if (!moduleOfStateData.equals(moduleOfConfigData)) {
910             throw new RestconfDocumentedException("Unable to merge data from different modules.");
911         }
912     }
913
914     /**
915      * Prepare and map data for rpc.
916      *
917      * @param configDataNode data node of config data
918      * @param stateDataNode  data node of state data
919      * @return {@link NormalizedNode}
920      */
921     private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
922                                                           final @NonNull NormalizedNode stateDataNode) {
923         final var mapEntryBuilder = Builders.mapEntryBuilder()
924             .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
925
926         // MAP CONFIG DATA
927         mapRpcDataNode(configDataNode, mapEntryBuilder);
928         // MAP STATE DATA
929         mapRpcDataNode(stateDataNode, mapEntryBuilder);
930
931         return Builders.mapBuilder()
932             .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
933             .addChild(mapEntryBuilder.build())
934             .build();
935     }
936
937     /**
938      * Map node to map entry builder.
939      *
940      * @param dataNode        data node
941      * @param mapEntryBuilder builder for mapping data
942      */
943     private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
944             final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
945         ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
946     }
947
948     /**
949      * Prepare and map all data from DS.
950      *
951      * @param configDataNode data node of config data
952      * @param stateDataNode  data node of state data
953      * @return {@link NormalizedNode}
954      */
955     @SuppressWarnings("unchecked")
956     private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
957                                                        final @NonNull NormalizedNode stateDataNode) {
958         if (configDataNode instanceof UserMapNode configMap) {
959             final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
960             mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
961             return builder.build();
962         } else if (configDataNode instanceof SystemMapNode configMap) {
963             final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
964             mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
965             return builder.build();
966         } else if (configDataNode instanceof MapEntryNode configEntry) {
967             final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
968             mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
969             return builder.build();
970         } else if (configDataNode instanceof ContainerNode configContaienr) {
971             final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
972             mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
973             return builder.build();
974         } else if (configDataNode instanceof ChoiceNode configChoice) {
975             final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
976             mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
977             return builder.build();
978         } else if (configDataNode instanceof LeafNode configLeaf) {
979             // config trumps oper
980             return configLeaf;
981         } else if (configDataNode instanceof UserLeafSetNode) {
982             final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
983             final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
984             mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
985             return builder.build();
986         } else if (configDataNode instanceof SystemLeafSetNode) {
987             final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
988             final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
989             mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
990             return builder.build();
991         } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
992             // config trumps oper
993             return configEntry;
994         } else if (configDataNode instanceof UnkeyedListNode configList) {
995             final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
996             mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
997             return builder.build();
998         } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
999             final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
1000             mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
1001             return builder.build();
1002         } else {
1003             throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
1004         }
1005     }
1006
1007     /**
1008      * Map value from container node to builder.
1009      *
1010      * @param configData collection of config data nodes
1011      * @param stateData  collection of state data nodes
1012      * @param builder    builder
1013      */
1014     private static <T extends NormalizedNode> void mapValueToBuilder(
1015             final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1016             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1017         final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1018         final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1019
1020         // merge config and state data of children with different identifiers
1021         mapDataToBuilder(configMap, stateMap, builder);
1022
1023         // merge config and state data of children with the same identifiers
1024         mergeDataToBuilder(configMap, stateMap, builder);
1025     }
1026
1027     /**
1028      * Map data with different identifiers to builder. Data with different identifiers can be just added
1029      * as childs to parent node.
1030      *
1031      * @param configMap map of config data nodes
1032      * @param stateMap  map of state data nodes
1033      * @param builder   - builder
1034      */
1035     private static <T extends NormalizedNode> void mapDataToBuilder(
1036             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1037             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1038         configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1039             y -> builder.addChild(y.getValue()));
1040         stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1041             y -> builder.addChild(y.getValue()));
1042     }
1043
1044     /**
1045      * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1046      * go one level down with {@code prepareData} method.
1047      *
1048      * @param configMap immutable config data
1049      * @param stateMap  immutable state data
1050      * @param builder   - builder
1051      */
1052     @SuppressWarnings("unchecked")
1053     private static <T extends NormalizedNode> void mergeDataToBuilder(
1054             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1055             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1056         // it is enough to process only config data because operational contains the same data
1057         configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1058             y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1059     }
1060
1061     public @NonNull RestconfFuture<OperationOutput> invokeRpc(final URI restconfURI, final QName type,
1062             final OperationInput input) {
1063         final var local = localRpcs.get(type);
1064         if (local != null) {
1065             return local.invoke(restconfURI, input);
1066         }
1067         if (rpcService == null) {
1068             LOG.debug("RPC invocation is not available");
1069             return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1070                 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1071         }
1072
1073         final var ret = new SettableRestconfFuture<OperationOutput>();
1074         Futures.addCallback(rpcService.invokeRpc(requireNonNull(type), input.input()),
1075             new FutureCallback<DOMRpcResult>() {
1076                 @Override
1077                 public void onSuccess(final DOMRpcResult response) {
1078                     final var errors = response.errors();
1079                     if (errors.isEmpty()) {
1080                         ret.set(input.newOperationOutput(response.value()));
1081                     } else {
1082                         LOG.debug("RPC invocation reported {}", response.errors());
1083                         ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1084                             response.errors()));
1085                     }
1086                 }
1087
1088                 @Override
1089                 public void onFailure(final Throwable cause) {
1090                     LOG.debug("RPC invocation failed, cause");
1091                     if (cause instanceof RestconfDocumentedException ex) {
1092                         ret.setFailure(ex);
1093                     } else {
1094                         // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1095                         ret.setFailure(new RestconfDocumentedException(cause,
1096                             new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1097                     }
1098                 }
1099             }, MoreExecutors.directExecutor());
1100         return ret;
1101     }
1102
1103     public @NonNull RestconfFuture<CharSource> resolveSource(final SourceIdentifier source,
1104             final Class<? extends SchemaSourceRepresentation> representation) {
1105         final var src = requireNonNull(source);
1106         if (YangTextSchemaSource.class.isAssignableFrom(representation)) {
1107             if (sourceProvider != null) {
1108                 final var ret = new SettableRestconfFuture<CharSource>();
1109                 Futures.addCallback(sourceProvider.getSource(src), new FutureCallback<YangTextSchemaSource>() {
1110                     @Override
1111                     public void onSuccess(final YangTextSchemaSource result) {
1112                         ret.set(result);
1113                     }
1114
1115                     @Override
1116                     public void onFailure(final Throwable cause) {
1117                         ret.setFailure(cause instanceof RestconfDocumentedException e ? e
1118                             : new RestconfDocumentedException(cause.getMessage(), ErrorType.RPC,
1119                                 ErrorTag.OPERATION_FAILED, cause));
1120                     }
1121                 }, MoreExecutors.directExecutor());
1122                 return ret;
1123             }
1124             return exportSource(modelContext(), src, YangCharSource::new, YangCharSource::new);
1125         }
1126         if (YinTextSchemaSource.class.isAssignableFrom(representation)) {
1127             return exportSource(modelContext(), src, YinCharSource.OfModule::new, YinCharSource.OfSubmodule::new);
1128         }
1129         return RestconfFuture.failed(new RestconfDocumentedException(
1130             "Unsupported source representation " + representation.getName()));
1131     }
1132
1133     private static @NonNull RestconfFuture<CharSource> exportSource(final EffectiveModelContext modelContext,
1134             final SourceIdentifier source, final Function<ModuleEffectiveStatement, CharSource> moduleCtor,
1135             final BiFunction<ModuleEffectiveStatement, SubmoduleEffectiveStatement, CharSource> submoduleCtor) {
1136         // If the source identifies a module, things are easy
1137         final var name = source.name().getLocalName();
1138         final var optRevision = Optional.ofNullable(source.revision());
1139         final var optModule = modelContext.findModule(name, optRevision);
1140         if (optModule.isPresent()) {
1141             return RestconfFuture.of(moduleCtor.apply(optModule.orElseThrow().asEffectiveStatement()));
1142         }
1143
1144         // The source could be a submodule, which we need to hunt down
1145         for (var module : modelContext.getModules()) {
1146             for (var submodule : module.getSubmodules()) {
1147                 if (name.equals(submodule.getName()) && optRevision.equals(submodule.getRevision())) {
1148                     return RestconfFuture.of(submoduleCtor.apply(module.asEffectiveStatement(),
1149                         submodule.asEffectiveStatement()));
1150                 }
1151             }
1152         }
1153
1154         final var sb = new StringBuilder().append("Source ").append(source.name().getLocalName());
1155         optRevision.ifPresent(rev -> sb.append('@').append(rev));
1156         sb.append(" not found");
1157         return RestconfFuture.failed(new RestconfDocumentedException(sb.toString(),
1158             ErrorType.APPLICATION, ErrorTag.DATA_MISSING));
1159     }
1160
1161 }