001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.rest.server.springboot;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020import static org.apache.juneau.commons.utils.ThrowableUtils.*;
021
022import java.util.*;
023import java.util.concurrent.*;
024import java.util.concurrent.atomic.*;
025import java.util.function.*;
026
027import org.springframework.boot.context.properties.source.*;
028import org.springframework.core.env.*;
029
030/**
031 * Bridges a Spring {@link Environment} into the Juneau {@link org.apache.juneau.commons.settings.Settings Settings}
032 * singleton as a {@link org.apache.juneau.commons.settings.PropertySource PropertySource}.
033 *
034 * <p>
035 * Allows {@link org.apache.juneau.commons.inject.Value @Value("&#123;spring.property.key&#125;")} resolution
036 * against the same property sources that Spring Boot would resolve through
037 * {@code @org.springframework.beans.factory.annotation.Value}: {@code application.yaml},
038 * {@code application.properties}, command-line args, environment variables, and any custom
039 * {@code org.springframework.core.env.PropertySource} that Spring loads.
040 *
041 * <h2 class='section'>Lifecycle:</h2>
042 * <p>
043 * {@link SpringBeanStore} registers one instance per {@link org.springframework.context.ApplicationContext} in
044 * {@link org.apache.juneau.commons.settings.Settings Settings}, shared by every store on that context.  It is removed
045 * when every such store has been {@link SpringBeanStore#clear() cleared}, or when the context closes (for a
046 * {@link org.springframework.context.ConfigurableApplicationContext ConfigurableApplicationContext}).  Callers that
047 * want explicit lifecycle control can construct the source directly and add it via {@code Settings.get().addSource(...)};
048 * such instances are not shared.
049 *
050 * <h2 class='section'>Miss cache:</h2>
051 * <p>
052 * Juneau's builder keys (e.g. {@code MarshallingContext.unsortedProperties}) are not valid Spring Boot property names,
053 * so Spring walks every raw property source for each of them.  This source remembers up to 4096 such keys that were
054 * absent.  Every lookup checks the Environment's property-source list by identity (an added, removed or replaced
055 * source drops the cache) and re-checks {@link System#getProperty(String)} for a cached key.  Valid Boot names and
056 * {@code juneau.profiles.active} are never cached, and hits are never cached.  A source whose <em>contents</em> change
057 * in place (a mutated map, {@code MockEnvironment.setProperty}) is not detected for a key already cached as missing;
058 * call {@link #invalidate()} after such a change.  Setting {@code juneau.spring.missCache.disable=true} in the Spring
059 * Environment before the first lookup turns the cache off.
060 *
061 * <h2 class='section'>Lazy resolution:</h2>
062 * <p>
063 * The {@code Environment} is resolved lazily on the first {@link #get(String)} call so that
064 * constructors that build the source from an {@code ApplicationContext} do not interact with the
065 * context until a lookup actually happens.  This matters for tests that mock the context and assert
066 * "no interactions" until a Spring-side bean is requested.
067 *
068 * <h2 class='section'>Ordering:</h2>
069 * <p>
070 * Because {@code Settings} walks property sources in reverse insertion order, the Spring
071 * {@code Environment} bridge — registered when Spring creates the bean store — shadows any
072 * classpath-default {@code juneau.cfg} loaded earlier through the SPI-discovered
073 * {@code ConfigPropertySourceProvider}.  Programmatic {@code addSource()} calls made after the
074 * Spring context is built (e.g. from a user-provided microservice {@code Config}) still win.
075 *
076 * <h2 class='section'>See Also:</h2><ul>
077 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/ValueAnnotation">@Value Annotation Basics</a>
078 *    <li class='jc'>{@link SpringBeanStore}
079 * </ul>
080 */
081public class SpringEnvironmentPropertySource implements org.apache.juneau.commons.settings.PropertySource {
082
083   /** Soft cap on cached misses per bridge; same policy as J1037's source cache (copied, not referenced). */
084   static final int MISS_CACHE_MAX_ENTRIES = 4096;
085
086   /** Opt-out switch, read once at first resolve from the bridged Environment itself (never through Settings). */
087   private static final String MISS_CACHE_DISABLE_KEY = "juneau.spring.missCache.disable";
088
089   private final Supplier<Environment> envSupplier;
090
091   // Written inside resolve() before resolved; readers read resolved first, so plain fields are safely published.
092   private volatile boolean resolved;
093   @SuppressWarnings({
094      "java:S3077" // Publish-once reference: env is assigned before resolved is set (constructor or resolve()) and is never compound-mutated, so volatile visibility is sufficient.
095   })
096   private volatile Environment env;
097   private boolean cacheEnabled;
098
099   // The miss set for the source list it was built from; replaced, never edited, when the list changes.
100   private final AtomicReference<MissGeneration> generation = new AtomicReference<>();
101
102   /**
103    * Constructor that bridges a pre-built {@link Environment}.
104    *
105    * @param env The Spring environment to bridge.  Must not be <jk>null</jk>.
106    */
107   public SpringEnvironmentPropertySource(Environment env) {
108      this.env = Objects.requireNonNull(env, "env");
109      this.envSupplier = null;
110   }
111
112   /**
113    * Constructor that lazily resolves the {@link Environment} on first lookup.
114    *
115    * <p>
116    * Use this overload when wiring through {@link org.springframework.context.ApplicationContext}: pass
117    * {@code appContext::getEnvironment} so the application context isn't invoked until a lookup
118    * actually occurs.
119    *
120    * @param envSupplier Supplier of the Spring environment.  Must not be <jk>null</jk>.  May return
121    *    <jk>null</jk>, in which case this source returns
122    *    {@link org.apache.juneau.commons.settings.PropertyLookupResult#missing()} for every key.
123    */
124   public SpringEnvironmentPropertySource(Supplier<Environment> envSupplier) {
125      this.envSupplier = Objects.requireNonNull(envSupplier, "envSupplier");
126   }
127
128   private synchronized void resolve() {
129      if (resolved)  // HTT: another thread resolved between the caller's check and lock acquisition; a single-threaded test cannot force it
130         return;
131      // safeOpt swallows exceptions thrown by the supplier, e.g. a mocked ApplicationContext that returns null or
132      // throws during getEnvironment().
133      var e = nn(envSupplier) ? safeOpt(envSupplier::get).orElse(null) : env;
134      env = e;
135      cacheEnabled = e instanceof ConfigurableEnvironment && ! safeOpt(() -> e.getProperty(MISS_CACHE_DISABLE_KEY)).map(Boolean::parseBoolean).orElse(false);
136      resolved = true;
137   }
138
139   @SuppressWarnings({
140      "java:S3776" // Single lookup flow: profile piggyback, miss-cache check and property read share locals, so splitting it would only obscure the order of checks
141   })
142   @Override
143   public org.apache.juneau.commons.settings.PropertyLookupResult get(String name) {
144      if (! resolved)
145         resolve();
146      // Read env only after resolved: reading it first could see null, then resolved == true, and miss wrongly.
147      var e = env;
148      if (e == null)
149         return org.apache.juneau.commons.settings.PropertyLookupResult.missing();
150      // Profile piggyback: a Juneau config-profile activation lookup resolves to Spring's active profiles, so a
151      // Spring-Boot deployment has a single source of truth for which profiles are active.  Only answered when the
152      // caller has NOT explicitly set juneau.profiles.active as a property (that exact key wins if present).
153      if (eq(name, PROFILES_ACTIVE_KEY) && ! e.containsProperty(name)) {
154         var active = e.getActiveProfiles();
155         if (active.length > 0)  // getActiveProfiles() never returns null per the Environment contract.
156            return org.apache.juneau.commons.settings.PropertyLookupResult.present(o(String.join(",", active)));
157         return org.apache.juneau.commons.settings.PropertyLookupResult.missing();
158      }
159      var g = cacheEnabled && nn(name) ? currentGeneration((ConfigurableEnvironment)e) : null;
160      if (nn(g) && g.misses.contains(name)) {
161         // For an invalid Boot name, the raw systemProperties source (exact key) is the only one whose contents
162         // can change without a source-list change; systemEnvironment wraps System.getenv(), which cannot.
163         if (! g.hasSystemProperties || System.getProperty(name) == null)
164            return org.apache.juneau.commons.settings.PropertyLookupResult.missing();
165         g.misses.remove(name);
166      }
167      if (! e.containsProperty(name)) {
168         // Valid Boot names are never cached: Boot's relaxed binding can answer them from a changed source.
169         // isValid allocates, so it runs only here, on an uncached miss.
170         if (nn(g) && g.misses.size() < MISS_CACHE_MAX_ENTRIES && ! ConfigurationPropertyName.isValid(name))
171            g.misses.add(name);
172         return org.apache.juneau.commons.settings.PropertyLookupResult.missing();
173      }
174      // Spring's getProperty() returns null for a key mapped to an explicit null value, and throws
175      // IllegalArgumentException for an unresolvable nested placeholder.  o() maps the null to an empty value.
176      var v = e.getProperty(name);
177      return org.apache.juneau.commons.settings.PropertyLookupResult.present(o(v));
178   }
179
180   /**
181    * Clears this bridge's miss cache.
182    *
183    * <p>
184    * Needed only after a property source's contents change in place (for example a mutated
185    * {@code MapPropertySource} map, or {@code MockEnvironment.setProperty} in a test) for a key that is not a valid
186    * Spring Boot property name and that was already looked up and missed.  Adding, removing or replacing a property
187    * source, and setting a system property, are detected without it.  A lookup already in progress on another thread
188    * may still answer from the old cache; lookups that start after this method returns do not.
189    *
190    * @since 10.0.0
191    */
192   public void invalidate() {
193      generation.set(null);
194   }
195
196   /** @return The number of cached misses (tests). */
197   int missCount() {
198      var g = generation.get();
199      return g == null ? 0 : g.misses.size();
200   }
201
202   private MissGeneration currentGeneration(ConfigurableEnvironment e) {
203      var live = e.getPropertySources();
204      var g = generation.get();
205      if (nn(g) && g.matches(live))
206         return g;
207      // Racing threads may each build one; the loser's misses go to an unused generation, which only costs a walk.
208      g = new MissGeneration(live);
209      generation.set(g);
210      return g;
211   }
212
213   /**
214    * Cached misses for one snapshot of the Environment's property-source list.  A new generation replaces the old one
215    * when the list changes, so a miss computed against an old list can only land in a generation nobody reads.
216    */
217   private static final class MissGeneration {
218      final org.springframework.core.env.PropertySource<?>[] sources;
219      final boolean hasSystemProperties;
220      final Set<String> misses = ConcurrentHashMap.newKeySet();
221
222      MissGeneration(MutablePropertySources live) {
223         sources = live.stream().toArray(org.springframework.core.env.PropertySource<?>[]::new);
224         hasSystemProperties = Arrays.stream(sources).anyMatch(x -> StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME.equals(x.getName()));
225      }
226
227      // Identity, element by element, then count.  MutablePropertySources iterates its copy-on-write array without copying.
228      boolean matches(MutablePropertySources live) {
229         var i = 0;
230         for (var s : live) {
231            if (i >= sources.length || s != sources[i])
232               return false;
233            i++;
234         }
235         return i == sources.length;
236      }
237   }
238
239   /** The Juneau config-profile activation key that piggybacks on Spring's active profiles. */
240   private static final String PROFILES_ACTIVE_KEY = "juneau.profiles.active";
241}