All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.split.client.SplitClientBuilder Maven / Gradle / Ivy

package io.split.client;

import io.split.client.jmx.JmxMonitor;
import io.split.client.jmx.SplitJmxMonitor;
import io.split.client.metrics.CachedMetrics;
import io.split.client.metrics.FireAndForgetMetrics;
import io.split.client.metrics.HttpMetrics;
import io.split.engine.SDKReadinessGates;
import io.split.engine.experiments.SplitChangeFetcher;
import io.split.engine.experiments.SplitFetcher;
import io.split.engine.experiments.SplitParser;
import io.split.engine.experiments.RefreshableSplitFetcherProvider;
import io.split.engine.impressions.CachedTreatmentLog;
import io.split.engine.metrics.Metrics;
import io.split.engine.segments.RefreshableSegmentFetcher;
import io.split.engine.segments.SegmentChangeFetcher;
import io.split.engine.segments.SegmentFetcher;
import io.codigo.grammar.Treatments;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.filter.EncodingFilter;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.message.GZipEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Builds an instance of SplitClient.
 */
public class SplitClientBuilder {

    private static final Logger _log = LoggerFactory.getLogger(SplitClientBuilder.class);

    private static Random RANDOM = new Random();

    private static AtomicReference _client = new AtomicReference();
    private static Object _lock = new Object();


    public static SplitClient build(String apiToken) throws IOException, InterruptedException, TimeoutException {
        return build(apiToken, SplitClientConfig.builder().build());
    }

    /**
     *
     * @param apiToken the API token. MUST NOT be null
     * @param config parameters to control sdk construction. MUST NOT be null.
     *
     * @return a SplitClient
     *
     * @throws IOException if the SDK was being started in 'localhost' mode, but
     * there were problems reading the override file from disk.
     * @throws java.lang.InterruptedException if you asked to block until the sdk was
     * ready and the block was interrupted.
     * @throws java.util.concurrent.TimeoutException if you asked to block until the sdk was
     * ready and the timeout specified via config#ready() passed.
     */
    public static SplitClient build(String apiToken, SplitClientConfig config) throws IOException, InterruptedException, TimeoutException {
        if (_client.get() != null) {
            return _client.get();
        }

        synchronized (_lock) {
            // double check locking.
            if (_client.get() != null) {
                return _client.get();
            }

            if (LocalhostSplitClientBuilder.LOCALHOST.equals(apiToken)) {
                SplitClient splitClient = LocalhostSplitClientBuilder.build();
                _client.set(splitClient);
                registerJmxMonitor(splitClient);
                return splitClient;
            }

            Client client = ClientBuilder.newClient(new ClientConfig()
                    .property(ClientProperties.CONNECT_TIMEOUT, config.connectionTimeout())
                    .property(ClientProperties.READ_TIMEOUT, config.readTimeout())
                    .register(AddSplitHeadersFilter.instance(apiToken))
                    .register(ObjectMapperProvider.class)
                    .register(JacksonFeature.class)
                    .register(GZipEncoder.class)
                    .register(EncodingFilter.class));

            if (config.debugEnabled()) {
                client.register(new LoggingFilter());
            }

            WebTarget rootTarget = client.target(config.endpoint());
            WebTarget eventsRootTarget = client.target(config.eventsEndpoint());

            // Metrics
            HttpMetrics httpMetrics = HttpMetrics.create(eventsRootTarget);
            FireAndForgetMetrics uncachedFireAndForget = FireAndForgetMetrics.instance(httpMetrics, 2, 1000);

            SDKReadinessGates gates = new SDKReadinessGates();

            // Segments
            SegmentChangeFetcher segmentChangeFetcher = HttpSegmentChangeFetcher.create(rootTarget, uncachedFireAndForget);
            SegmentFetcher segmentFetcher = new RefreshableSegmentFetcher(segmentChangeFetcher,
                    findPollingPeriod(RANDOM, config.segmentsRefreshRate()),
                    config.numThreadsForSegmentFetch(),
                    gates);

            SplitParser splitParser = new SplitParser(segmentFetcher);

            // Feature Changes
            SplitChangeFetcher splitChangeFetcher = HttpSplitChangeFetcher.create(rootTarget, uncachedFireAndForget);


            RefreshableSplitFetcherProvider experimentFetcherProvider = new RefreshableSplitFetcherProvider(splitChangeFetcher, splitParser, findPollingPeriod(RANDOM, config.featuresRefreshRate()), gates);

            // Impressions
            CachedTreatmentLog treatmentLog = CachedTreatmentLog.instance(config.impressionsRefreshRate(), 1000, CachedTreatmentLogRemovalListener.create(eventsRootTarget));


            CachedMetrics cachedMetrics = new CachedMetrics(httpMetrics, TimeUnit.SECONDS.toMillis(config.metricsRefreshRate()));
            Metrics cachedFireAndForgetMetrics = FireAndForgetMetrics.instance(cachedMetrics, 2, 1000);

            // Now create the client.
            SplitClient splitClient = new SplitClientImpl(experimentFetcherProvider.getFetcher(), treatmentLog, cachedFireAndForgetMetrics);

            registerJmxMonitor(splitClient, experimentFetcherProvider.getFetcher(), segmentFetcher);

            _client.set(splitClient);

            if (config.blockUntilReady() > 0) {
                if (!gates.isSDKReady(config.blockUntilReady())) {
                    throw new TimeoutException("SDK was not ready in " + config.blockUntilReady() + " milliseconds");
                }
            }
            return splitClient;
        }

    }

    private static void registerJmxMonitor(SplitClient splitClient) {
        registerJmxMonitor(splitClient, null, null);
    }

    private static void registerJmxMonitor(SplitClient splitClient, SplitFetcher fetcher, SegmentFetcher segmentFetcher) {
        try {
            SplitJmxMonitor mbean = new SplitJmxMonitor(splitClient, fetcher, segmentFetcher);
            JmxMonitor.getInstance().registerMonitor("io.split.monitor", "Split", mbean);
        } catch (Exception e) {
            _log.warn("Unable to create JMX monitor", e);
        }
    }

    private static int findPollingPeriod(Random rand, int max) {
        int min = max/2;
        return rand.nextInt((max - min) + 1) + min;
    }


    public static void main(String ... args) throws IOException, InterruptedException, TimeoutException {

        if (args.length !=1 ) {
            System.out.println("Usage: ");
            System.exit(1);
            return;
        }

        SplitClientConfig config = SplitClientConfig.builder()
                .endpoint("http://localhost:8081/api")
                .enableDebug()
                .build();

        SplitClient client = SplitClientBuilder.build(args[0], config);

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

            for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                if ("exit".equals(line)) {
                    System.exit(0);
                }
                String[] userIdAndSplit = line.split(" ");

                if (userIdAndSplit.length != 2) {
                    System.out.println("Could not understand command");
                    continue;
                }

                boolean isOn = client.getTreatment(userIdAndSplit[0], userIdAndSplit[1]).equals("on");

                System.out.println(isOn ? Treatments.ON : Treatments.OFF);
            }

        } catch(IOException io){
            io.printStackTrace();
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy