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