Eliminate IdentifierCodec
[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.utils.parser.YangInstanceIdentifierSerializer;
52 import org.opendaylight.restconf.server.api.DataPostResult.CreateResource;
53 import org.opendaylight.restconf.server.api.DataPutResult;
54 import org.opendaylight.restconf.server.api.DatabindContext;
55 import org.opendaylight.restconf.server.api.OperationsPostResult;
56 import org.opendaylight.restconf.server.spi.OperationInput;
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(new YangInstanceIdentifierSerializer(databind).serializePath(
403                     data instanceof MapNode mapData && !mapData.isEmpty()
404                         ? path.node(mapData.body().iterator().next().name()) : path)));
405             }
406
407             @Override
408             public void onFailure(final Throwable cause) {
409                 ret.setFailure(TransactionUtil.decodeException(cause, "POST", path, modelContext()));
410             }
411
412         }, MoreExecutors.directExecutor());
413         return ret;
414     }
415
416     private ListenableFuture<? extends CommitInfo> insertAndCommitPost(final YangInstanceIdentifier path,
417             final NormalizedNode data, final @NonNull Insert insert, final YangInstanceIdentifier parent) {
418         final var grandParent = parent.coerceParent();
419         final var tx = prepareWriteExecution();
420
421         return switch (insert.insert()) {
422             case FIRST -> {
423                 final var readData = tx.readList(grandParent);
424                 if (readData == null || readData.isEmpty()) {
425                     tx.replace(path, data);
426                 } else {
427                     checkItemDoesNotExists(exists(path), path);
428                     tx.remove(grandParent);
429                     tx.replace(path, data);
430                     tx.replace(grandParent, readData);
431                 }
432                 yield tx.commit();
433             }
434             case LAST -> createAndCommit(tx, path, data);
435             case BEFORE -> {
436                 final var readData = tx.readList(grandParent);
437                 if (readData == null || readData.isEmpty()) {
438                     tx.replace(path, data);
439                 } else {
440                     checkItemDoesNotExists(exists(path), path);
441                     insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, true);
442                 }
443                 yield tx.commit();
444             }
445             case AFTER -> {
446                 final var readData = tx.readList(grandParent);
447                 if (readData == null || readData.isEmpty()) {
448                     tx.replace(path, data);
449                 } else {
450                     checkItemDoesNotExists(exists(path), path);
451                     insertWithPointPost(tx, path, data, verifyNotNull(insert.pointArg()), readData, grandParent, false);
452                 }
453                 yield tx.commit();
454             }
455         };
456     }
457
458     /**
459      * Process edit operations of one {@link PatchContext}.
460      *
461      * @param patch Patch context to be processed
462      * @return {@link PatchStatusContext}
463      */
464     public final @NonNull RestconfFuture<PatchStatusContext> patchData(final PatchContext patch) {
465         final var editCollection = new ArrayList<PatchStatusEntity>();
466         final var tx = prepareWriteExecution();
467
468         boolean noError = true;
469         for (var patchEntity : patch.entities()) {
470             if (noError) {
471                 final var targetNode = patchEntity.getTargetNode();
472                 final var editId = patchEntity.getEditId();
473
474                 switch (patchEntity.getOperation()) {
475                     case Create:
476                         try {
477                             tx.create(targetNode, patchEntity.getNode());
478                             editCollection.add(new PatchStatusEntity(editId, true, null));
479                         } catch (RestconfDocumentedException e) {
480                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
481                             noError = false;
482                         }
483                         break;
484                     case Delete:
485                         try {
486                             tx.delete(targetNode);
487                             editCollection.add(new PatchStatusEntity(editId, true, null));
488                         } catch (RestconfDocumentedException e) {
489                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
490                             noError = false;
491                         }
492                         break;
493                     case Merge:
494                         try {
495                             tx.ensureParentsByMerge(targetNode);
496                             tx.merge(targetNode, patchEntity.getNode());
497                             editCollection.add(new PatchStatusEntity(editId, true, null));
498                         } catch (RestconfDocumentedException e) {
499                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
500                             noError = false;
501                         }
502                         break;
503                     case Replace:
504                         try {
505                             tx.replace(targetNode, patchEntity.getNode());
506                             editCollection.add(new PatchStatusEntity(editId, true, null));
507                         } catch (RestconfDocumentedException e) {
508                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
509                             noError = false;
510                         }
511                         break;
512                     case Remove:
513                         try {
514                             tx.remove(targetNode);
515                             editCollection.add(new PatchStatusEntity(editId, true, null));
516                         } catch (RestconfDocumentedException e) {
517                             editCollection.add(new PatchStatusEntity(editId, false, e.getErrors()));
518                             noError = false;
519                         }
520                         break;
521                     default:
522                         editCollection.add(new PatchStatusEntity(editId, false, List.of(
523                             new RestconfError(ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED,
524                                 "Not supported Yang Patch operation"))));
525                         noError = false;
526                         break;
527                 }
528             } else {
529                 break;
530             }
531         }
532
533         final var ret = new SettableRestconfFuture<PatchStatusContext>();
534         // We have errors
535         if (!noError) {
536             tx.cancel();
537             ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false, null));
538             return ret;
539         }
540
541         Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
542             @Override
543             public void onSuccess(final CommitInfo result) {
544                 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), true,
545                     null));
546             }
547
548             @Override
549             public void onFailure(final Throwable cause) {
550                 // if errors occurred during transaction commit then patch failed and global errors are reported
551                 ret.set(new PatchStatusContext(modelContext(), patch.patchId(), List.copyOf(editCollection), false,
552                     TransactionUtil.decodeException(cause, "PATCH", null, modelContext()).getErrors()));
553             }
554         }, MoreExecutors.directExecutor());
555
556         return ret;
557     }
558
559     private void insertWithPointPost(final RestconfTransaction tx, final YangInstanceIdentifier path,
560             final NormalizedNode data, final PathArgument pointArg, final NormalizedNodeContainer<?> readList,
561             final YangInstanceIdentifier grandParentPath, final boolean before) {
562         tx.remove(grandParentPath);
563
564         int lastItemPosition = 0;
565         for (var nodeChild : readList.body()) {
566             if (nodeChild.name().equals(pointArg)) {
567                 break;
568             }
569             lastItemPosition++;
570         }
571         if (!before) {
572             lastItemPosition++;
573         }
574
575         int lastInsertedPosition = 0;
576         final var emptySubtree = ImmutableNodes.fromInstanceId(modelContext(), grandParentPath);
577         tx.merge(YangInstanceIdentifier.of(emptySubtree.name()), emptySubtree);
578         for (var nodeChild : readList.body()) {
579             if (lastInsertedPosition == lastItemPosition) {
580                 tx.replace(path, data);
581             }
582             tx.replace(grandParentPath.node(nodeChild.name()), nodeChild);
583             lastInsertedPosition++;
584         }
585     }
586
587     private static ListenableFuture<? extends CommitInfo> createAndCommit(final RestconfTransaction tx,
588             final YangInstanceIdentifier path, final NormalizedNode data) {
589         try {
590             tx.create(path, data);
591         } catch (RestconfDocumentedException e) {
592             // close transaction if any and pass exception further
593             tx.cancel();
594             throw e;
595         }
596
597         return tx.commit();
598     }
599
600     /**
601      * Check if items do NOT already exists at specified {@code path}.
602      *
603      * @param existsFuture if checked data exists
604      * @param path         Path to be checked
605      * @throws RestconfDocumentedException if data already exists.
606      */
607     static void checkItemDoesNotExists(final ListenableFuture<Boolean> existsFuture,
608             final YangInstanceIdentifier path) {
609         if (TransactionUtil.syncAccess(existsFuture, path)) {
610             LOG.trace("Operation via Restconf was not executed because data at {} already exists", path);
611             throw new RestconfDocumentedException("Data already exists", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS,
612                 path);
613         }
614     }
615
616     /**
617      * Read specific type of data from data store via transaction. Close {@link DOMTransactionChain} if any
618      * inside of object {@link RestconfStrategy} provided as a parameter.
619      *
620      * @param content      type of data to read (config, state, all)
621      * @param path         the path to read
622      * @param defaultsMode value of with-defaults parameter
623      * @return {@link NormalizedNode}
624      */
625     // FIXME: NETCONF-1155: this method should asynchronous
626     public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
627             final @NonNull YangInstanceIdentifier path, final WithDefaultsParam defaultsMode) {
628         return switch (content) {
629             case ALL -> {
630                 // PREPARE STATE DATA NODE
631                 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
632                 // PREPARE CONFIG DATA NODE
633                 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
634
635                 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, defaultsMode == null ? configDataNode
636                     : prepareDataByParamWithDef(configDataNode, path, defaultsMode.mode()));
637             }
638             case CONFIG -> {
639                 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path);
640                 yield defaultsMode == null ? read
641                     : prepareDataByParamWithDef(read, path, defaultsMode.mode());
642             }
643             case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path);
644         };
645     }
646
647     /**
648      * Read specific type of data from data store via transaction with specified subtrees that should only be read.
649      * Close {@link DOMTransactionChain} inside of object {@link RestconfStrategy} provided as a parameter.
650      *
651      * @param content  type of data to read (config, state, all)
652      * @param path     the parent path to read
653      * @param withDefa value of with-defaults parameter
654      * @param fields   paths to selected subtrees which should be read, relative to to the parent path
655      * @return {@link NormalizedNode}
656      */
657     // FIXME: NETCONF-1155: this method should asynchronous
658     public @Nullable NormalizedNode readData(final @NonNull ContentParam content,
659             final @NonNull YangInstanceIdentifier path, final @Nullable WithDefaultsParam withDefa,
660             final @NonNull List<YangInstanceIdentifier> fields) {
661         return switch (content) {
662             case ALL -> {
663                 // PREPARE STATE DATA NODE
664                 final var stateDataNode = readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
665                 // PREPARE CONFIG DATA NODE
666                 final var configDataNode = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
667
668                 yield mergeConfigAndSTateDataIfNeeded(stateDataNode, withDefa == null ? configDataNode
669                     : prepareDataByParamWithDef(configDataNode, path, withDefa.mode()));
670             }
671             case CONFIG -> {
672                 final var read = readDataViaTransaction(LogicalDatastoreType.CONFIGURATION, path, fields);
673                 yield withDefa == null ? read : prepareDataByParamWithDef(read, path, withDefa.mode());
674             }
675             case NONCONFIG -> readDataViaTransaction(LogicalDatastoreType.OPERATIONAL, path, fields);
676         };
677     }
678
679     private @Nullable NormalizedNode readDataViaTransaction(final LogicalDatastoreType store,
680             final YangInstanceIdentifier path) {
681         return TransactionUtil.syncAccess(read(store, path), path).orElse(null);
682     }
683
684     /**
685      * Read specific type of data {@link LogicalDatastoreType} via transaction in {@link RestconfStrategy} with
686      * specified subtrees that should only be read.
687      *
688      * @param store                 datastore type
689      * @param path                  parent path to selected fields
690      * @param closeTransactionChain if it is set to {@code true}, after transaction it will close transactionChain
691      *                              in {@link RestconfStrategy} if any
692      * @param fields                paths to selected subtrees which should be read, relative to to the parent path
693      * @return {@link NormalizedNode}
694      */
695     private @Nullable NormalizedNode readDataViaTransaction(final @NonNull LogicalDatastoreType store,
696             final @NonNull YangInstanceIdentifier path, final @NonNull List<YangInstanceIdentifier> fields) {
697         return TransactionUtil.syncAccess(read(store, path, fields), path).orElse(null);
698     }
699
700     private NormalizedNode prepareDataByParamWithDef(final NormalizedNode readData, final YangInstanceIdentifier path,
701             final WithDefaultsMode defaultsMode) {
702         final boolean trim = switch (defaultsMode) {
703             case Trim -> true;
704             case Explicit -> false;
705             case ReportAll, ReportAllTagged -> throw new RestconfDocumentedException(
706                 "Unsupported with-defaults value " + defaultsMode.getName());
707         };
708
709         // FIXME: we have this readily available in InstanceIdentifierContext
710         final var ctxNode = databind.schemaTree().findChild(path).orElseThrow();
711         if (readData instanceof ContainerNode container) {
712             final var builder = Builders.containerBuilder().withNodeIdentifier(container.name());
713             buildCont(builder, container.body(), ctxNode, trim);
714             return builder.build();
715         } else if (readData instanceof MapEntryNode mapEntry) {
716             if (!(ctxNode.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
717                 throw new IllegalStateException("Input " + mapEntry + " does not match " + ctxNode);
718             }
719
720             final var builder = Builders.mapEntryBuilder().withNodeIdentifier(mapEntry.name());
721             buildMapEntryBuilder(builder, mapEntry.body(), ctxNode, trim, listSchema.getKeyDefinition());
722             return builder.build();
723         } else {
724             throw new IllegalStateException("Unhandled data contract " + readData.contract());
725         }
726     }
727
728     private static void buildMapEntryBuilder(
729             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> builder,
730             final Collection<@NonNull DataContainerChild> children, final DataSchemaContext ctxNode,
731             final boolean trim, final List<QName> keys) {
732         for (var child : children) {
733             final var childCtx = getChildContext(ctxNode, child);
734
735             if (child instanceof ContainerNode container) {
736                 appendContainer(builder, container, childCtx, trim);
737             } else if (child instanceof MapNode map) {
738                 appendMap(builder, map, childCtx, trim);
739             } else if (child instanceof LeafNode<?> leaf) {
740                 appendLeaf(builder, leaf, childCtx, trim, keys);
741             } else {
742                 // FIXME: we should never hit this, throw an ISE if this ever happens
743                 LOG.debug("Ignoring unhandled child contract {}", child.contract());
744             }
745         }
746     }
747
748     private static void appendContainer(final DataContainerNodeBuilder<?, ?> builder, final ContainerNode container,
749             final DataSchemaContext ctxNode, final boolean trim) {
750         final var childBuilder = Builders.containerBuilder().withNodeIdentifier(container.name());
751         buildCont(childBuilder, container.body(), ctxNode, trim);
752         builder.withChild(childBuilder.build());
753     }
754
755     private static void appendLeaf(final DataContainerNodeBuilder<?, ?> builder, final LeafNode<?> leaf,
756             final DataSchemaContext ctxNode, final boolean trim, final List<QName> keys) {
757         if (!(ctxNode.dataSchemaNode() instanceof LeafSchemaNode leafSchema)) {
758             throw new IllegalStateException("Input " + leaf + " does not match " + ctxNode);
759         }
760
761         // FIXME: Document now this works with the likes of YangInstanceIdentifier. I bet it does not.
762         final var defaultVal = leafSchema.getType().getDefaultValue().orElse(null);
763
764         // This is a combined check for when we need to emit the leaf.
765         if (
766             // We always have to emit key leaf values
767             keys.contains(leafSchema.getQName())
768             // trim == WithDefaultsParam.TRIM and the source is assumed to store explicit values:
769             //
770             //            When data is retrieved with a <with-defaults> parameter equal to
771             //            'trim', data nodes MUST NOT be reported if they contain the schema
772             //            default value.  Non-configuration data nodes containing the schema
773             //            default value MUST NOT be reported.
774             //
775             || trim && (defaultVal == null || !defaultVal.equals(leaf.body()))
776             // !trim == WithDefaultsParam.EXPLICIT and the source is assume to store explicit values... but I fail to
777             // grasp what we are doing here... emit only if it matches default ???!!!
778             // FIXME: The WithDefaultsParam.EXPLICIT says:
779             //
780             //            Data nodes set to the YANG default by the client are reported.
781             //
782             //        and RFC8040 (https://www.rfc-editor.org/rfc/rfc8040#page-60) says:
783             //
784             //            If the "with-defaults" parameter is set to "explicit", then the
785             //            server MUST adhere to the default-reporting behavior defined in
786             //            Section 3.3 of [RFC6243].
787             //
788             //        and then RFC6243 (https://www.rfc-editor.org/rfc/rfc6243#section-3.3) says:
789             //
790             //            When data is retrieved with a <with-defaults> parameter equal to
791             //            'explicit', a data node that was set by a client to its schema
792             //            default value MUST be reported.  A conceptual data node that would be
793             //            set by the server to the schema default value MUST NOT be reported.
794             //            Non-configuration data nodes containing the schema default value MUST
795             //            be reported.
796             //
797             // (rovarga): The source reports explicitly-defined leaves and does *not* create defaults by itself.
798             //            This seems to disregard the 'trim = true' case semantics (see above).
799             //            Combining the above, though, these checks are missing the 'non-config' check, which would
800             //            distinguish, but barring that this check is superfluous and results in the wrong semantics.
801             //            Without that input, this really should be  covered by the previous case.
802                 || !trim && defaultVal != null && defaultVal.equals(leaf.body())) {
803             builder.withChild(leaf);
804         }
805     }
806
807     private static void appendMap(final DataContainerNodeBuilder<?, ?> builder, final MapNode map,
808             final DataSchemaContext childCtx, final boolean trim) {
809         if (!(childCtx.dataSchemaNode() instanceof ListSchemaNode listSchema)) {
810             throw new IllegalStateException("Input " + map + " does not match " + childCtx);
811         }
812
813         final var childBuilder = switch (map.ordering()) {
814             case SYSTEM -> Builders.mapBuilder();
815             case USER -> Builders.orderedMapBuilder();
816         };
817         buildList(childBuilder.withNodeIdentifier(map.name()), map.body(), childCtx, trim,
818             listSchema.getKeyDefinition());
819         builder.withChild(childBuilder.build());
820     }
821
822     private static void buildList(final CollectionNodeBuilder<MapEntryNode, ? extends MapNode> builder,
823             final Collection<@NonNull MapEntryNode> entries, final DataSchemaContext ctxNode, final boolean trim,
824             final List<@NonNull QName> keys) {
825         for (var entry : entries) {
826             final var childCtx = getChildContext(ctxNode, entry);
827             final var mapEntryBuilder = Builders.mapEntryBuilder().withNodeIdentifier(entry.name());
828             buildMapEntryBuilder(mapEntryBuilder, entry.body(), childCtx, trim, keys);
829             builder.withChild(mapEntryBuilder.build());
830         }
831     }
832
833     private static void buildCont(final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> builder,
834             final Collection<DataContainerChild> children, final DataSchemaContext ctxNode, final boolean trim) {
835         for (var child : children) {
836             final var childCtx = getChildContext(ctxNode, child);
837             if (child instanceof ContainerNode container) {
838                 appendContainer(builder, container, childCtx, trim);
839             } else if (child instanceof MapNode map) {
840                 appendMap(builder, map, childCtx, trim);
841             } else if (child instanceof LeafNode<?> leaf) {
842                 appendLeaf(builder, leaf, childCtx, trim, List.of());
843             }
844         }
845     }
846
847     private static @NonNull DataSchemaContext getChildContext(final DataSchemaContext ctxNode,
848             final NormalizedNode child) {
849         final var childId = child.name();
850         final var childCtx = ctxNode instanceof DataSchemaContext.Composite composite ? composite.childByArg(childId)
851             : null;
852         if (childCtx == null) {
853             throw new NoSuchElementException("Cannot resolve child " + childId + " in " + ctxNode);
854         }
855         return childCtx;
856     }
857
858     private static NormalizedNode mergeConfigAndSTateDataIfNeeded(final NormalizedNode stateDataNode,
859                                                                   final NormalizedNode configDataNode) {
860         // if no data exists
861         if (stateDataNode == null && configDataNode == null) {
862             return null;
863         }
864
865         // return config data
866         if (stateDataNode == null) {
867             return configDataNode;
868         }
869
870         // return state data
871         if (configDataNode == null) {
872             return stateDataNode;
873         }
874
875         // merge data from config and state
876         return mergeStateAndConfigData(stateDataNode, configDataNode);
877     }
878
879     /**
880      * Merge state and config data into a single NormalizedNode.
881      *
882      * @param stateDataNode  data node of state data
883      * @param configDataNode data node of config data
884      * @return {@link NormalizedNode}
885      */
886     private static @NonNull NormalizedNode mergeStateAndConfigData(
887             final @NonNull NormalizedNode stateDataNode, final @NonNull NormalizedNode configDataNode) {
888         validateNodeMerge(stateDataNode, configDataNode);
889         // FIXME: this check is bogus, as it confuses yang.data.api (NormalizedNode) with yang.model.api (RpcDefinition)
890         if (configDataNode instanceof RpcDefinition) {
891             return prepareRpcData(configDataNode, stateDataNode);
892         } else {
893             return prepareData(configDataNode, stateDataNode);
894         }
895     }
896
897     /**
898      * Validates whether the two NormalizedNodes can be merged.
899      *
900      * @param stateDataNode  data node of state data
901      * @param configDataNode data node of config data
902      */
903     private static void validateNodeMerge(final @NonNull NormalizedNode stateDataNode,
904                                           final @NonNull NormalizedNode configDataNode) {
905         final QNameModule moduleOfStateData = stateDataNode.name().getNodeType().getModule();
906         final QNameModule moduleOfConfigData = configDataNode.name().getNodeType().getModule();
907         if (!moduleOfStateData.equals(moduleOfConfigData)) {
908             throw new RestconfDocumentedException("Unable to merge data from different modules.");
909         }
910     }
911
912     /**
913      * Prepare and map data for rpc.
914      *
915      * @param configDataNode data node of config data
916      * @param stateDataNode  data node of state data
917      * @return {@link NormalizedNode}
918      */
919     private static @NonNull NormalizedNode prepareRpcData(final @NonNull NormalizedNode configDataNode,
920                                                           final @NonNull NormalizedNode stateDataNode) {
921         final var mapEntryBuilder = Builders.mapEntryBuilder()
922             .withNodeIdentifier((NodeIdentifierWithPredicates) configDataNode.name());
923
924         // MAP CONFIG DATA
925         mapRpcDataNode(configDataNode, mapEntryBuilder);
926         // MAP STATE DATA
927         mapRpcDataNode(stateDataNode, mapEntryBuilder);
928
929         return Builders.mapBuilder()
930             .withNodeIdentifier(NodeIdentifier.create(configDataNode.name().getNodeType()))
931             .addChild(mapEntryBuilder.build())
932             .build();
933     }
934
935     /**
936      * Map node to map entry builder.
937      *
938      * @param dataNode        data node
939      * @param mapEntryBuilder builder for mapping data
940      */
941     private static void mapRpcDataNode(final @NonNull NormalizedNode dataNode,
942             final @NonNull DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> mapEntryBuilder) {
943         ((ContainerNode) dataNode).body().forEach(mapEntryBuilder::addChild);
944     }
945
946     /**
947      * Prepare and map all data from DS.
948      *
949      * @param configDataNode data node of config data
950      * @param stateDataNode  data node of state data
951      * @return {@link NormalizedNode}
952      */
953     @SuppressWarnings("unchecked")
954     private static @NonNull NormalizedNode prepareData(final @NonNull NormalizedNode configDataNode,
955                                                        final @NonNull NormalizedNode stateDataNode) {
956         if (configDataNode instanceof UserMapNode configMap) {
957             final var builder = Builders.orderedMapBuilder().withNodeIdentifier(configMap.name());
958             mapValueToBuilder(configMap.body(), ((UserMapNode) stateDataNode).body(), builder);
959             return builder.build();
960         } else if (configDataNode instanceof SystemMapNode configMap) {
961             final var builder = Builders.mapBuilder().withNodeIdentifier(configMap.name());
962             mapValueToBuilder(configMap.body(), ((SystemMapNode) stateDataNode).body(), builder);
963             return builder.build();
964         } else if (configDataNode instanceof MapEntryNode configEntry) {
965             final var builder = Builders.mapEntryBuilder().withNodeIdentifier(configEntry.name());
966             mapValueToBuilder(configEntry.body(), ((MapEntryNode) stateDataNode).body(), builder);
967             return builder.build();
968         } else if (configDataNode instanceof ContainerNode configContaienr) {
969             final var builder = Builders.containerBuilder().withNodeIdentifier(configContaienr.name());
970             mapValueToBuilder(configContaienr.body(), ((ContainerNode) stateDataNode).body(), builder);
971             return builder.build();
972         } else if (configDataNode instanceof ChoiceNode configChoice) {
973             final var builder = Builders.choiceBuilder().withNodeIdentifier(configChoice.name());
974             mapValueToBuilder(configChoice.body(), ((ChoiceNode) stateDataNode).body(), builder);
975             return builder.build();
976         } else if (configDataNode instanceof LeafNode configLeaf) {
977             // config trumps oper
978             return configLeaf;
979         } else if (configDataNode instanceof UserLeafSetNode) {
980             final var configLeafSet = (UserLeafSetNode<Object>) configDataNode;
981             final var builder = Builders.<Object>orderedLeafSetBuilder().withNodeIdentifier(configLeafSet.name());
982             mapValueToBuilder(configLeafSet.body(), ((UserLeafSetNode<Object>) stateDataNode).body(), builder);
983             return builder.build();
984         } else if (configDataNode instanceof SystemLeafSetNode) {
985             final var configLeafSet = (SystemLeafSetNode<Object>) configDataNode;
986             final var builder = Builders.<Object>leafSetBuilder().withNodeIdentifier(configLeafSet.name());
987             mapValueToBuilder(configLeafSet.body(), ((SystemLeafSetNode<Object>) stateDataNode).body(), builder);
988             return builder.build();
989         } else if (configDataNode instanceof LeafSetEntryNode<?> configEntry) {
990             // config trumps oper
991             return configEntry;
992         } else if (configDataNode instanceof UnkeyedListNode configList) {
993             final var builder = Builders.unkeyedListBuilder().withNodeIdentifier(configList.name());
994             mapValueToBuilder(configList.body(), ((UnkeyedListNode) stateDataNode).body(), builder);
995             return builder.build();
996         } else if (configDataNode instanceof UnkeyedListEntryNode configEntry) {
997             final var builder = Builders.unkeyedListEntryBuilder().withNodeIdentifier(configEntry.name());
998             mapValueToBuilder(configEntry.body(), ((UnkeyedListEntryNode) stateDataNode).body(), builder);
999             return builder.build();
1000         } else {
1001             throw new RestconfDocumentedException("Unexpected node type: " + configDataNode.getClass().getName());
1002         }
1003     }
1004
1005     /**
1006      * Map value from container node to builder.
1007      *
1008      * @param configData collection of config data nodes
1009      * @param stateData  collection of state data nodes
1010      * @param builder    builder
1011      */
1012     private static <T extends NormalizedNode> void mapValueToBuilder(
1013             final @NonNull Collection<T> configData, final @NonNull Collection<T> stateData,
1014             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1015         final var configMap = configData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1016         final var stateMap = stateData.stream().collect(Collectors.toMap(NormalizedNode::name, Function.identity()));
1017
1018         // merge config and state data of children with different identifiers
1019         mapDataToBuilder(configMap, stateMap, builder);
1020
1021         // merge config and state data of children with the same identifiers
1022         mergeDataToBuilder(configMap, stateMap, builder);
1023     }
1024
1025     /**
1026      * Map data with different identifiers to builder. Data with different identifiers can be just added
1027      * as childs to parent node.
1028      *
1029      * @param configMap map of config data nodes
1030      * @param stateMap  map of state data nodes
1031      * @param builder   - builder
1032      */
1033     private static <T extends NormalizedNode> void mapDataToBuilder(
1034             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1035             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1036         configMap.entrySet().stream().filter(x -> !stateMap.containsKey(x.getKey())).forEach(
1037             y -> builder.addChild(y.getValue()));
1038         stateMap.entrySet().stream().filter(x -> !configMap.containsKey(x.getKey())).forEach(
1039             y -> builder.addChild(y.getValue()));
1040     }
1041
1042     /**
1043      * Map data with the same identifiers to builder. Data with the same identifiers cannot be just added but we need to
1044      * go one level down with {@code prepareData} method.
1045      *
1046      * @param configMap immutable config data
1047      * @param stateMap  immutable state data
1048      * @param builder   - builder
1049      */
1050     @SuppressWarnings("unchecked")
1051     private static <T extends NormalizedNode> void mergeDataToBuilder(
1052             final @NonNull Map<PathArgument, T> configMap, final @NonNull Map<PathArgument, T> stateMap,
1053             final @NonNull NormalizedNodeContainerBuilder<?, PathArgument, T, ?> builder) {
1054         // it is enough to process only config data because operational contains the same data
1055         configMap.entrySet().stream().filter(x -> stateMap.containsKey(x.getKey())).forEach(
1056             y -> builder.addChild((T) prepareData(y.getValue(), stateMap.get(y.getKey()))));
1057     }
1058
1059     public @NonNull RestconfFuture<OperationsPostResult> invokeRpc(final URI restconfURI, final QName type,
1060             final OperationInput input) {
1061         final var local = localRpcs.get(type);
1062         if (local != null) {
1063             return local.invoke(restconfURI, input);
1064         }
1065         if (rpcService == null) {
1066             LOG.debug("RPC invocation is not available");
1067             return RestconfFuture.failed(new RestconfDocumentedException("RPC invocation is not available",
1068                 ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED));
1069         }
1070
1071         final var ret = new SettableRestconfFuture<OperationsPostResult>();
1072         Futures.addCallback(rpcService.invokeRpc(requireNonNull(type), input.input()),
1073             new FutureCallback<DOMRpcResult>() {
1074                 @Override
1075                 public void onSuccess(final DOMRpcResult response) {
1076                     final var errors = response.errors();
1077                     if (errors.isEmpty()) {
1078                         ret.set(input.newOperationOutput(response.value()));
1079                     } else {
1080                         LOG.debug("RPC invocation reported {}", response.errors());
1081                         ret.setFailure(new RestconfDocumentedException("RPC implementation reported errors", null,
1082                             response.errors()));
1083                     }
1084                 }
1085
1086                 @Override
1087                 public void onFailure(final Throwable cause) {
1088                     LOG.debug("RPC invocation failed, cause");
1089                     if (cause instanceof RestconfDocumentedException ex) {
1090                         ret.setFailure(ex);
1091                     } else {
1092                         // TODO: YangNetconfErrorAware if we ever get into a broader invocation scope
1093                         ret.setFailure(new RestconfDocumentedException(cause,
1094                             new RestconfError(ErrorType.RPC, ErrorTag.OPERATION_FAILED, cause.getMessage())));
1095                     }
1096                 }
1097             }, MoreExecutors.directExecutor());
1098         return ret;
1099     }
1100
1101     public @NonNull RestconfFuture<CharSource> resolveSource(final SourceIdentifier source,
1102             final Class<? extends SchemaSourceRepresentation> representation) {
1103         final var src = requireNonNull(source);
1104         if (YangTextSchemaSource.class.isAssignableFrom(representation)) {
1105             if (sourceProvider != null) {
1106                 final var ret = new SettableRestconfFuture<CharSource>();
1107                 Futures.addCallback(sourceProvider.getSource(src), new FutureCallback<YangTextSchemaSource>() {
1108                     @Override
1109                     public void onSuccess(final YangTextSchemaSource result) {
1110                         ret.set(result);
1111                     }
1112
1113                     @Override
1114                     public void onFailure(final Throwable cause) {
1115                         ret.setFailure(cause instanceof RestconfDocumentedException e ? e
1116                             : new RestconfDocumentedException(cause.getMessage(), ErrorType.RPC,
1117                                 ErrorTag.OPERATION_FAILED, cause));
1118                     }
1119                 }, MoreExecutors.directExecutor());
1120                 return ret;
1121             }
1122             return exportSource(modelContext(), src, YangCharSource::new, YangCharSource::new);
1123         }
1124         if (YinTextSchemaSource.class.isAssignableFrom(representation)) {
1125             return exportSource(modelContext(), src, YinCharSource.OfModule::new, YinCharSource.OfSubmodule::new);
1126         }
1127         return RestconfFuture.failed(new RestconfDocumentedException(
1128             "Unsupported source representation " + representation.getName()));
1129     }
1130
1131     private static @NonNull RestconfFuture<CharSource> exportSource(final EffectiveModelContext modelContext,
1132             final SourceIdentifier source, final Function<ModuleEffectiveStatement, CharSource> moduleCtor,
1133             final BiFunction<ModuleEffectiveStatement, SubmoduleEffectiveStatement, CharSource> submoduleCtor) {
1134         // If the source identifies a module, things are easy
1135         final var name = source.name().getLocalName();
1136         final var optRevision = Optional.ofNullable(source.revision());
1137         final var optModule = modelContext.findModule(name, optRevision);
1138         if (optModule.isPresent()) {
1139             return RestconfFuture.of(moduleCtor.apply(optModule.orElseThrow().asEffectiveStatement()));
1140         }
1141
1142         // The source could be a submodule, which we need to hunt down
1143         for (var module : modelContext.getModules()) {
1144             for (var submodule : module.getSubmodules()) {
1145                 if (name.equals(submodule.getName()) && optRevision.equals(submodule.getRevision())) {
1146                     return RestconfFuture.of(submoduleCtor.apply(module.asEffectiveStatement(),
1147                         submodule.asEffectiveStatement()));
1148                 }
1149             }
1150         }
1151
1152         final var sb = new StringBuilder().append("Source ").append(source.name().getLocalName());
1153         optRevision.ifPresent(rev -> sb.append('@').append(rev));
1154         sb.append(" not found");
1155         return RestconfFuture.failed(new RestconfDocumentedException(sb.toString(),
1156             ErrorType.APPLICATION, ErrorTag.DATA_MISSING));
1157     }
1158
1159 }