Bump odlparent to 10.0.0
[yangtools.git] / codec / yang-data-codec-gson / src / main / java / org / opendaylight / yangtools / yang / data / codec / gson / JSONCodecFactorySupplier.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies, 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.yangtools.yang.data.codec.gson;
9
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.base.Stopwatch;
15 import com.google.common.cache.CacheBuilder;
16 import com.google.common.cache.CacheLoader;
17 import com.google.common.cache.LoadingCache;
18 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
19 import java.util.Optional;
20 import java.util.function.BiFunction;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.opendaylight.yangtools.yang.data.util.codec.CodecCache;
23 import org.opendaylight.yangtools.yang.data.util.codec.LazyCodecCache;
24 import org.opendaylight.yangtools.yang.data.util.codec.NoopCodecCache;
25 import org.opendaylight.yangtools.yang.data.util.codec.PrecomputedCodecCache;
26 import org.opendaylight.yangtools.yang.data.util.codec.SharedCodecCache;
27 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
28 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.stmt.DataTreeAwareEffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.DataTreeAwareEffectiveStatement.DataTreeNamespace;
31 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
32 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 /**
37  * API entry point for acquiring {@link JSONCodecFactory} instances.
38  *
39  * @author Robert Varga
40  */
41 @Beta
42 public enum JSONCodecFactorySupplier {
43     /**
44      * Source of {@link JSONCodecFactory} instances compliant with RFC7951.
45      */
46     RFC7951() {
47         @Override
48         JSONCodecFactory createFactory(final EffectiveModelContext context, final CodecCache<JSONCodec<?>> cache) {
49             return new RFC7951JSONCodecFactory(context, cache);
50         }
51     },
52     /**
53      * Source of {@link JSONCodecFactory} instances compliant with draft-lhotka-netmod-yang-json-02.
54      */
55     DRAFT_LHOTKA_NETMOD_YANG_JSON_02() {
56         @Override
57         JSONCodecFactory createFactory(final EffectiveModelContext context, final CodecCache<JSONCodec<?>> cache) {
58             return new Lhotka02JSONCodecFactory(context, cache);
59         }
60     };
61
62     private static final Logger LOG = LoggerFactory.getLogger(JSONCodecFactorySupplier.class);
63
64     private static final class EagerCacheLoader extends CacheLoader<EffectiveModelContext, JSONCodecFactory> {
65         private final BiFunction<EffectiveModelContext, CodecCache<JSONCodec<?>>, JSONCodecFactory> factorySupplier;
66
67         EagerCacheLoader(final BiFunction<EffectiveModelContext,
68                 CodecCache<JSONCodec<?>>, JSONCodecFactory> factorySupplier) {
69             this.factorySupplier = requireNonNull(factorySupplier);
70         }
71
72         @Override
73         public JSONCodecFactory load(final EffectiveModelContext key) {
74             final Stopwatch sw = Stopwatch.createStarted();
75             final LazyCodecCache<JSONCodec<?>> lazyCache = new LazyCodecCache<>();
76             final JSONCodecFactory lazy = factorySupplier.apply(key, lazyCache);
77             final SchemaInferenceStack stack = SchemaInferenceStack.of(key);
78
79             int visitedLeaves = 0;
80             for (ModuleEffectiveStatement module : key.getModuleStatements().values()) {
81                 visitedLeaves += codecsForChildren(lazy, stack, module);
82                 stack.clear();
83             }
84             sw.stop();
85
86             final PrecomputedCodecCache<JSONCodec<?>> cache = lazyCache.toPrecomputed();
87             LOG.debug("{} leaf nodes resulted in {} simple and {} complex codecs in {}", visitedLeaves,
88                 cache.simpleSize(), cache.complexSize(), sw);
89             return factorySupplier.apply(key, cache);
90         }
91
92         private static int codecsForChildren(final JSONCodecFactory lazy, final SchemaInferenceStack stack,
93                 final DataTreeAwareEffectiveStatement<?, ?> parent) {
94             int ret = 0;
95             for (var entry : parent.getAll(DataTreeNamespace.class).entrySet()) {
96                 final var child = entry.getValue();
97                 if (child instanceof DataTreeAwareEffectiveStatement) {
98                     stack.enterDataTree(entry.getKey());
99                     ret += codecsForChildren(lazy, stack, (DataTreeAwareEffectiveStatement<?, ?>) child);
100                     stack.exit();
101                 } else if (child instanceof TypedDataSchemaNode) {
102                     lazy.codecFor((TypedDataSchemaNode) child, stack);
103                     ++ret;
104                 }
105             }
106
107             return ret;
108         }
109     }
110
111     // Weak keys to retire the entry when SchemaContext goes away
112     private final LoadingCache<EffectiveModelContext, JSONCodecFactory> precomputed;
113
114     // Weak keys to retire the entry when SchemaContext goes away and to force identity-based lookup
115     private final LoadingCache<EffectiveModelContext, JSONCodecFactory> shared = CacheBuilder.newBuilder()
116         .weakKeys().build(new CacheLoader<EffectiveModelContext, JSONCodecFactory>() {
117             @Override
118             public JSONCodecFactory load(final EffectiveModelContext key) {
119                 return createFactory(key, new SharedCodecCache<>());
120             }
121         });
122
123     @SuppressFBWarnings(value = "MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR",
124         justification = "https://github.com/spotbugs/spotbugs/issues/1867")
125     JSONCodecFactorySupplier() {
126         precomputed = CacheBuilder.newBuilder().weakKeys().build(new EagerCacheLoader(this::createFactory));
127     }
128
129     /**
130      * Get a thread-safe, eagerly-caching {@link JSONCodecFactory} for a SchemaContext. This method can, and will,
131      * return the same instance as long as the associated SchemaContext is present. Returned object can be safely
132      * used by multiple threads concurrently. If the SchemaContext instance does not have a cached instance
133      * of {@link JSONCodecFactory}, it will be completely precomputed before this method will return.
134      *
135      * <p>
136      * Choosing this implementation is appropriate when the memory overhead of keeping a full codec tree is not as
137      * great a concern as predictable performance. When compared to the implementation returned by
138      * {@link #getShared(EffectiveModelContext)}, this implementation is expected to offer higher performance and have
139      * lower peak memory footprint when most of the SchemaContext is actually in use.
140      *
141      * <p>
142      * For call sites which do not want to pay the CPU cost of pre-computing this implementation, but still would like
143      * to use it if is available (by being populated by some other caller), you can use
144      * {@link #getPrecomputedIfAvailable(EffectiveModelContext)}.
145      *
146      * @param context SchemaContext instance
147      * @return A sharable {@link JSONCodecFactory}
148      * @throws NullPointerException if context is null
149      */
150     public @NonNull JSONCodecFactory getPrecomputed(final @NonNull EffectiveModelContext context) {
151         return verifyNotNull(precomputed.getUnchecked(context));
152     }
153
154     /**
155      * Get a thread-safe, eagerly-caching {@link JSONCodecFactory} for a SchemaContext, if it is available. This
156      * method is a non-blocking equivalent of {@link #getPrecomputed(EffectiveModelContext)} for use in code paths where
157      * the potential of having to pre-compute the implementation is not acceptable. One such scenario is when the
158      * code base wants to opportunistically take advantage of pre-computed version, but is okay with a fallback to
159      * a different implementation.
160      *
161      * @param context SchemaContext instance
162      * @return A sharable {@link JSONCodecFactory}, or absent if such an implementation is not available.
163      * @throws NullPointerException if context is null
164      */
165     public @NonNull Optional<JSONCodecFactory> getPrecomputedIfAvailable(final @NonNull EffectiveModelContext context) {
166         return Optional.ofNullable(precomputed.getIfPresent(context));
167     }
168
169     /**
170      * Get a thread-safe, lazily-caching {@link JSONCodecFactory} for a SchemaContext. This method can, and will,
171      * return the same instance as long as the associated EffectiveModelContext is present or the factory is not
172      * invalidated by memory pressure. Returned object can be safely used by multiple threads concurrently.
173      *
174      * <p>
175      * Choosing this implementation is a safe default, as it will not incur prohibitive blocking, nor will it tie up
176      * memory in face of pressure.
177      *
178      * @param context SchemaContext instance
179      * @return A sharable {@link JSONCodecFactory}
180      * @throws NullPointerException if context is null
181      */
182     public @NonNull JSONCodecFactory getShared(final @NonNull EffectiveModelContext context) {
183         return verifyNotNull(shared.getUnchecked(context));
184     }
185
186     /**
187      * Create a new thread-unsafe, lazily-caching {@link JSONCodecFactory} for a SchemaContext. This method will
188      * return distinct objects every time it is invoked. Returned object may not be used from multiple threads
189      * concurrently.
190      *
191      * <p>
192      * This implementation is appropriate for one-off serialization from a single thread. It will aggressively cache
193      * codecs for reuse and will tie them up in memory until the factory is freed.
194      *
195      * @param context SchemaContext instance
196      * @return A non-sharable {@link JSONCodecFactory}
197      * @throws NullPointerException if context is null
198      */
199     public @NonNull JSONCodecFactory createLazy(final @NonNull EffectiveModelContext context) {
200         return createFactory(context, new LazyCodecCache<>());
201     }
202
203     /**
204      * Create a simplistic, thread-safe {@link JSONCodecFactory} for a {@link EffectiveModelContext}. This method will
205      * return distinct objects every time it is invoked. Returned object may be use from multiple threads concurrently.
206      *
207      * <p>
208      * This implementation exists mostly for completeness only, as it does not perform any caching at all and each codec
209      * is computed every time it is requested. This may be useful in extremely constrained environments, where memory
210      * footprint is more critical than performance.
211      *
212      * @param context SchemaContext instance
213      * @return A non-sharable {@link JSONCodecFactory}
214      * @throws NullPointerException if context is null.
215      */
216     public @NonNull JSONCodecFactory createSimple(final @NonNull EffectiveModelContext context) {
217         return createFactory(context, NoopCodecCache.getInstance());
218     }
219
220     abstract @NonNull JSONCodecFactory createFactory(EffectiveModelContext context, CodecCache<JSONCodec<?>> cache);
221 }