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