Bump versions to 14.0.0-SNAPSHOT
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / DataObjectCodecContext.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. 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.mdsal.binding.dom.codec.impl;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.Throwables;
14 import com.google.common.base.VerifyException;
15 import com.google.common.collect.ImmutableCollection;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.collect.ImmutableSet;
18 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
19 import java.lang.invoke.MethodHandle;
20 import java.lang.invoke.MethodHandles;
21 import java.lang.invoke.MethodType;
22 import java.lang.invoke.VarHandle;
23 import java.lang.reflect.Method;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataObjectCodecTreeNode;
30 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCachingCodec;
31 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
32 import org.opendaylight.mdsal.binding.model.api.Type;
33 import org.opendaylight.mdsal.binding.runtime.api.AugmentRuntimeType;
34 import org.opendaylight.mdsal.binding.runtime.api.AugmentableRuntimeType;
35 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
36 import org.opendaylight.yangtools.yang.binding.Augmentable;
37 import org.opendaylight.yangtools.yang.binding.Augmentation;
38 import org.opendaylight.yangtools.yang.binding.BindingObject;
39 import org.opendaylight.yangtools.yang.binding.DataObject;
40 import org.opendaylight.yangtools.yang.binding.DataObjectStep;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
44 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
47 import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
48 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 /**
53  * This class is an implementation detail. It is public only due to technical reasons and may change at any time.
54  */
55 @Beta
56 public abstract sealed class DataObjectCodecContext<D extends DataObject, T extends CompositeRuntimeType>
57         extends AbstractDataObjectCodecContext<D, T> implements BindingDataObjectCodecTreeNode<D>
58         permits CaseCodecContext, ContainerLikeCodecContext, ListCodecContext, NotificationCodecContext {
59     private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
60
61     private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class,
62         AbstractDataObjectCodecContext.class, DataContainerNode.class);
63     private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class,
64         DataObjectCodecContext.class, DataContainerNode.class);
65     private static final VarHandle MISMATCHED_AUGMENTED;
66
67     static {
68         try {
69             MISMATCHED_AUGMENTED = MethodHandles.lookup().findVarHandle(DataObjectCodecContext.class,
70                 "mismatchedAugmented", ImmutableMap.class);
71         } catch (NoSuchFieldException | IllegalAccessException e) {
72             throw new ExceptionInInitializerError(e);
73         }
74     }
75
76     private final ImmutableMap<Class<?>, AugmentationCodecPrototype<?>> augmentToPrototype;
77     private final ImmutableMap<NodeIdentifier, Class<?>> yangToAugmentClass;
78     private final @NonNull Class<? extends CodecDataObject<?>> generatedClass;
79     private final MethodHandle proxyConstructor;
80
81     // Note this the content of this field depends only of invariants expressed as this class's fields or
82     // BindingRuntimeContext. It is only accessed via MISMATCHED_AUGMENTED above.
83     @SuppressWarnings("unused")
84     @SuppressFBWarnings(value = "URF_UNREAD_FIELD", justification = "https://github.com/spotbugs/spotbugs/issues/2749")
85     private volatile ImmutableMap<Class<?>, CommonDataObjectCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
86
87     DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype) {
88         this(prototype, new DataContainerAnalysis<>(prototype), null);
89     }
90
91     DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype,
92             final Class<? extends DataObject> caseClass) {
93         this(prototype, new DataContainerAnalysis<>(prototype, caseClass), null);
94     }
95
96     DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype, final Method keyMethod) {
97         this(prototype, new DataContainerAnalysis<>(prototype), keyMethod);
98     }
99
100     private DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype,
101             final DataContainerAnalysis<T> analysis, final Method keyMethod) {
102         super(prototype, analysis);
103
104         final var bindingClass = getBindingClass();
105
106         // Final bits: generate the appropriate class, As a side effect we identify what Augmentations are possible
107         final List<AugmentRuntimeType> possibleAugmentations;
108         final var loader = prototype().contextFactory().getLoader();
109         if (Augmentable.class.isAssignableFrom(bindingClass)) {
110             // Verify we have the appropriate backing runtimeType
111             final var runtimeType = prototype.runtimeType();
112             if (!(runtimeType instanceof AugmentableRuntimeType augmentableRuntimeType)) {
113                 throw new VerifyException(
114                     "Unexpected type %s backing augmenable %s".formatted(runtimeType, bindingClass));
115             }
116
117             possibleAugmentations = augmentableRuntimeType.augments();
118             generatedClass = CodecDataObjectGenerator.generateAugmentable(loader, bindingClass, analysis.leafContexts,
119                 analysis.daoProperties, keyMethod);
120         } else {
121             possibleAugmentations = List.of();
122             generatedClass = CodecDataObjectGenerator.generate(loader, bindingClass, analysis.leafContexts,
123                 analysis.daoProperties, keyMethod);
124         }
125
126         // All done: acquire the constructor: it is supposed to be public
127         final MethodHandle ctor;
128         try {
129             ctor = MethodHandles.publicLookup().findConstructor(generatedClass, CONSTRUCTOR_TYPE);
130         } catch (NoSuchMethodException | IllegalAccessException e) {
131             throw new LinkageError("Failed to find contructor for class " + generatedClass, e);
132         }
133
134         proxyConstructor = ctor.asType(DATAOBJECT_TYPE);
135
136         // Deal with augmentations, which are not something we analysis provides
137         final var augPathToBinding = new HashMap<NodeIdentifier, Class<?>>();
138         final var augClassToProto = new HashMap<Class<?>, AugmentationCodecPrototype<?>>();
139         for (var augment : possibleAugmentations) {
140             final var augProto = loadAugmentPrototype(augment);
141             if (augProto != null) {
142                 final var augBindingClass = augProto.javaClass();
143                 for (var childPath : augProto.getChildArgs()) {
144                     augPathToBinding.putIfAbsent(childPath, augBindingClass);
145                 }
146                 augClassToProto.putIfAbsent(augBindingClass, augProto);
147             }
148         }
149         yangToAugmentClass = ImmutableMap.copyOf(augPathToBinding);
150         augmentToPrototype = ImmutableMap.copyOf(augClassToProto);
151     }
152
153     @Override
154     final DataContainerPrototype<?, ?> pathChildPrototype(final Class<? extends DataObject> argType) {
155         final var child = super.pathChildPrototype(argType);
156         return child != null ? child : augmentToPrototype.get(argType);
157     }
158
159     @Override
160     final DataContainerPrototype<?, ?> streamChildPrototype(final Class<?> childClass) {
161         final var child = super.streamChildPrototype(childClass);
162         if (child == null && Augmentation.class.isAssignableFrom(childClass)) {
163             return getAugmentationProtoByClass(childClass);
164         }
165         return child;
166     }
167
168     @Override
169     final CodecContextSupplier yangChildSupplier(final NodeIdentifier arg) {
170         final var child = super.yangChildSupplier(arg);
171         if (child == null) {
172             final var augClass = yangToAugmentClass.get(arg);
173             if (augClass != null) {
174                 return augmentToPrototype.get(augClass);
175             }
176         }
177         return child;
178     }
179
180     private @Nullable AugmentationCodecPrototype<?> getAugmentationProtoByClass(final @NonNull Class<?> augmClass) {
181         final var childProto = augmentToPrototype.get(augmClass);
182         return childProto != null ? childProto : mismatchedAugmentationByClass(augmClass);
183     }
184
185     private @Nullable AugmentationCodecPrototype<?> mismatchedAugmentationByClass(final @NonNull Class<?> childClass) {
186         /*
187          * It is potentially mismatched valid augmentation - we look up equivalent augmentation using reflection
188          * and walk all stream child and compare augmentations classes if they are equivalent. When we find a match
189          * we'll cache it so we do not need to perform reflection operations again.
190          */
191         final var local = (ImmutableMap<Class<?>, AugmentationCodecPrototype<?>>) MISMATCHED_AUGMENTED.getAcquire(this);
192         final var mismatched = local.get(childClass);
193         return mismatched != null ? mismatched : loadMismatchedAugmentation(local, childClass);
194     }
195
196     private @Nullable AugmentationCodecPrototype<?> loadMismatchedAugmentation(
197             final ImmutableMap<Class<?>, AugmentationCodecPrototype<?>> oldMismatched,
198             final @NonNull Class<?> childClass) {
199         @SuppressWarnings("rawtypes")
200         final Class<?> augTarget = findAugmentationTarget((Class) childClass);
201         // Do not bother with proposals which are not augmentations of our class, or do not match what the runtime
202         // context would load.
203         if (getBindingClass().equals(augTarget) && belongsToRuntimeContext(childClass)) {
204             for (var realChild : augmentToPrototype.values()) {
205                 final var realClass = realChild.javaClass();
206                 if (Augmentation.class.isAssignableFrom(realClass) && isSubstitutionFor(childClass, realClass)) {
207                     return cacheMismatched(oldMismatched, childClass, realChild);
208                 }
209             }
210         }
211         LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
212         return null;
213     }
214
215     private @NonNull AugmentationCodecPrototype<?> cacheMismatched(
216             final @NonNull ImmutableMap<Class<?>, AugmentationCodecPrototype<?>> oldMismatched,
217             final @NonNull Class<?> childClass, final @NonNull AugmentationCodecPrototype<?> prototype) {
218         var expected = oldMismatched;
219         while (true) {
220             final var newMismatched =
221                 ImmutableMap.<Class<?>, CommonDataObjectCodecPrototype<?>>builderWithExpectedSize(expected.size() + 1)
222                     .putAll(expected)
223                     .put(childClass, prototype)
224                     .build();
225
226             final var witness = (ImmutableMap<Class<?>, AugmentationCodecPrototype<?>>)
227                 MISMATCHED_AUGMENTED.compareAndExchangeRelease(this, expected, newMismatched);
228             if (witness == expected) {
229                 LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
230                 return prototype;
231             }
232
233             expected = witness;
234             final var existing = expected.get(childClass);
235             if (existing != null) {
236                 LOG.trace("Using raced mismatched augmentation {} -> {} in {}", childClass, existing, this);
237                 return existing;
238             }
239         }
240     }
241
242     private boolean belongsToRuntimeContext(final Class<?> cls) {
243         final var ctx = prototype().contextFactory().getRuntimeContext();
244         final Class<?> loaded;
245         try {
246             loaded = ctx.loadClass(Type.of(cls));
247         } catch (ClassNotFoundException e) {
248             LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx, e);
249             return false;
250         }
251         return cls.equals(loaded);
252     }
253
254     private @Nullable AugmentationCodecPrototype<?> loadAugmentPrototype(final AugmentRuntimeType augment) {
255         // FIXME: in face of deviations this code should be looking at declared view, i.e. all possibilities at augment
256         //        declaration site
257         final var childPaths = augment.statement()
258             .streamEffectiveSubstatements(SchemaTreeEffectiveStatement.class)
259             .map(stmt -> new NodeIdentifier((QName) stmt.argument()))
260             .collect(ImmutableSet.toImmutableSet());
261
262         if (childPaths.isEmpty()) {
263             return null;
264         }
265
266         final var factory = prototype().contextFactory();
267         final GeneratedType javaType = augment.javaType();
268         final Class<? extends Augmentation<?>> augClass;
269         try {
270             augClass = factory.getRuntimeContext().loadClass(javaType);
271         } catch (final ClassNotFoundException e) {
272             throw new IllegalStateException(
273                 "RuntimeContext references type " + javaType + " but failed to load its class", e);
274         }
275         return new AugmentationCodecPrototype<>(augClass, augment, factory, childPaths);
276     }
277
278     @Override
279     @SuppressWarnings("unchecked")
280     Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(final DataContainerNode data) {
281         /**
282          * Due to augmentation fields are at same level as direct children the data of each augmentation needs to be
283          * aggregated into own container node, then only deserialized using associated prototype.
284          */
285         final var builders = new HashMap<Class<?>, DataContainerNodeBuilder<?, ?>>();
286         for (var childValue : data.body()) {
287             final var bindingClass = yangToAugmentClass.get(childValue.name());
288             if (bindingClass != null) {
289                 builders.computeIfAbsent(bindingClass,
290                     key -> ImmutableNodes.newContainerBuilder()
291                         .withNodeIdentifier(new NodeIdentifier(data.name().getNodeType())))
292                         .addChild(childValue);
293             }
294         }
295         @SuppressWarnings("rawtypes")
296         final var map = new HashMap();
297         for (final var entry : builders.entrySet()) {
298             final var bindingClass = entry.getKey();
299             final var codecProto = augmentToPrototype.get(bindingClass);
300             if (codecProto != null) {
301                 final var bindingObj = codecProto.getCodecContext().deserializeObject(entry.getValue().build());
302                 if (bindingObj != null) {
303                     map.put(bindingClass, bindingObj);
304                 }
305             }
306         }
307         return map;
308     }
309
310     @Override
311     public DataObjectStep<?> deserializePathArgument(final PathArgument arg) {
312         checkArgument(getDomPathArgument().equals(arg));
313         return bindingArg();
314     }
315
316     @Override
317     public PathArgument serializePathArgument(final DataObjectStep<?> step) {
318         checkArgument(bindingArg().equals(step));
319         return getDomPathArgument();
320     }
321
322     @Override
323     public NormalizedNode serialize(final D data) {
324         return serializeImpl(data);
325     }
326
327     @Override
328     public final BindingNormalizedNodeCachingCodec<D> createCachingCodec(
329             final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
330         return createCachingCodec(this, cacheSpecifier);
331     }
332
333     final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
334         return generatedClass;
335     }
336
337     @SuppressWarnings("checkstyle:illegalCatch")
338     final @NonNull D createBindingProxy(final DataContainerNode node) {
339         try {
340             return (D) proxyConstructor.invokeExact(this, node);
341         } catch (final Throwable e) {
342             Throwables.throwIfUnchecked(e);
343             throw new IllegalStateException(e);
344         }
345     }
346
347     @Override
348     Object deserializeObject(final NormalizedNode normalizedNode) {
349         return deserialize(normalizedNode);
350     }
351 }