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