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