index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/MovieHollowFactory.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.custom.HollowTypeAPI; import com.netflix.hollow.api.objects.provider.HollowFactory; import com.netflix.hollow.core.read.dataaccess.HollowTypeDataAccess; @SuppressWarnings("all") public class MovieHollowFactory<T extends Movie> extends HollowFactory<T> { @Override public T newHollowObject(HollowTypeDataAccess dataAccess, HollowTypeAPI typeAPI, int ordinal) { return (T)new Movie(((MovieTypeAPI)typeAPI).getDelegateLookupImpl(), ordinal); } @Override public T newCachedHollowObject(HollowTypeDataAccess dataAccess, HollowTypeAPI typeAPI, int ordinal) { return (T)new Movie(new MovieDelegateCachedImpl((MovieTypeAPI)typeAPI, ordinal), ordinal); } }
8,800
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/MovieDataAccessor.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.consumer.data.AbstractHollowDataAccessor; import com.netflix.hollow.core.index.key.PrimaryKey; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; @SuppressWarnings("all") public class MovieDataAccessor extends AbstractHollowDataAccessor<Movie> { public static final String TYPE = "Movie"; private AwardsAPI api; public MovieDataAccessor(HollowConsumer consumer) { super(consumer, TYPE); this.api = (AwardsAPI)consumer.getAPI(); } public MovieDataAccessor(HollowReadStateEngine rStateEngine, AwardsAPI api) { super(rStateEngine, TYPE); this.api = api; } public MovieDataAccessor(HollowReadStateEngine rStateEngine, AwardsAPI api, String ... fieldPaths) { super(rStateEngine, TYPE, fieldPaths); this.api = api; } public MovieDataAccessor(HollowReadStateEngine rStateEngine, AwardsAPI api, PrimaryKey primaryKey) { super(rStateEngine, TYPE, primaryKey); this.api = api; } @Override public Movie getRecord(int ordinal){ return api.getMovie(ordinal); } }
8,801
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/AwardDelegateLookupImpl.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.objects.delegate.HollowObjectAbstractDelegate; import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess; import com.netflix.hollow.core.schema.HollowObjectSchema; @SuppressWarnings("all") public class AwardDelegateLookupImpl extends HollowObjectAbstractDelegate implements AwardDelegate { private final AwardTypeAPI typeAPI; public AwardDelegateLookupImpl(AwardTypeAPI typeAPI) { this.typeAPI = typeAPI; } public long getId(int ordinal) { return typeAPI.getId(ordinal); } public Long getIdBoxed(int ordinal) { return typeAPI.getIdBoxed(ordinal); } public int getWinnerOrdinal(int ordinal) { return typeAPI.getWinnerOrdinal(ordinal); } public int getNomineesOrdinal(int ordinal) { return typeAPI.getNomineesOrdinal(ordinal); } public AwardTypeAPI getTypeAPI() { return typeAPI; } @Override public HollowObjectSchema getSchema() { return typeAPI.getTypeDataAccess().getSchema(); } @Override public HollowObjectTypeDataAccess getTypeDataAccess() { return typeAPI.getTypeDataAccess(); } }
8,802
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/Award.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.objects.HollowObject; @SuppressWarnings("all") public class Award extends HollowObject { public Award(AwardDelegate delegate, int ordinal) { super(delegate, ordinal); } public long getId() { return delegate().getId(ordinal); } public Long getIdBoxed() { return delegate().getIdBoxed(ordinal); } public Movie getWinner() { int refOrdinal = delegate().getWinnerOrdinal(ordinal); if(refOrdinal == -1) return null; return api().getMovie(refOrdinal); } public SetOfMovie getNominees() { int refOrdinal = delegate().getNomineesOrdinal(ordinal); if(refOrdinal == -1) return null; return api().getSetOfMovie(refOrdinal); } public AwardsAPI api() { return typeApi().getAPI(); } public AwardTypeAPI typeApi() { return delegate().getTypeAPI(); } protected AwardDelegate delegate() { return (AwardDelegate)delegate; } }
8,803
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/AwardsAPI.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.consumer.HollowConsumerAPI; import com.netflix.hollow.api.custom.HollowAPI; import com.netflix.hollow.api.objects.provider.HollowFactory; import com.netflix.hollow.api.objects.provider.HollowObjectCacheProvider; import com.netflix.hollow.api.objects.provider.HollowObjectFactoryProvider; import com.netflix.hollow.api.objects.provider.HollowObjectProvider; import com.netflix.hollow.api.sampling.HollowObjectCreationSampler; import com.netflix.hollow.api.sampling.HollowSamplingDirector; import com.netflix.hollow.api.sampling.SampleResult; import com.netflix.hollow.core.read.dataaccess.HollowDataAccess; import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess; import com.netflix.hollow.core.read.dataaccess.HollowSetTypeDataAccess; import com.netflix.hollow.core.read.dataaccess.HollowTypeDataAccess; import com.netflix.hollow.core.read.dataaccess.missing.HollowObjectMissingDataAccess; import com.netflix.hollow.core.read.dataaccess.missing.HollowSetMissingDataAccess; import com.netflix.hollow.core.type.HString; import com.netflix.hollow.core.type.StringHollowFactory; import com.netflix.hollow.core.type.StringTypeAPI; import com.netflix.hollow.core.util.AllHollowRecordCollection; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Objects; import java.util.Set; @SuppressWarnings("all") public class AwardsAPI extends HollowAPI implements HollowConsumerAPI.StringRetriever { private final HollowObjectCreationSampler objectCreationSampler; private final StringTypeAPI stringTypeAPI; private final MovieTypeAPI movieTypeAPI; private final SetOfMovieTypeAPI setOfMovieTypeAPI; private final AwardTypeAPI awardTypeAPI; private final HollowObjectProvider stringProvider; private final HollowObjectProvider movieProvider; private final HollowObjectProvider setOfMovieProvider; private final HollowObjectProvider awardProvider; public AwardsAPI(HollowDataAccess dataAccess) { this(dataAccess, Collections.<String>emptySet()); } public AwardsAPI(HollowDataAccess dataAccess, Set<String> cachedTypes) { this(dataAccess, cachedTypes, Collections.<String, HollowFactory<?>>emptyMap()); } public AwardsAPI(HollowDataAccess dataAccess, Set<String> cachedTypes, Map<String, HollowFactory<?>> factoryOverrides) { this(dataAccess, cachedTypes, factoryOverrides, null); } public AwardsAPI(HollowDataAccess dataAccess, Set<String> cachedTypes, Map<String, HollowFactory<?>> factoryOverrides, AwardsAPI previousCycleAPI) { super(dataAccess); HollowTypeDataAccess typeDataAccess; HollowFactory factory; objectCreationSampler = new HollowObjectCreationSampler("String","Movie","SetOfMovie","Award"); typeDataAccess = dataAccess.getTypeDataAccess("String"); if(typeDataAccess != null) { stringTypeAPI = new StringTypeAPI(this, (HollowObjectTypeDataAccess)typeDataAccess); } else { stringTypeAPI = new StringTypeAPI(this, new HollowObjectMissingDataAccess(dataAccess, "String")); } addTypeAPI(stringTypeAPI); factory = factoryOverrides.get("String"); if(factory == null) factory = new StringHollowFactory(); if(cachedTypes.contains("String")) { HollowObjectCacheProvider previousCacheProvider = null; if(previousCycleAPI != null && (previousCycleAPI.stringProvider instanceof HollowObjectCacheProvider)) previousCacheProvider = (HollowObjectCacheProvider) previousCycleAPI.stringProvider; stringProvider = new HollowObjectCacheProvider(typeDataAccess, stringTypeAPI, factory, previousCacheProvider); } else { stringProvider = new HollowObjectFactoryProvider(typeDataAccess, stringTypeAPI, factory); } typeDataAccess = dataAccess.getTypeDataAccess("Movie"); if(typeDataAccess != null) { movieTypeAPI = new MovieTypeAPI(this, (HollowObjectTypeDataAccess)typeDataAccess); } else { movieTypeAPI = new MovieTypeAPI(this, new HollowObjectMissingDataAccess(dataAccess, "Movie")); } addTypeAPI(movieTypeAPI); factory = factoryOverrides.get("Movie"); if(factory == null) factory = new MovieHollowFactory(); if(cachedTypes.contains("Movie")) { HollowObjectCacheProvider previousCacheProvider = null; if(previousCycleAPI != null && (previousCycleAPI.movieProvider instanceof HollowObjectCacheProvider)) previousCacheProvider = (HollowObjectCacheProvider) previousCycleAPI.movieProvider; movieProvider = new HollowObjectCacheProvider(typeDataAccess, movieTypeAPI, factory, previousCacheProvider); } else { movieProvider = new HollowObjectFactoryProvider(typeDataAccess, movieTypeAPI, factory); } typeDataAccess = dataAccess.getTypeDataAccess("SetOfMovie"); if(typeDataAccess != null) { setOfMovieTypeAPI = new SetOfMovieTypeAPI(this, (HollowSetTypeDataAccess)typeDataAccess); } else { setOfMovieTypeAPI = new SetOfMovieTypeAPI(this, new HollowSetMissingDataAccess(dataAccess, "SetOfMovie")); } addTypeAPI(setOfMovieTypeAPI); factory = factoryOverrides.get("SetOfMovie"); if(factory == null) factory = new SetOfMovieHollowFactory(); if(cachedTypes.contains("SetOfMovie")) { HollowObjectCacheProvider previousCacheProvider = null; if(previousCycleAPI != null && (previousCycleAPI.setOfMovieProvider instanceof HollowObjectCacheProvider)) previousCacheProvider = (HollowObjectCacheProvider) previousCycleAPI.setOfMovieProvider; setOfMovieProvider = new HollowObjectCacheProvider(typeDataAccess, setOfMovieTypeAPI, factory, previousCacheProvider); } else { setOfMovieProvider = new HollowObjectFactoryProvider(typeDataAccess, setOfMovieTypeAPI, factory); } typeDataAccess = dataAccess.getTypeDataAccess("Award"); if(typeDataAccess != null) { awardTypeAPI = new AwardTypeAPI(this, (HollowObjectTypeDataAccess)typeDataAccess); } else { awardTypeAPI = new AwardTypeAPI(this, new HollowObjectMissingDataAccess(dataAccess, "Award")); } addTypeAPI(awardTypeAPI); factory = factoryOverrides.get("Award"); if(factory == null) factory = new AwardHollowFactory(); if(cachedTypes.contains("Award")) { HollowObjectCacheProvider previousCacheProvider = null; if(previousCycleAPI != null && (previousCycleAPI.awardProvider instanceof HollowObjectCacheProvider)) previousCacheProvider = (HollowObjectCacheProvider) previousCycleAPI.awardProvider; awardProvider = new HollowObjectCacheProvider(typeDataAccess, awardTypeAPI, factory, previousCacheProvider); } else { awardProvider = new HollowObjectFactoryProvider(typeDataAccess, awardTypeAPI, factory); } } /* * set expectation here*/ public void detachCaches() { if(stringProvider instanceof HollowObjectCacheProvider) ((HollowObjectCacheProvider)stringProvider).detach(); if(movieProvider instanceof HollowObjectCacheProvider) ((HollowObjectCacheProvider)movieProvider).detach(); if(setOfMovieProvider instanceof HollowObjectCacheProvider) ((HollowObjectCacheProvider)setOfMovieProvider).detach(); if(awardProvider instanceof HollowObjectCacheProvider) ((HollowObjectCacheProvider)awardProvider).detach(); } public StringTypeAPI getStringTypeAPI() { return stringTypeAPI; } public MovieTypeAPI getMovieTypeAPI() { return movieTypeAPI; } public SetOfMovieTypeAPI getSetOfMovieTypeAPI() { return setOfMovieTypeAPI; } public AwardTypeAPI getAwardTypeAPI() { return awardTypeAPI; } public Collection<HString> getAllHString() { HollowTypeDataAccess tda = Objects.requireNonNull(getDataAccess().getTypeDataAccess("String"), "type not loaded or does not exist in dataset; type=String"); return new AllHollowRecordCollection<HString>(tda.getTypeState()) { protected HString getForOrdinal(int ordinal) { return getHString(ordinal); } }; } public HString getHString(int ordinal) { objectCreationSampler.recordCreation(0); return (HString)stringProvider.getHollowObject(ordinal); } public Collection<Movie> getAllMovie() { HollowTypeDataAccess tda = Objects.requireNonNull(getDataAccess().getTypeDataAccess("Movie"), "type not loaded or does not exist in dataset; type=Movie"); return new AllHollowRecordCollection<Movie>(tda.getTypeState()) { protected Movie getForOrdinal(int ordinal) { return getMovie(ordinal); } }; } public Movie getMovie(int ordinal) { objectCreationSampler.recordCreation(1); return (Movie)movieProvider.getHollowObject(ordinal); } public Collection<SetOfMovie> getAllSetOfMovie() { HollowTypeDataAccess tda = Objects.requireNonNull(getDataAccess().getTypeDataAccess("SetOfMovie"), "type not loaded or does not exist in dataset; type=SetOfMovie"); return new AllHollowRecordCollection<SetOfMovie>(tda.getTypeState()) { protected SetOfMovie getForOrdinal(int ordinal) { return getSetOfMovie(ordinal); } }; } public SetOfMovie getSetOfMovie(int ordinal) { objectCreationSampler.recordCreation(2); return (SetOfMovie)setOfMovieProvider.getHollowObject(ordinal); } public Collection<Award> getAllAward() { HollowTypeDataAccess tda = Objects.requireNonNull(getDataAccess().getTypeDataAccess("Award"), "type not loaded or does not exist in dataset; type=Award"); return new AllHollowRecordCollection<Award>(tda.getTypeState()) { protected Award getForOrdinal(int ordinal) { return getAward(ordinal); } }; } public Award getAward(int ordinal) { objectCreationSampler.recordCreation(3); return (Award)awardProvider.getHollowObject(ordinal); } public void setSamplingDirector(HollowSamplingDirector director) { super.setSamplingDirector(director); objectCreationSampler.setSamplingDirector(director); } public Collection<SampleResult> getObjectCreationSamplingResults() { return objectCreationSampler.getSampleResults(); } }
8,804
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/MoviePrimaryKeyIndex.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.consumer.index.AbstractHollowUniqueKeyIndex; import com.netflix.hollow.api.consumer.index.HollowUniqueKeyIndex; import com.netflix.hollow.core.schema.HollowObjectSchema; /** * @deprecated see {@link com.netflix.hollow.api.consumer.index.UniqueKeyIndex} which can be built as follows: * <pre>{@code * UniqueKeyIndex<Movie, K> uki = UniqueKeyIndex.from(consumer, Movie.class) * .usingBean(k); * Movie m = uki.findMatch(k); * }</pre> * where {@code K} is a class declaring key field paths members, annotated with * {@link com.netflix.hollow.api.consumer.index.FieldPath}, and {@code k} is an instance of * {@code K} that is the key to find the unique {@code Movie} object. */ @Deprecated @SuppressWarnings("all") public class MoviePrimaryKeyIndex extends AbstractHollowUniqueKeyIndex<AwardsAPI, Movie> implements HollowUniqueKeyIndex<Movie> { public MoviePrimaryKeyIndex(HollowConsumer consumer) { this(consumer, true); } public MoviePrimaryKeyIndex(HollowConsumer consumer, boolean isListenToDataRefresh) { this(consumer, isListenToDataRefresh, ((HollowObjectSchema)consumer.getStateEngine().getNonNullSchema("Movie")).getPrimaryKey().getFieldPaths()); } public MoviePrimaryKeyIndex(HollowConsumer consumer, String... fieldPaths) { this(consumer, true, fieldPaths); } public MoviePrimaryKeyIndex(HollowConsumer consumer, boolean isListenToDataRefresh, String... fieldPaths) { super(consumer, "Movie", isListenToDataRefresh, fieldPaths); } @Override public Movie findMatch(Object... keys) { int ordinal = idx.getMatchingOrdinal(keys); if(ordinal == -1) return null; return api.getMovie(ordinal); } }
8,805
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/AwardDelegateCachedImpl.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.custom.HollowTypeAPI; import com.netflix.hollow.api.objects.delegate.HollowCachedDelegate; import com.netflix.hollow.api.objects.delegate.HollowObjectAbstractDelegate; import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess; import com.netflix.hollow.core.schema.HollowObjectSchema; @SuppressWarnings("all") public class AwardDelegateCachedImpl extends HollowObjectAbstractDelegate implements HollowCachedDelegate, AwardDelegate { private final Long id; private final int winnerOrdinal; private final int nomineesOrdinal; private AwardTypeAPI typeAPI; public AwardDelegateCachedImpl(AwardTypeAPI typeAPI, int ordinal) { this.id = typeAPI.getIdBoxed(ordinal); this.winnerOrdinal = typeAPI.getWinnerOrdinal(ordinal); this.nomineesOrdinal = typeAPI.getNomineesOrdinal(ordinal); this.typeAPI = typeAPI; } public long getId(int ordinal) { if(id == null) return Long.MIN_VALUE; return id.longValue(); } public Long getIdBoxed(int ordinal) { return id; } public int getWinnerOrdinal(int ordinal) { return winnerOrdinal; } public int getNomineesOrdinal(int ordinal) { return nomineesOrdinal; } @Override public HollowObjectSchema getSchema() { return typeAPI.getTypeDataAccess().getSchema(); } @Override public HollowObjectTypeDataAccess getTypeDataAccess() { return typeAPI.getTypeDataAccess(); } public AwardTypeAPI getTypeAPI() { return typeAPI; } public void updateTypeAPI(HollowTypeAPI typeAPI) { this.typeAPI = (AwardTypeAPI) typeAPI; } }
8,806
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/Movie.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.consumer.index.UniqueKeyIndex; import com.netflix.hollow.api.objects.HollowObject; import com.netflix.hollow.core.type.HString; @SuppressWarnings("all") public class Movie extends HollowObject { public Movie(MovieDelegate delegate, int ordinal) { super(delegate, ordinal); } public long getId() { return delegate().getId(ordinal); } public Long getIdBoxed() { return delegate().getIdBoxed(ordinal); } public String getTitle() { return delegate().getTitle(ordinal); } public boolean isTitleEqual(String testValue) { return delegate().isTitleEqual(ordinal, testValue); } public HString getTitleHollowReference() { int refOrdinal = delegate().getTitleOrdinal(ordinal); if(refOrdinal == -1) return null; return api().getHString(refOrdinal); } public int getYear() { return delegate().getYear(ordinal); } public Integer getYearBoxed() { return delegate().getYearBoxed(ordinal); } public AwardsAPI api() { return typeApi().getAPI(); } public MovieTypeAPI typeApi() { return delegate().getTypeAPI(); } protected MovieDelegate delegate() { return (MovieDelegate)delegate; } /** * Creates a unique key index for {@code Movie} that has a primary key. * The primary key is represented by the type {@code long}. * <p> * By default the unique key index will not track updates to the {@code consumer} and thus * any changes will not be reflected in matched results. To track updates the index must be * {@link HollowConsumer#addRefreshListener(HollowConsumer.RefreshListener) registered} * with the {@code consumer} * * @param consumer the consumer * @return the unique key index */ public static UniqueKeyIndex<Movie, Long> uniqueIndex(HollowConsumer consumer) { return UniqueKeyIndex.from(consumer, Movie.class) .bindToPrimaryKey() .usingPath("id", long.class); } }
8,807
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/generated/SetOfMovieHollowFactory.java
package com.netflix.hollow.test.generated; import com.netflix.hollow.api.custom.HollowTypeAPI; import com.netflix.hollow.api.objects.delegate.HollowSetCachedDelegate; import com.netflix.hollow.api.objects.provider.HollowFactory; import com.netflix.hollow.core.read.dataaccess.HollowTypeDataAccess; @SuppressWarnings("all") public class SetOfMovieHollowFactory<T extends SetOfMovie> extends HollowFactory<T> { @Override public T newHollowObject(HollowTypeDataAccess dataAccess, HollowTypeAPI typeAPI, int ordinal) { return (T)new SetOfMovie(((SetOfMovieTypeAPI)typeAPI).getDelegateLookupImpl(), ordinal); } @Override public T newCachedHollowObject(HollowTypeDataAccess dataAccess, HollowTypeAPI typeAPI, int ordinal) { return (T)new SetOfMovie(new HollowSetCachedDelegate((SetOfMovieTypeAPI)typeAPI, ordinal), ordinal); } }
8,808
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/model/Award.java
package com.netflix.hollow.test.model; import java.util.Set; public class Award { long id; Movie winner; Set<Movie> nominees; public Award(long id, Movie winner, Set<Movie> nominees) { this.id = id; this.winner = winner; this.nominees = nominees; } }
8,809
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/test/model/Movie.java
package com.netflix.hollow.test.model; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; @HollowPrimaryKey(fields = {"id"}) public class Movie { long id; String title; int year; public Movie(long id, String title, int year) { this.id = id; this.title = title; this.year = year; } }
8,810
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/metrics/HollowProducerMetricsTests.java
package com.netflix.hollow.api.metrics; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.HollowProducerFakeListener; import com.netflix.hollow.api.producer.HollowProducerListener; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowProducerMetricsTests { private InMemoryBlobStore blobStore; private HollowProducerMetrics hollowProducerMetrics; private HollowProducerFakeListener hollowProducerFakeListener; @Before public void setUp() { blobStore = new InMemoryBlobStore(); hollowProducerMetrics = new HollowProducerMetrics(); hollowProducerFakeListener = new HollowProducerFakeListener(); } @Test public void metricsDoNotBreakWithNullStateEngineInSuccess() { HollowProducerListener.ProducerStatus producerStatus = hollowProducerFakeListener.getSuccessFakeStatus(1L); hollowProducerMetrics.updateCycleMetrics(producerStatus); Assert.assertEquals(hollowProducerMetrics.getCyclesSucceeded(), 1); } @Test public void metricsDoNotBreakWithNullStateEngineInFail() { HollowProducerListener.ProducerStatus producerStatus = hollowProducerFakeListener.getFailFakeStatus(1L); hollowProducerMetrics.updateCycleMetrics(producerStatus); Assert.assertEquals(hollowProducerMetrics.getCycleFailed(), 1); } @Test public void metricsWhenPublishingSnapshot() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); producer.runCycle(new HollowProducer.Populator() { public void populate(HollowProducer.WriteState state) throws Exception { state.add(Integer.valueOf(1)); } }); HollowProducerMetrics hollowProducerMetrics = producer.getMetrics(); Assert.assertEquals(hollowProducerMetrics.getCyclesSucceeded(), 1); Assert.assertEquals(hollowProducerMetrics.getCyclesCompleted(), 1); Assert.assertEquals(hollowProducerMetrics.getTotalPopulatedOrdinals(), 1); Assert.assertEquals(hollowProducerMetrics.getSnapshotsCompleted(), 1); } @Test public void metricsWhenPublishingFails() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); try { producer.runCycle(new HollowProducer.Populator() { public void populate(HollowProducer.WriteState state) throws Exception { state.add(null); } }); } catch (Exception ignored){ } HollowProducerMetrics hollowProducerMetrics = producer.getMetrics(); Assert.assertEquals(hollowProducerMetrics.getCyclesSucceeded(), 0); Assert.assertEquals(hollowProducerMetrics.getCyclesCompleted(), 1); Assert.assertEquals(hollowProducerMetrics.getCycleFailed(), 1); } }
8,811
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/metrics/HollowMetricsCollectorTests.java
package com.netflix.hollow.api.metrics; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowMetricsCollectorTests { private InMemoryBlobStore blobStore; @Before public void setUp() { blobStore = new InMemoryBlobStore(); } @Test public void testNullMetricsCollector() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); long version = producer.runCycle(new HollowProducer.Populator() { public void populate(HollowProducer.WriteState state) throws Exception { state.add(Integer.valueOf(1)); } }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore) .withMetricsCollector(null) .build(); consumer.triggerRefreshTo(version); } @Test public void metricsCollectorWhenPublishingSnapshot() { FakePublisherHollowMetricsCollector metricsCollector = new FakePublisherHollowMetricsCollector(); HollowProducer producer = HollowProducer.withPublisher(blobStore) .withMetricsCollector(metricsCollector) .withBlobStager(new HollowInMemoryBlobStager()) .build(); producer.runCycle(new HollowProducer.Populator() { public void populate(HollowProducer.WriteState state) throws Exception { state.add(Integer.valueOf(1)); } }); HollowProducerMetrics hollowProducerMetrics = metricsCollector.getMetrics(); Assert.assertEquals(metricsCollector.getMetricsCollected(), true); Assert.assertEquals(hollowProducerMetrics.getCyclesSucceeded(), 1); Assert.assertEquals(hollowProducerMetrics.getCyclesCompleted(), 1); Assert.assertEquals(hollowProducerMetrics.getTotalPopulatedOrdinals(), 1); Assert.assertEquals(hollowProducerMetrics.getSnapshotsCompleted(), 1); } @Test public void metricsCollectorWhenLoadingSnapshot() { FakeConsumerHollowMetricsCollector metricsCollector = new FakeConsumerHollowMetricsCollector(); HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); long version = producer.runCycle(new HollowProducer.Populator() { public void populate(HollowProducer.WriteState state) throws Exception { state.add(Integer.valueOf(1)); } }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore) .withMetricsCollector(metricsCollector) .build(); consumer.triggerRefreshTo(version); HollowConsumerMetrics hollowConsumerMetrics = metricsCollector.getMetrics(); Assert.assertEquals(metricsCollector.getMetricsCollected(), true); Assert.assertEquals(version, consumer.getCurrentVersionId()); Assert.assertEquals(hollowConsumerMetrics.getCurrentVersion(), consumer.getCurrentVersionId()); Assert.assertEquals(hollowConsumerMetrics.getRefreshSucceded(), 1); Assert.assertEquals(hollowConsumerMetrics.getTotalPopulatedOrdinals(), 1); } private static class FakePublisherHollowMetricsCollector extends HollowMetricsCollector<HollowProducerMetrics> { private HollowProducerMetrics metrics; private boolean metricsCollected; @Override public void collect(HollowProducerMetrics metrics) { this.metrics = metrics; this.metricsCollected = true; } public HollowProducerMetrics getMetrics() { return this.metrics; } public boolean getMetricsCollected() { return this.metricsCollected; } } private static class FakeConsumerHollowMetricsCollector extends HollowMetricsCollector<HollowConsumerMetrics> { private HollowConsumerMetrics metrics; private boolean metricsCollected; @Override public void collect(HollowConsumerMetrics metrics) { this.metrics = metrics; this.metricsCollected = true; } public HollowConsumerMetrics getMetrics() { return this.metrics; } public boolean getMetricsCollected() { return this.metricsCollected; } } }
8,812
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/metrics/HollowConsumerMetricsTests.java
package com.netflix.hollow.api.metrics; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowConsumerMetricsTests { private InMemoryBlobStore blobStore; @Before public void setUp() { blobStore = new InMemoryBlobStore(); } @Test public void metricsWhenLoadingSnapshot() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); long version = producer.runCycle(new HollowProducer.Populator() { public void populate(HollowProducer.WriteState state) throws Exception { state.add(Integer.valueOf(1)); } }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(version); HollowConsumerMetrics hollowConsumerMetrics = consumer.getMetrics(); Assert.assertEquals(version, consumer.getCurrentVersionId()); Assert.assertEquals(hollowConsumerMetrics.getCurrentVersion(), consumer.getCurrentVersionId()); Assert.assertEquals(hollowConsumerMetrics.getRefreshSucceded(), 1); Assert.assertEquals(hollowConsumerMetrics.getTotalPopulatedOrdinals(), 1); } @Test public void metricsWhenRefreshFails() { HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); try { consumer.triggerRefreshTo(0); } catch (Exception ignored) { } HollowConsumerMetrics hollowConsumerMetrics = consumer.getMetrics(); Assert.assertEquals(hollowConsumerMetrics.getRefreshFailed(), 1); Assert.assertEquals(hollowConsumerMetrics.getTotalPopulatedOrdinals(), 0); } @Test public void metricsWhenRefreshFailsDoNotRestartPreviousOnes() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); /// Showing verbose version of `runCycle(producer, 1);` long version = producer.runCycle(new HollowProducer.Populator() { public void populate(HollowProducer.WriteState state) throws Exception { state.add(Integer.valueOf(1)); } }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(version); try { consumer.triggerRefreshTo(0); } catch (Exception ignored) { } HollowConsumerMetrics hollowConsumerMetrics = consumer.getMetrics(); Assert.assertEquals(hollowConsumerMetrics.getRefreshFailed(), 1); Assert.assertEquals(hollowConsumerMetrics.getRefreshSucceded(), 1); Assert.assertEquals(hollowConsumerMetrics.getTotalPopulatedOrdinals(), 1); } }
8,813
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/HollowProducerTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.producer; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.objects.delegate.HollowObjectGenericDelegate; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.api.producer.HollowProducer.Blob; import com.netflix.hollow.api.producer.HollowProducer.Blob.Type; import com.netflix.hollow.api.producer.HollowProducer.HeaderBlob; import com.netflix.hollow.api.producer.HollowProducer.ReadState; import com.netflix.hollow.api.producer.HollowProducerListener.ProducerStatus; import com.netflix.hollow.api.producer.HollowProducerListener.RestoreStatus; import com.netflix.hollow.api.producer.HollowProducerListener.Status; import com.netflix.hollow.api.producer.enforcer.BasicSingleProducerEnforcer; import com.netflix.hollow.api.producer.enforcer.SingleProducerEnforcer; import com.netflix.hollow.api.producer.fs.HollowFilesystemAnnouncer; import com.netflix.hollow.core.HollowBlobHeader; import com.netflix.hollow.core.read.engine.HollowBlobHeaderReader; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.objectmapper.HollowTypeName; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowProducerTest { private static final String NAMESPACE = "hollowProducerTest"; private File tmpFolder; private HollowObjectSchema schema; private HollowConsumer.BlobRetriever blobRetriever; private Map<Long, Blob> blobMap = new HashMap<>(); private Map<Long, File> blobFileMap = new HashMap<>(); private Map<Long, HeaderBlob> headerBlobMap = new HashMap<>(); private Map<Long, File> headerFileMap = new HashMap<>(); private ProducerStatus lastProducerStatus; private RestoreStatus lastRestoreStatus; @Before public void setUp() throws IOException { schema = new HollowObjectSchema("TestPojo", 2, "id"); schema.addField("id", FieldType.INT); schema.addField("v1", FieldType.INT); tmpFolder = Files.createTempDirectory(null).toFile(); blobRetriever = new FakeBlobRetriever(NAMESPACE, tmpFolder.getAbsolutePath()); } private HollowProducer createProducer(File tmpFolder, HollowObjectSchema... schemas) { HollowProducer producer = HollowProducer.withPublisher(new FakeBlobPublisher()) .withAnnouncer(new HollowFilesystemAnnouncer(tmpFolder.toPath())).build(); if (schemas != null && schemas.length > 0) { producer.initializeDataModel(schemas); } producer.addListener(new FakeProducerListener()); return producer; } @After public void tearDown() { for (File file : blobFileMap.values()) { System.out.println("\t deleting: " + file); file.delete(); } } @Test public void testPopulateNoChangesVersion() { HollowProducer producer = createProducer(tmpFolder); long v1 = producer.runCycle(ws -> { ws.add(1); }); Assert.assertEquals(producer.getCycleCountWithPrimaryStatus(), 1); // Run cycle with no changes long v2 = producer.runCycle(ws -> { ws.add(1); }); Assert.assertEquals(producer.getCycleCountWithPrimaryStatus(), 2); long v3 = producer.runCycle(ws -> { ws.add(2); }); Assert.assertEquals(producer.getCycleCountWithPrimaryStatus(), 3); Assert.assertEquals(v1, v2); Assert.assertTrue(v3 > v2); } @Test public void testNotPrimaryProducerVersion() { BasicSingleProducerEnforcer enforcer = new BasicSingleProducerEnforcer(); HollowProducer producer = HollowProducer.withPublisher(new FakeBlobPublisher()) .withSingleProducerEnforcer(enforcer) .withAnnouncer(new HollowFilesystemAnnouncer(tmpFolder.toPath())) .build(); producer.addListener(new FakeProducerListener()); long v1 = producer.runCycle(ws -> { ws.add(1); }); enforcer.disable(); // Run cycle as not the primary producer long v2 = producer.runCycle(ws -> { ws.add(1); }); Assert.assertEquals(producer.getCycleCountWithPrimaryStatus(), 0); // Run cycle as the primary producer enforcer.enable(); long v3 = producer.runCycle(ws -> { ws.add(2); }); Assert.assertEquals(v1, v2); Assert.assertTrue(v3 > v2); Assert.assertEquals(producer.getCycleCountWithPrimaryStatus(), 1); } @Test public void testNonPrimaryCantPublish() { // when producer starts cycle as primary but relinquishes primary status sometime before publish BasicSingleProducerEnforcer enforcer = new BasicSingleProducerEnforcer(); HollowProducer producer = HollowProducer.withPublisher(new FakeBlobPublisher()) .withSingleProducerEnforcer(enforcer) .withAnnouncer(new HollowFilesystemAnnouncer(tmpFolder.toPath())) .build(); producer.runCycle(ws -> { ws.add(1); }); producer.addListener(new ProducerYieldsPrimaryBeforePublish(enforcer)); try { producer.runCycle(ws -> { ws.add(2); }); } catch (IllegalStateException e) { Assert.assertTrue(e instanceof HollowProducer.NotPrimaryMidCycleException); Assert.assertEquals("Publish failed primary (aka leader) check", e.getMessage()); Assert.assertEquals(producer.getCycleCountWithPrimaryStatus(), 2); // counted as cycle ran for the producer with primary status but lost status mid cycle. Doesn't matter as the next cycle result in a no-op. return; } Assert.fail(); } @Test public void testNonPrimaryProducerCantAnnounce() { // when producer starts cycle as primary but relinquishes primary status sometime before announcement BasicSingleProducerEnforcer enforcer = new BasicSingleProducerEnforcer(); HollowProducer producer = HollowProducer.withPublisher(new FakeBlobPublisher()) .withSingleProducerEnforcer(enforcer) .withAnnouncer(new HollowFilesystemAnnouncer(tmpFolder.toPath())) .build(); producer.addListener(new ProducerYieldsPrimaryBeforeAnnounce(enforcer)); try { producer.runCycle(ws -> { ws.add(1); }); } catch (HollowProducer.NotPrimaryMidCycleException e) { Assert.assertEquals("Announcement failed primary (aka leader) check", e.getMessage()); Assert.assertEquals(producer.getCycleCountWithPrimaryStatus(), 1); // counted as cycle ran for producer with primary status return; } Assert.fail(); } @Test public void testRestoreFailure() { HollowProducer producer = createProducer(tmpFolder, schema); long fakeVersion = 101; try { producer.restore(fakeVersion, blobRetriever); Assert.fail(); } catch(Exception expected) { } Assert.assertNotNull(lastRestoreStatus); Assert.assertEquals(Status.FAIL, lastRestoreStatus.getStatus()); Assert.assertEquals(producer.getCycleCountWithPrimaryStatus(), 0); } @Test public void testPublishAndRestore() { HollowProducer producer = createProducer(tmpFolder, schema); long version = testPublishV1(producer, 2, 10); producer.restore(version, blobRetriever); Assert.assertNotNull(lastRestoreStatus); Assert.assertEquals(Status.SUCCESS, lastRestoreStatus.getStatus()); Assert.assertEquals("Version should be the same", version, lastRestoreStatus.getDesiredVersion()); Assert.assertEquals(producer.getCycleCountWithPrimaryStatus(), 1); } @Test public void testHeaderPublish() throws IOException { HollowProducer producer = createProducer(tmpFolder, schema); long version = testPublishV1(producer, 2, 10); HollowConsumer.HeaderBlob headerBlob = blobRetriever.retrieveHeaderBlob(version); Assert.assertNotNull(headerBlob); Assert.assertEquals(version, headerBlob.getVersion()); HollowBlobHeader header = new HollowBlobHeaderReader().readHeader(headerBlob.getInputStream()); Assert.assertNotNull(header); Assert.assertEquals(1, header.getSchemas().size()); Assert.assertEquals(schema, header.getSchemas().get(0)); } @Test public void testMultipleRestores() throws Exception { HollowProducer producer = createProducer(tmpFolder, schema); System.out.println("\n\n------------ Publish a few versions ------------\n"); List<Long> versions = new ArrayList<>(); for (int i = 0; i < 5; i++) { int size = i + 1; int valueMultiplier = i + 10; long version = testPublishV1(producer, size, valueMultiplier); versions.add(version); } Assert.assertEquals(producer.getCycleCountWithPrimaryStatus(), 5); System.out.println("\n\n------------ Restore and validate ------------\n"); for (int i = 0; i < versions.size(); i++) { long version = versions.get(i); int size = i + 1; int valueMultiplier = i + 10; restoreAndAssert(producer, version, size, valueMultiplier); } System.out.println("\n\n------------ Restore in reverse order and validate ------------\n"); for (int i = versions.size() - 1; i >= 0; i--) { long version = versions.get(i); int size = i + 1; int valueMultiplier = i + 10; restoreAndAssert(producer, version, size, valueMultiplier); } } @Test public void testAlternatingPublishAndRestores() throws Exception { HollowProducer producer = createProducer(tmpFolder, schema); List<Long> versions = new ArrayList<>(); for (int i = 0; i < 5; i++) { int size = i + 10; int valueMultiplier = i + 10; long version = testPublishV1(producer, size, valueMultiplier); versions.add(version); restoreAndAssert(producer, version, size, valueMultiplier); } } @Test public void testPublishAndRestoreWithSchemaChanges() throws Exception { int sizeV1 = 3; int valueMultiplierV1 = 20; long v1 = 0; { // Publish V1 HollowProducer producer = createProducer(tmpFolder, schema); v1 = testPublishV1(producer, sizeV1, valueMultiplierV1); Assert.assertEquals(producer.getCycleCountWithPrimaryStatus(), 1); } // Publish V2; int sizeV2 = sizeV1 * 2; int valueMultiplierV2 = valueMultiplierV1 * 2; HollowObjectSchema schemaV2 = new HollowObjectSchema("TestPojo", 3, "id"); schemaV2.addField("id", FieldType.INT); schemaV2.addField("v1", FieldType.INT); schemaV2.addField("v2", FieldType.INT); HollowProducer producerV2 = createProducer(tmpFolder, schemaV2); long v2 = testPublishV2(producerV2, sizeV2, valueMultiplierV2); { // Restore V1 int valueFieldCount = 1; restoreAndAssert(producerV2, v1, sizeV1, valueMultiplierV1, valueFieldCount); } // Publish V3 int sizeV3 = sizeV1 * 3; int valueMultiplierV3 = valueMultiplierV1 * 3; long v3 = testPublishV2(producerV2, sizeV3, valueMultiplierV3); { // Restore V2 int valueFieldCount = 2; restoreAndAssert(producerV2, v2, sizeV2, valueMultiplierV2, valueFieldCount); } { // Restore V3 int valueFieldCount = 2; restoreAndAssert(producerV2, v3, sizeV3, valueMultiplierV3, valueFieldCount); } Assert.assertEquals(producerV2.getCycleCountWithPrimaryStatus(), 2); } @Test public void testRestoreToNonExact() { HollowProducer producer = createProducer(tmpFolder, schema); long version = testPublishV1(producer, 2, 7); producer = createProducer(tmpFolder, schema); producer.restore(version + 1, blobRetriever); Assert.assertNotNull(lastRestoreStatus); Assert.assertEquals(Status.SUCCESS, lastRestoreStatus.getStatus()); Assert.assertEquals("Should have reached correct version", version, lastRestoreStatus.getVersionReached()); Assert.assertEquals("Should have correct desired version", version + 1, lastRestoreStatus.getDesiredVersion()); Assert.assertEquals(producer.getCycleCountWithPrimaryStatus(), 0); // no cycle run } @Test public void testRollsBackStateEngineOnPublishFailure() throws Exception { HollowProducer producer = spy(createProducer(tmpFolder, schema)); Assert.assertEquals("Should have no populated ordinals", 0, producer.getWriteEngine().getTypeState("TestPojo").getPopulatedBitSet().cardinality()); doThrow(new RuntimeException("Publish failed")).when(producer).publish( any(ProducerListenerSupport.ProducerListeners.class), any(Long.class), any(AbstractHollowProducer.Artifacts.class)); try { producer.runCycle(newState -> newState.add(new TestPojoV1(1, 1))); } catch (RuntimeException e) { // expected } Assert.assertEquals("Should still have no populated ordinals", 0, producer.getWriteEngine().getTypeState("TestPojo").getPopulatedBitSet().cardinality()); Assert.assertEquals(producer.getCycleCountWithPrimaryStatus(), 1); // counted as cycle ran for producer with primary status } private long testPublishV1(HollowProducer producer, final int size, final int valueMultiplier) { producer.runCycle(newState -> { for (int i = 1; i <= size; i++) { newState.add(new TestPojoV1(i, i * valueMultiplier)); } }); Assert.assertNotNull(lastProducerStatus); Assert.assertEquals(Status.SUCCESS, lastProducerStatus.getStatus()); return lastProducerStatus.getVersion(); } private long testPublishV2(HollowProducer producer, final int size, final int valueMultiplier) { producer.runCycle(newState -> { for (int i = 1; i <= size; i++) { newState.add(new TestPojoV2(i, i * valueMultiplier, i * valueMultiplier)); } }); Assert.assertNotNull(lastProducerStatus); Assert.assertEquals(Status.SUCCESS, lastProducerStatus.getStatus()); return lastProducerStatus.getVersion(); } private void restoreAndAssert(HollowProducer producer, long version, int size, int valueMultiplier) throws Exception { restoreAndAssert(producer, version, size, valueMultiplier, 1); } private void restoreAndAssert(HollowProducer producer, long version, int size, int valueMultiplier, int valueFieldCount) { ReadState readState = producer.restore(version, blobRetriever); Assert.assertNotNull(lastRestoreStatus); Assert.assertEquals(Status.SUCCESS, lastRestoreStatus.getStatus()); Assert.assertEquals("Version should be the same", version, lastRestoreStatus.getDesiredVersion()); HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readState.getStateEngine().getTypeState("TestPojo"); BitSet populatedOrdinals = typeState.getPopulatedOrdinals(); Assert.assertEquals(size, populatedOrdinals.cardinality()); int ordinal = populatedOrdinals.nextSetBit(0); while (ordinal != -1) { GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(typeState), ordinal); System.out.println("ordinal=" + ordinal + obj); int id = obj.getInt("id"); for (int i = 0; i < valueFieldCount; i++) { String valueFN = "v" + (i + 1); int value = id * valueMultiplier; Assert.assertEquals(valueFN, value, obj.getInt(valueFN)); } ordinal = populatedOrdinals.nextSetBit(ordinal + 1); } System.out.println("Asserted Correctness of version:" + version + "\n\n"); } @SuppressWarnings("unused") @HollowTypeName(name = "TestPojo") private static class TestPojoV1 { public int id; public int v1; TestPojoV1(int id, int v1) { super(); this.id = id; this.v1 = v1; } } @SuppressWarnings("unused") @HollowTypeName(name = "TestPojo") private static class TestPojoV2 { int id; int v1; int v2; TestPojoV2(int id, int v1, int v2) { this.id = id; this.v1 = v1; this.v2 = v2; } } private class FakeProducerListener extends AbstractHollowProducerListener { @Override public void onCycleComplete(ProducerStatus status, long elapsed, TimeUnit unit) { lastProducerStatus = status; } @Override public void onProducerRestoreComplete(RestoreStatus status, long elapsed, TimeUnit unit) { lastRestoreStatus = status; } } private class ProducerYieldsPrimaryBeforePublish extends AbstractHollowProducerListener { private SingleProducerEnforcer singleProducerEnforcer; ProducerYieldsPrimaryBeforePublish(SingleProducerEnforcer singleProducerEnforcer) { this.singleProducerEnforcer = singleProducerEnforcer; } @Override public void onPopulateStart(long version) { singleProducerEnforcer.disable(); } } private class ProducerYieldsPrimaryBeforeAnnounce extends AbstractHollowProducerListener { private SingleProducerEnforcer singleProducerEnforcer; ProducerYieldsPrimaryBeforeAnnounce(SingleProducerEnforcer singleProducerEnforcer) { this.singleProducerEnforcer = singleProducerEnforcer; } @Override public void onValidationStart(long version) { singleProducerEnforcer.disable(); } } private class FakeBlobPublisher implements HollowProducer.Publisher { private void publishBlob(Blob blob) { File blobFile = blob.getFile(); if (!blob.getType().equals(Type.SNAPSHOT)) { // Only snapshot is needed for smoke Test return; } File copiedFile = copyFile(blobFile); blobMap.put(blob.getToVersion(), blob); blobFileMap.put(blob.getToVersion(), copiedFile); System.out.println("Published:" + copiedFile); } private File copyFile(File blobFile) { if (!blobFile.exists()) throw new RuntimeException("File does not exists: " + blobFile); // Copy file File copiedFile = new File(tmpFolder, "copied_" + blobFile.getName()); try { Files.copy(blobFile.toPath(), copiedFile.toPath()); } catch (IOException e) { throw new RuntimeException("Failed to publish:" + copiedFile, e); } return copiedFile; } private void publishHeader(HeaderBlob headerBlob) { File headerBlobFile = headerBlob.getFile(); File copiedFile = copyFile(headerBlobFile); headerBlobMap.put(headerBlob.getVersion(), headerBlob); headerFileMap.put(headerBlob.getVersion(), copiedFile); System.out.println("Published Header:" + copiedFile); } @Override public void publish(HollowProducer.PublishArtifact publishArtifact) { if (publishArtifact instanceof HeaderBlob) { publishHeader((HeaderBlob) publishArtifact); } else { publishBlob((Blob) publishArtifact); } } } @SuppressWarnings("unused") private class FakeBlobRetriever implements HollowConsumer.BlobRetriever { private String namespace; private String tmpDir; FakeBlobRetriever(String namespace, String tmpDir) { this.namespace = namespace; this.tmpDir = tmpDir; } @Override public HollowConsumer.Blob retrieveSnapshotBlob(long desiredVersion) { long blobVersion = desiredVersion; File blobFile = blobFileMap.get(desiredVersion); if (blobFile == null) { // find the closest one blobVersion = blobFileMap.keySet().stream() .filter(l -> l < desiredVersion) .reduce(Long.MIN_VALUE, Math::max); if (blobVersion == Long.MIN_VALUE) { return null; } else { blobFile = blobFileMap.get(blobVersion); } } final File blobFileFinal = blobFile; System.out.println("Restored: " + blobFile); return new HollowConsumer.Blob(blobVersion) { @Override public InputStream getInputStream() throws IOException { return new FileInputStream(blobFileFinal); } }; } @Override public HollowConsumer.Blob retrieveDeltaBlob(long currentVersion) { // no delta available return null; } @Override public HollowConsumer.Blob retrieveReverseDeltaBlob(long currentVersion) { throw new UnsupportedOperationException(); } @Override public HollowConsumer.HeaderBlob retrieveHeaderBlob(long currentVersion) { final File blobFile = headerFileMap.get(currentVersion); System.out.println("Restored: " + blobFile); return new HollowConsumer.HeaderBlob(currentVersion) { @Override public InputStream getInputStream() throws IOException { return new FileInputStream(blobFile); } }; } } }
8,814
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/ProducerListenerSupportTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.producer; import static java.util.concurrent.TimeUnit.MILLISECONDS; import com.netflix.hollow.api.producer.listener.CycleListener; import com.netflix.hollow.api.producer.validation.ValidationStatusListener; import java.time.Duration; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; public class ProducerListenerSupportTest { interface ProducerAndValidationStatusListener extends HollowProducerListener, ValidationStatusListener { } private ProducerListenerSupport listenerSupport; @Mock private HollowProducerListener listener; @Mock private ValidationStatusListener validationStatusListener; @Mock private ProducerAndValidationStatusListener producerAndValidationStatusListener; @Before public void setUp() { MockitoAnnotations.initMocks(this); listenerSupport = new ProducerListenerSupport(); listenerSupport.addListener(listener); listenerSupport.addListener(validationStatusListener); listenerSupport.addListener(producerAndValidationStatusListener); } @Test public void testDuplicates() { ProducerListenerSupport ls = new ProducerListenerSupport(); CycleListener l = Mockito.mock(CycleListener.class); ls.addListener(l); ls.addListener(l); ProducerListenerSupport.ProducerListeners s = ls.listeners(); s.fireCycleStart(1); Mockito.verify(l, Mockito.times(1)).onCycleStart(1); } @Test public void testAddDuringCycle() { ProducerListenerSupport ls = new ProducerListenerSupport(); class SecondCycleListener implements CycleListener { int cycleStart; int cycleComplete; @Override public void onCycleSkip(CycleSkipReason reason) { } @Override public void onNewDeltaChain(long version) { } @Override public void onCycleStart(long version) { cycleStart++; } @Override public void onCycleComplete(Status status, HollowProducer.ReadState rs, long version, Duration elapsed) { cycleComplete++; } } class FirstCycleListener extends SecondCycleListener { private SecondCycleListener scl = new SecondCycleListener(); @Override public void onCycleStart(long version) { super.onCycleStart(version); ls.addListener(scl); } } FirstCycleListener fcl = new FirstCycleListener(); ls.addListener(fcl); ProducerListenerSupport.ProducerListeners s = ls.listeners(); s.fireCycleStart(1); s.fireCycleComplete(new Status.StageWithStateBuilder()); Assert.assertEquals(1, fcl.cycleStart); Assert.assertEquals(1, fcl.cycleComplete); Assert.assertEquals(0, fcl.scl.cycleStart); Assert.assertEquals(0, fcl.scl.cycleComplete); s = ls.listeners(); s.fireCycleStart(1); s.fireCycleComplete(new Status.StageWithStateBuilder()); Assert.assertEquals(2, fcl.cycleStart); Assert.assertEquals(2, fcl.cycleComplete); Assert.assertEquals(1, fcl.scl.cycleStart); Assert.assertEquals(1, fcl.scl.cycleComplete); } @Test public void testRemoveDuringCycle() { ProducerListenerSupport ls = new ProducerListenerSupport(); class SecondCycleListener implements CycleListener { int cycleStart; int cycleComplete; @Override public void onCycleSkip(CycleSkipReason reason) { } @Override public void onNewDeltaChain(long version) { } @Override public void onCycleStart(long version) { cycleStart++; } @Override public void onCycleComplete(Status status, HollowProducer.ReadState rs, long version, Duration elapsed) { cycleComplete++; } } class FirstCycleListener extends SecondCycleListener { private SecondCycleListener scl; private FirstCycleListener(SecondCycleListener scl) { this.scl = scl; } @Override public void onCycleStart(long version) { super.onCycleStart(version); ls.removeListener(scl); } } SecondCycleListener scl = new SecondCycleListener(); FirstCycleListener fcl = new FirstCycleListener(scl); ls.addListener(fcl); ls.addListener(scl); ProducerListenerSupport.ProducerListeners s = ls.listeners(); s.fireCycleStart(1); s.fireCycleComplete(new Status.StageWithStateBuilder()); Assert.assertEquals(1, fcl.cycleStart); Assert.assertEquals(1, fcl.cycleComplete); Assert.assertEquals(1, fcl.scl.cycleStart); Assert.assertEquals(1, fcl.scl.cycleComplete); s = ls.listeners(); s.fireCycleStart(1); s.fireCycleComplete(new Status.StageWithStateBuilder()); Assert.assertEquals(2, fcl.cycleStart); Assert.assertEquals(2, fcl.cycleComplete); Assert.assertEquals(1, fcl.scl.cycleStart); Assert.assertEquals(1, fcl.scl.cycleComplete); } @Test public void testFireValidationStart() { long version = 31337; HollowProducer.ReadState readState = Mockito.mock(HollowProducer.ReadState.class); Mockito.when(readState.getVersion()).thenReturn(version); listenerSupport.listeners().fireValidationStart(readState); Mockito.verify(listener).onValidationStart(version); Mockito.verify(validationStatusListener).onValidationStatusStart(version); Mockito.verify(producerAndValidationStatusListener).onValidationStart(version); } @Test public void testFireValidationStartDontStopWhenOneFails() { long version = 31337; HollowProducer.ReadState readState = Mockito.mock(HollowProducer.ReadState.class); Mockito.when(readState.getVersion()).thenReturn(version); Mockito.doThrow(RuntimeException.class).when(validationStatusListener).onValidationStatusStart(version); listenerSupport.listeners().fireValidationStart(readState); Mockito.verify(listener).onValidationStart(version); Mockito.verify(validationStatusListener).onValidationStatusStart(version); Mockito.verify(producerAndValidationStatusListener).onValidationStart(version); } @Test public void testFireValidationStartDontStopWhenOneFails2() { long version = 31337; HollowProducer.ReadState readState = Mockito.mock(HollowProducer.ReadState.class); Mockito.when(readState.getVersion()).thenReturn(version); Mockito.doThrow(RuntimeException.class).when(validationStatusListener).onValidationStatusStart(version); listenerSupport.listeners().fireValidationStart(readState); Mockito.verify(listener).onValidationStart(version); Mockito.verify(validationStatusListener).onValidationStatusStart(version); Mockito.verify(producerAndValidationStatusListener).onValidationStart(version); } @Test public void fireProducerInitDontStopWhenOneFails() { long version = 31337; HollowProducer.ReadState readState = Mockito.mock(HollowProducer.ReadState.class); Mockito.when(readState.getVersion()).thenReturn(version); Mockito.doThrow(RuntimeException.class).when(listener).onProducerInit(1L, MILLISECONDS); listenerSupport.listeners().fireProducerInit(1L); Mockito.verify(listener).onProducerInit(Duration.ofMillis(1L)); } @Test public void fireProducerRestoreStartDontStopWhenOneFails() { long version = 31337; HollowProducer.ReadState readState = Mockito.mock(HollowProducer.ReadState.class); Mockito.when(readState.getVersion()).thenReturn(version); Mockito.doThrow(RuntimeException.class).when(listener).onProducerRestoreStart(version); Status.RestoreStageBuilder b = new Status.RestoreStageBuilder(); listenerSupport.listeners().fireProducerRestoreComplete(b); ArgumentCaptor<Status> status = ArgumentCaptor.forClass( Status.class); ArgumentCaptor<Long> desired = ArgumentCaptor.forClass( long.class); ArgumentCaptor<Long> reached = ArgumentCaptor.forClass( long.class); ArgumentCaptor<Duration> elapsed = ArgumentCaptor.forClass( Duration.class); Mockito.verify(listener).onProducerRestoreComplete(status.capture(), desired.capture(), reached.capture(), elapsed.capture()); Assert.assertNotNull(status.getValue()); Assert.assertNotNull(elapsed.getValue()); } @Test public void fireNewDeltaChainDontStopWhenOneFails() { long version = 31337; HollowProducer.ReadState readState = Mockito.mock(HollowProducer.ReadState.class); Mockito.when(readState.getVersion()).thenReturn(version); Mockito.doThrow(RuntimeException.class).when(listener).onNewDeltaChain(version); listenerSupport.listeners().fireNewDeltaChain(version); Mockito.verify(listener).onNewDeltaChain(version); } @Test public void fireCycleStartDontStopWhenOneFails() { long version = 31337; HollowProducer.ReadState readState = Mockito.mock(HollowProducer.ReadState.class); Mockito.when(readState.getVersion()).thenReturn(version); Mockito.doThrow(RuntimeException.class).when(listener).onCycleStart(version); listenerSupport.listeners().fireCycleStart(version); Mockito.verify(listener).onCycleStart(version); } @Test public void firePopulateStartDontStopWhenOneFails() { long version = 31337; HollowProducer.ReadState readState = Mockito.mock(HollowProducer.ReadState.class); Mockito.when(readState.getVersion()).thenReturn(version); Mockito.doThrow(RuntimeException.class).when(listener).onPopulateStart(version); listenerSupport.listeners().firePopulateStart(version); Mockito.verify(listener).onPopulateStart(version); } @Test public void firePublishStartDontStopWhenOneFails() { long version = 31337; HollowProducer.ReadState readState = Mockito.mock(HollowProducer.ReadState.class); Mockito.when(readState.getVersion()).thenReturn(version); Mockito.doThrow(RuntimeException.class).when(listener).onPublishStart(version); listenerSupport.listeners().firePublishStart(version); Mockito.verify(listener).onPublishStart(version); } @Test public void fireIntegrityCheckStartDontStopWhenOneFails() { long version = 31337; HollowProducer.ReadState readState = Mockito.mock(HollowProducer.ReadState.class); Mockito.when(readState.getVersion()).thenReturn(version); Mockito.doThrow(RuntimeException.class).when(listener).onIntegrityCheckStart(version); listenerSupport.listeners().fireIntegrityCheckStart(readState); Mockito.verify(listener).onIntegrityCheckStart(version); } @Test public void fireAnnouncementStartDontStopWhenOneFails() { long version = 31337; HollowProducer.ReadState readState = Mockito.mock(HollowProducer.ReadState.class); Mockito.when(readState.getVersion()).thenReturn(version); Mockito.doThrow(RuntimeException.class).when(listener).onAnnouncementStart(version); listenerSupport.listeners().fireAnnouncementStart(readState); Mockito.verify(listener).onAnnouncementStart(version); Mockito.verify(listener).onAnnouncementStart(readState); } }
8,815
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/HollowProduceIncrementalMultithreadingTest.java
package com.netflix.hollow.api.producer; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.core.index.HollowPrimaryKeyIndex; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import java.util.Arrays; import java.util.stream.IntStream; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class HollowProduceIncrementalMultithreadingTest { private static final int ELEMENTS = 20000; private static final int ITERATIONS = 10; private InMemoryBlobStore blobStore; @Before public void setUp() { blobStore = new InMemoryBlobStore(); } @Rule public final ExpectedException exception = ExpectedException.none(); @Test public void updateAndPublishUsingMultithreading() { // run within a loop to increase the likelihood of a race condition to occur for (int iterationCounter = 0; iterationCounter < ITERATIONS; ++iterationCounter) { HollowProducer.Incremental producer = createInMemoryIncrementalProducer(); initializeData(producer); int[] notModifiedElementIds = IntStream.range(0, ELEMENTS / 2).toArray(); int[] modifiedElementIds = IntStream.range(ELEMENTS / 2, ELEMENTS).toArray(); long versionAfterUpdate = producer.runIncrementalCycle(iws -> { Arrays.stream(modifiedElementIds).parallel() .mapToObj(i -> new SimpleType(i, i + 1)) .forEach(iws::addOrModify); }); /// now we read the changes and assert HollowPrimaryKeyIndex idx = createPrimaryKeyIndex(versionAfterUpdate); Assert.assertFalse(idx.containsDuplicates()); Assert.assertTrue(Arrays.stream(notModifiedElementIds) .boxed() .map(elementId -> getHollowObject(idx, elementId)) .allMatch(obj -> obj.getInt("value") == obj.getInt("id"))); Assert.assertTrue(Arrays.stream(modifiedElementIds) .boxed() .map(elementId -> getHollowObject(idx, elementId)) .allMatch(obj -> obj.getInt("value") != obj.getInt("id"))); } } @Test public void removeAndPublishUsingMultithreading() { // run within a loop to increase the likelihood of a race condition to occur for (int iterationCounter = 0; iterationCounter < ITERATIONS; ++iterationCounter) { HollowProducer.Incremental producer = createInMemoryIncrementalProducer(); initializeData(producer); int[] notModifiedElementIds = IntStream.range(0, ELEMENTS / 2).toArray(); int[] deletedElementIds = IntStream.range(ELEMENTS / 2, ELEMENTS).toArray(); long versionAfterDelete = producer.runIncrementalCycle(iws -> { Arrays.stream(deletedElementIds).parallel() .mapToObj(i -> new SimpleType(i, i)) .forEach(iws::delete); }); /// now we read the changes and assert HollowPrimaryKeyIndex idx = createPrimaryKeyIndex(versionAfterDelete); Assert.assertTrue(Arrays.stream(notModifiedElementIds) .boxed() .map(elementId -> getHollowObject(idx, elementId)) .allMatch(obj -> obj.getInt("value") == obj.getInt("id"))); Assert.assertTrue(Arrays.stream(deletedElementIds) .boxed() .map(elementId -> getOrdinal(idx, elementId)) .allMatch(ordinal -> ordinal == -1)); } } private HollowProducer.Incremental createInMemoryIncrementalProducer() { return new HollowProducer.Builder<>() .withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .buildIncremental(); } private void initializeData(HollowProducer.Incremental producer) { producer.runIncrementalCycle(iws -> { for (int i = 0; i < ELEMENTS; ++i) { iws.addOrModify(new SimpleType(i, i)); } }); } private HollowPrimaryKeyIndex createPrimaryKeyIndex(long version) { HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(version); return new HollowPrimaryKeyIndex(consumer.getStateEngine(), "SimpleType", "id"); } private GenericHollowObject getHollowObject(HollowPrimaryKeyIndex idx, Object... keys) { int ordinal = getOrdinal(idx, keys); return new GenericHollowObject(idx.getTypeState(), ordinal); } private int getOrdinal(HollowPrimaryKeyIndex idx, Object... keys) { return idx.getMatchingOrdinal(keys); } @HollowPrimaryKey(fields = "id") private static class SimpleType { int id; int value; SimpleType(int id, int value) { this.id = id; this.value = value; } } }
8,816
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/CustomProducerBuilderTest.java
package com.netflix.hollow.api.producer; import org.junit.Assert; import org.junit.Before; import org.junit.Test; // this test doesn't do much beyond making sure that a custom builder will // compile and ensure that HollowProducer.Builder is parameterized correctly // to allow custom builder methods to be interleaved with base class builder // methods public class CustomProducerBuilderTest { @Before public void setUp() { } @Test public void defaultBehavior() { HollowProducer producer = new AugmentedBuilder() .build(); Assert.assertFalse(producer instanceof AugmentedProducer); } @Test public void augmentedBehavior() { HollowProducer consumer = new AugmentedBuilder() .withNumStatesBetweenSnapshots(42) // should be called before custom builder methods .withAugmentation() .build(); Assert.assertTrue(consumer instanceof AugmentedProducer); } private static class AugmentedBuilder extends HollowProducer.Builder<AugmentedBuilder> { private boolean shouldAugment = false; AugmentedBuilder withAugmentation() { shouldAugment = true; return this; } @Override public HollowProducer build() { checkArguments(); HollowProducer producer; if(shouldAugment) producer = new AugmentedProducer(null, null); else producer = super.build(); return producer; } } private static class AugmentedProducer extends HollowProducer { AugmentedProducer( HollowProducer.Publisher publisher, HollowProducer.Announcer announcer ) { super(publisher, announcer); } @Override public String toString() { return "I am augmented"; } } }
8,817
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/HollowProducerBlobStorageCleanerTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.producer; import com.netflix.hollow.api.producer.fs.HollowFilesystemBlobStorageCleaner; import com.netflix.hollow.api.producer.fs.HollowFilesystemPublisher; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowProducerBlobStorageCleanerTest { private static final String SCRATCH_DIR = System.getProperty("java.io.tmpdir"); private File publishDir; @Before public void setUp() { publishDir = new File(SCRATCH_DIR, "publish-dir"); publishDir.mkdir(); } @Test public void cleanSnapshotsWithDefaultValue() { HollowProducer.Publisher publisher = new HollowFilesystemPublisher(publishDir.toPath()); HollowProducer.BlobStorageCleaner blobStorageCleaner = new HollowFilesystemBlobStorageCleaner(publishDir); HollowProducer producer = HollowProducer.withPublisher(publisher) .withBlobStorageCleaner(blobStorageCleaner) .withVersionMinter(new TestVersionMinter()) .build(); /// initialize the data -- classic producer creates the first state in the delta chain. producer.runCycle(state -> state.add(new TypeA(1, "one", 1))); HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(producer); incrementalProducer.addOrModify(new TypeA(2, "two", 100)); incrementalProducer.runCycle(); incrementalProducer.addOrModify(new TypeA(3, "three", 1000)); incrementalProducer.runCycle(); incrementalProducer.addOrModify(new TypeA(4, "two", 100)); incrementalProducer.runCycle(); incrementalProducer.addOrModify(new TypeA(5, "three", 1000)); incrementalProducer.runCycle(); File[] files = listFiles(HollowProducer.Blob.Type.SNAPSHOT.prefix); List<String> fileNames = getFileNames(files); Assert.assertEquals(5, files.length); incrementalProducer.addOrModify(new TypeA(6, "three", 1000)); incrementalProducer.runCycle(); incrementalProducer.addOrModify(new TypeA(7, "three", 1000)); incrementalProducer.runCycle(); File[] filesAfterCleanup = listFiles(HollowProducer.Blob.Type.SNAPSHOT.prefix); List<String> fileNamesAfterCleanup = getFileNames(filesAfterCleanup); Assert.assertEquals(5, files.length); Assert.assertFalse(fileNamesAfterCleanup.contains("snapshot-1")); Assert.assertNotEquals(fileNamesAfterCleanup, fileNames); } @SuppressWarnings("unused") @HollowPrimaryKey(fields = { "id1", "id2" }) private static class TypeA { int id1; String id2; long value; public TypeA(int id1, String id2, long value) { this.id1 = id1; this.id2 = id2; this.value = value; } } private File[] listFiles(final String blobType) { return publishDir.listFiles((dir, name) -> name.contains(blobType)); } private List<String> getFileNames(File[] files) { List<String> fileNames = new ArrayList<>(); for(File file : files) { fileNames.add(file.getName()); } return fileNames; } @After public void removeAllFiles() { Arrays.stream(publishDir.listFiles()).forEach(File::delete); } private static final class TestVersionMinter implements HollowProducer.VersionMinter { private static int versionCounter = 1; @Override public long mint() { return versionCounter++; } } }
8,818
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/WriteStateTest.java
package com.netflix.hollow.api.producer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; public class WriteStateTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule().silent(); @Mock private HollowWriteStateEngine writeStateEngine; @Mock private HollowObjectMapper objectMapper; private CloseableWriteState subject; private long version; @Before public void before() { when(objectMapper.getStateEngine()).thenReturn(writeStateEngine); version = 13L; subject = new CloseableWriteState(version, objectMapper, null); } @Test public void add_delegatesToObjectMapper() { subject.add("Yes!"); verify(objectMapper).add("Yes!"); } @Test public void getObjectMapper() { assertEquals(objectMapper, subject.getObjectMapper()); } @Test public void getStateEngine_delegatesToObjectMapper() throws Exception { assertEquals(writeStateEngine, subject.getStateEngine()); } @Test public void add_whenClosed() { assertThrowsAfterClose(() -> subject.add("Nope!")); } @Test public void getObjectMapper_whenClosed() { assertThrowsAfterClose(() -> subject.getObjectMapper()); } @Test public void getStateEngine_whenClosed() { assertThrowsAfterClose(() -> subject.getStateEngine()); } @Test public void getPriorState_whenClosed() { assertThrowsAfterClose(() -> subject.getPriorState()); } @Test public void getVersion_whenClosed() { assertThrowsAfterClose(() -> subject.getVersion()); } private void assertThrowsAfterClose(Runnable code) { subject.close(); try { code.run(); fail("should throw"); } catch (IllegalStateException e) { assertEquals("Write state operated on after the population stage of a cycle; version=" + version, e.getMessage()); } } }
8,819
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/HashCodeFinderTest.java
package com.netflix.hollow.api.producer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.core.schema.HollowMapSchema; import com.netflix.hollow.core.util.HollowObjectHashCodeFinder; import com.netflix.hollow.core.write.objectmapper.HollowInline; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HashCodeFinderTest { private InMemoryBlobStore blobStore; @Before public void setUp() { blobStore = new InMemoryBlobStore(); } @Test public void testProduceAndRestore() { TestHollowObjectHashCodeFinder hcf = new TestHollowObjectHashCodeFinder(); HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withHashCodeFinder(hcf) .build(); long v1 = producer.runCycle(ws -> ws.add(new Top(100))); HollowMapSchema s = (HollowMapSchema) producer.getWriteEngine().getSchema( "MapOfStringUsingHashCodeFinderToStringUsingHashCodeFinder"); Assert.assertNull(s.getHashKey()); Assert.assertEquals(100, hcf.i.get()); HollowProducer restoredProducer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withHashCodeFinder(hcf) .build(); restoredProducer.initializeDataModel(Top.class); restoredProducer.restore(v1, blobStore); // Cycle on restored producer will fail integrity check if hash code are not the same long v2 = restoredProducer.runCycle(ws -> ws.add(new Top(101))); s = (HollowMapSchema) restoredProducer.getWriteEngine().getSchema( "MapOfStringUsingHashCodeFinderToStringUsingHashCodeFinder"); Assert.assertNull(s.getHashKey()); Assert.assertEquals(201, hcf.i.get()); } static class Top { final Map<StringUsingHashCodeFinder, StringUsingHashCodeFinder> m; Top(int n) { this.m = new HashMap<>(); for (int i = 0; i < n; i++) { StringUsingHashCodeFinder s = new StringUsingHashCodeFinder( Integer.toString(i)); m.put(s, s); } } } static class StringUsingHashCodeFinder { @HollowInline final String s; StringUsingHashCodeFinder(String s) { this.s = s; } } private static class TestHollowObjectHashCodeFinder implements HollowObjectHashCodeFinder { final AtomicInteger i = new AtomicInteger(); @Override public int hashCode(Object objectToHash) { throw new UnsupportedOperationException(); } @Override public int hashCode(String typeName, int ordinal, Object objectToHash) { if (typeName.equals("StringUsingHashCodeFinder")) { i.incrementAndGet(); String s = ((StringUsingHashCodeFinder) objectToHash).s; return s.hashCode() ^ s.charAt(0); } else { return ordinal; } } @Override public Set<String> getTypesWithDefinedHashCodes() { return Collections.singleton("StringUsingHashCodeFinder"); } @Override public int hashCode(int ordinal, Object objectToHash) { throw new UnsupportedOperationException(); } } }
8,820
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/HollowProducerListenerTest.java
package com.netflix.hollow.api.producer; import com.netflix.hollow.api.producer.enforcer.SingleProducerEnforcer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.api.producer.listener.AnnouncementListener; import com.netflix.hollow.api.producer.listener.CycleListener; import com.netflix.hollow.api.producer.listener.DataModelInitializationListener; import com.netflix.hollow.api.producer.listener.IntegrityCheckListener; import com.netflix.hollow.api.producer.listener.PopulateListener; import com.netflix.hollow.api.producer.listener.PublishListener; import com.netflix.hollow.api.producer.listener.RestoreListener; import com.netflix.hollow.api.producer.listener.VetoableListener; import com.netflix.hollow.api.producer.validation.ValidationStatus; import com.netflix.hollow.api.producer.validation.ValidationStatusListener; import java.io.InputStream; import java.time.Duration; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Unit tests to verify that HollowProducerListener objects provided to HollowProducers * are invoked at the right times. */ public class HollowProducerListenerTest { private InMemoryBlobStore blobStore; @Before public void setUp() { blobStore = new InMemoryBlobStore(); } static class BaseListener { Map<String, Integer> callCount = new HashMap<>(); void reportCaller() { Throwable t = new Throwable(); StackTraceElement caller = t.getStackTrace()[1]; callCount.compute(caller.getMethodName(), (k, v) -> v == null ? 1 : v + 1); } } @Test public void testListenerVetoException() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withAnnouncer((HollowProducer.Announcer) stateVersion -> { }) .build(); class Listener implements CycleListener { @Override public void onCycleSkip(CycleSkipReason reason) { } @Override public void onNewDeltaChain(long version) { } @Override public void onCycleStart(long version) { throw new VetoableListener.ListenerVetoException("VETOED"); } @Override public void onCycleComplete( Status status, HollowProducer.ReadState readState, long version, Duration elapsed) { } } Listener l = new Listener(); producer.addListener(l); producer.initializeDataModel(Top.class); try { producer.runCycle(ws -> ws.add(new Top(1))); Assert.fail(); } catch (VetoableListener.ListenerVetoException e) { Assert.assertEquals("VETOED", e.getMessage()); } } @Test public void testVetoableListener() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withAnnouncer((HollowProducer.Announcer) stateVersion -> { }) .build(); class Listener implements CycleListener, VetoableListener { @Override public void onCycleSkip(CycleSkipReason reason) { } @Override public void onNewDeltaChain(long version) { } @Override public void onCycleStart(long version) { throw new RuntimeException("VETOED"); } @Override public void onCycleComplete( Status status, HollowProducer.ReadState readState, long version, Duration elapsed) { } } Listener l = new Listener(); producer.addListener(l); producer.initializeDataModel(Top.class); try { producer.runCycle(ws -> ws.add(new Top(1))); Assert.fail(); } catch (RuntimeException e) { Assert.assertEquals("VETOED", e.getMessage()); } } @Test public void testFirstCycle() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withAnnouncer((HollowProducer.Announcer) stateVersion -> { }) .build(); class Listeners extends BaseListener implements DataModelInitializationListener, RestoreListener, CycleListener, PopulateListener, IntegrityCheckListener, ValidationStatusListener, PublishListener, AnnouncementListener { @Override public void onProducerInit(Duration elapsed) { reportCaller(); } @Override public void onProducerRestoreStart(long restoreVersion) { Assert.fail(); } @Override public void onProducerRestoreComplete( Status status, long versionDesired, long versionReached, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } Assert.fail(); } @Override public void onCycleSkip(CycleSkipReason reason) { Assert.fail(); } long newDeltaChainVersion; @Override public void onNewDeltaChain(long version) { reportCaller(); newDeltaChainVersion = version; } @Override public void onCycleStart(long version) { reportCaller(); Assert.assertEquals(newDeltaChainVersion, version); } @Override public void onCycleComplete( Status status, HollowProducer.ReadState readState, long version, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } reportCaller(); Assert.assertTrue(callCount.containsKey("onCycleStart")); Assert.assertEquals(Status.StatusType.SUCCESS, status.getType()); Assert.assertEquals(newDeltaChainVersion, version); } @Override public void onIntegrityCheckStart(long version) { reportCaller(); Assert.assertEquals(newDeltaChainVersion, version); } @Override public void onIntegrityCheckComplete( Status status, HollowProducer.ReadState readState, long version, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } reportCaller(); Assert.assertTrue(callCount.containsKey("onIntegrityCheckStart")); Assert.assertEquals(Status.StatusType.SUCCESS, status.getType()); Assert.assertEquals(newDeltaChainVersion, version); } @Override public void onPopulateStart(long version) { reportCaller(); Assert.assertEquals(newDeltaChainVersion, version); } @Override public void onPopulateComplete(Status status, long version, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } reportCaller(); Assert.assertTrue(callCount.containsKey("onPopulateStart")); Assert.assertEquals(Status.StatusType.SUCCESS, status.getType()); Assert.assertEquals(newDeltaChainVersion, version); } @Override public void onNoDeltaAvailable(long version) { Assert.fail(); } @Override public void onPublishStart(long version) { reportCaller(); Assert.assertEquals(newDeltaChainVersion, version); } @Override public void onBlobStage(Status status, HollowProducer.Blob blob, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } reportCaller(); Assert.assertEquals(HollowProducer.Blob.Type.SNAPSHOT, blob.getType()); Assert.assertTrue(callCount.containsKey("onPublishStart")); Assert.assertEquals(Status.StatusType.SUCCESS, status.getType()); } @Override public void onBlobPublishAsync( CompletableFuture<HollowProducer.Blob> blob) { Assert.fail(); } @Override public void onBlobPublish(Status status, HollowProducer.Blob blob, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } reportCaller(); Assert.assertEquals(HollowProducer.Blob.Type.SNAPSHOT, blob.getType()); Assert.assertTrue(callCount.containsKey("onBlobStage")); Assert.assertEquals(Status.StatusType.SUCCESS, status.getType()); } @Override public void onPublishComplete(Status status, long version, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } reportCaller(); Assert.assertTrue(callCount.containsKey("onBlobPublish")); Assert.assertEquals(Status.StatusType.SUCCESS, status.getType()); Assert.assertEquals(newDeltaChainVersion, version); } @Override public void onValidationStatusStart(long version) { reportCaller(); Assert.assertEquals(newDeltaChainVersion, version); } @Override public void onValidationStatusComplete( ValidationStatus status, long version, Duration elapsed) { reportCaller(); Assert.assertTrue(callCount.containsKey("onValidationStatusStart")); Assert.assertTrue(status.passed()); Assert.assertEquals(newDeltaChainVersion, version); } @Override public void onAnnouncementStart(long version) { reportCaller(); Assert.assertEquals(newDeltaChainVersion, version); } @Override public void onAnnouncementStart(HollowProducer.ReadState readState) { reportCaller(); Assert.assertEquals(newDeltaChainVersion, readState.getVersion()); Assert.assertNotNull("Read state engine should not be null.", readState.getStateEngine()); } @Override public void onAnnouncementComplete( Status status, HollowProducer.ReadState readState, long version, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } reportCaller(); Assert.assertTrue(callCount.containsKey("onAnnouncementStart")); Assert.assertEquals(Status.StatusType.SUCCESS, status.getType()); Assert.assertEquals(newDeltaChainVersion, version); } } Listeners ls = new Listeners(); producer.addListener(ls); producer.initializeDataModel(Top.class); producer.runCycle(ws -> ws.add(new Top(1))); Assert.assertTrue(ls.callCount.entrySet().stream().filter(c -> !c.getKey().equals("onAnnouncementStart")).allMatch(c -> c.getValue() == 1)); Assert.assertEquals(ls.callCount.get("onAnnouncementStart").intValue(), 2); Assert.assertEquals(16, ls.callCount.size()); } @Test public void testSecondCycleWithChanges() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); producer.initializeDataModel(Top.class); producer.runCycle(ws -> ws.add(new Top(1))); class Listeners extends BaseListener implements DataModelInitializationListener, RestoreListener, CycleListener, PopulateListener, IntegrityCheckListener, ValidationStatusListener, PublishListener, AnnouncementListener { @Override public void onProducerInit(Duration elapsed) { Assert.fail(); } @Override public void onProducerRestoreStart(long restoreVersion) { Assert.fail(); } @Override public void onProducerRestoreComplete( Status status, long versionDesired, long versionReached, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } Assert.fail(); } @Override public void onCycleSkip(CycleSkipReason reason) { Assert.fail(); } long cycleStartVersion; @Override public void onNewDeltaChain(long version) { Assert.fail(); } @Override public void onCycleStart(long version) { reportCaller(); cycleStartVersion = version; } @Override public void onCycleComplete( Status status, HollowProducer.ReadState readState, long version, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } reportCaller(); Assert.assertTrue(callCount.containsKey("onCycleStart")); Assert.assertEquals(Status.StatusType.SUCCESS, status.getType()); Assert.assertEquals(cycleStartVersion, version); } @Override public void onIntegrityCheckStart(long version) { reportCaller(); Assert.assertEquals(cycleStartVersion, version); } @Override public void onIntegrityCheckComplete( Status status, HollowProducer.ReadState readState, long version, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } reportCaller(); Assert.assertTrue(callCount.containsKey("onIntegrityCheckStart")); Assert.assertEquals(Status.StatusType.SUCCESS, status.getType()); Assert.assertEquals(cycleStartVersion, version); } @Override public void onPopulateStart(long version) { reportCaller(); Assert.assertEquals(cycleStartVersion, version); } @Override public void onPopulateComplete(Status status, long version, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } reportCaller(); Assert.assertTrue(callCount.containsKey("onPopulateStart")); Assert.assertEquals(Status.StatusType.SUCCESS, status.getType()); Assert.assertEquals(cycleStartVersion, version); } @Override public void onNoDeltaAvailable(long version) { Assert.fail(); } @Override public void onPublishStart(long version) { reportCaller(); Assert.assertEquals(cycleStartVersion, version); } @Override public void onBlobStage(Status status, HollowProducer.Blob blob, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } reportCaller(); Assert.assertTrue(callCount.containsKey("onPublishStart")); Assert.assertEquals(Status.StatusType.SUCCESS, status.getType()); } @Override public void onBlobPublishAsync( CompletableFuture<HollowProducer.Blob> blob) { Assert.fail(); } @Override public void onBlobPublish(Status status, HollowProducer.Blob blob, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } reportCaller(); Assert.assertTrue(callCount.containsKey("onBlobStage")); Assert.assertEquals(Status.StatusType.SUCCESS, status.getType()); } @Override public void onPublishComplete(Status status, long version, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } reportCaller(); Assert.assertTrue(callCount.containsKey("onBlobPublish")); Assert.assertEquals(Status.StatusType.SUCCESS, status.getType()); Assert.assertEquals(cycleStartVersion, version); } @Override public void onValidationStatusStart(long version) { reportCaller(); Assert.assertEquals(cycleStartVersion, version); } @Override public void onValidationStatusComplete( ValidationStatus status, long version, Duration elapsed) { reportCaller(); Assert.assertTrue(callCount.containsKey("onValidationStatusStart")); Assert.assertTrue(status.passed()); Assert.assertEquals(cycleStartVersion, version); } @Override public void onAnnouncementStart(long version) { reportCaller(); Assert.assertEquals(cycleStartVersion, version); } @Override public void onAnnouncementStart(HollowProducer.ReadState readState) { reportCaller(); Assert.assertEquals(cycleStartVersion, readState.getVersion()); Assert.assertNotNull("Read state engine should not be null.", readState.getStateEngine()); } @Override public void onAnnouncementComplete( Status status, HollowProducer.ReadState readState, long version, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } reportCaller(); Assert.assertTrue(callCount.containsKey("onAnnouncementStart")); Assert.assertEquals(Status.StatusType.SUCCESS, status.getType()); Assert.assertEquals(cycleStartVersion, version); } } Listeners ls = new Listeners(); producer.addListener(ls); producer.runCycle(ws -> ws.add(new Top(2))); Assert.assertTrue(ls.callCount.entrySet().stream() .filter(e -> !e.getKey().equals("onBlobStage")) .filter(e -> !e.getKey().equals("onBlobPublish")) .map(Map.Entry::getValue) .allMatch(c -> c == 1)); Assert.assertEquals(3, ls.callCount.get("onBlobStage").intValue()); Assert.assertEquals(3, ls.callCount.get("onBlobPublish").intValue()); Assert.assertEquals(12, ls.callCount.size()); } @Test public void testSecondCycleNoChanges() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); producer.initializeDataModel(Top.class); producer.runCycle(ws -> ws.add(new Top(1))); class Listeners extends BaseListener implements DataModelInitializationListener, RestoreListener, CycleListener, PopulateListener, IntegrityCheckListener, ValidationStatusListener, PublishListener, AnnouncementListener { @Override public void onProducerInit(Duration elapsed) { Assert.fail(); } @Override public void onProducerRestoreStart(long restoreVersion) { Assert.fail(); } @Override public void onProducerRestoreComplete( Status status, long versionDesired, long versionReached, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } Assert.fail(); } @Override public void onCycleSkip(CycleSkipReason reason) { Assert.fail(); } long cycleStartVersion; @Override public void onNewDeltaChain(long version) { Assert.fail(); } @Override public void onCycleStart(long version) { reportCaller(); cycleStartVersion = version; } @Override public void onCycleComplete( Status status, HollowProducer.ReadState readState, long version, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } reportCaller(); Assert.assertTrue(callCount.containsKey("onCycleStart")); Assert.assertEquals(Status.StatusType.SUCCESS, status.getType()); Assert.assertEquals(cycleStartVersion, version); } @Override public void onIntegrityCheckStart(long version) { Assert.fail(); } @Override public void onIntegrityCheckComplete( Status status, HollowProducer.ReadState readState, long version, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } Assert.fail(); } @Override public void onPopulateStart(long version) { reportCaller(); Assert.assertEquals(cycleStartVersion, version); } @Override public void onPopulateComplete(Status status, long version, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } reportCaller(); Assert.assertTrue(callCount.containsKey("onPopulateStart")); Assert.assertEquals(Status.StatusType.SUCCESS, status.getType()); Assert.assertEquals(cycleStartVersion, version); } @Override public void onNoDeltaAvailable(long version) { reportCaller(); Assert.assertTrue(callCount.containsKey("onPopulateComplete")); } @Override public void onPublishStart(long version) { Assert.fail(); } @Override public void onBlobStage(Status status, HollowProducer.Blob blob, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } Assert.fail(); } @Override public void onBlobPublishAsync( CompletableFuture<HollowProducer.Blob> blob) { Assert.fail(); } @Override public void onBlobPublish(Status status, HollowProducer.Blob blob, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } Assert.fail(); } @Override public void onPublishComplete(Status status, long version, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } Assert.fail(); } @Override public void onValidationStatusStart(long version) { Assert.fail(); } @Override public void onValidationStatusComplete( ValidationStatus status, long version, Duration elapsed) { Assert.fail(); } @Override public void onAnnouncementStart(long version) { Assert.fail(); } @Override public void onAnnouncementStart(HollowProducer.ReadState readState) { Assert.fail(); } @Override public void onAnnouncementComplete( Status status, HollowProducer.ReadState readState, long version, Duration elapsed) { if (status.getCause() instanceof AssertionError) { return; } Assert.fail(); } } Listeners ls = new Listeners(); producer.addListener(ls); producer.runCycle(ws -> ws.add(new Top(1))); Assert.assertTrue(ls.callCount.values().stream().allMatch(c -> c == 1)); Assert.assertEquals(5, ls.callCount.size()); } @Test public void testCycleSkipWithSingleEnforcer() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withSingleProducerEnforcer(new SingleProducerEnforcer() { @Override public void enable() { } @Override public void disable() { } @Override public boolean isPrimary() { return false; } @Override public void force() { } }) .build(); class Listeners extends BaseListener implements CycleListener { @Override public void onCycleSkip(CycleSkipReason reason) { reportCaller(); Assert.assertEquals(HollowProducerListener.CycleSkipReason.NOT_PRIMARY_PRODUCER, reason); } @Override public void onNewDeltaChain(long version) { Assert.fail(); } @Override public void onCycleStart(long version) { Assert.fail(); } @Override public void onCycleComplete( Status status, HollowProducer.ReadState readState, long version, Duration elapsed) { Assert.fail(); } } Listeners ls = new Listeners(); producer.addListener(ls); producer.runCycle(ws -> ws.add(new Top(1))); Assert.assertEquals(1, ls.callCount.size()); } @Test public void testCycleStartEndWithSingleEnforcer() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withSingleProducerEnforcer(new SingleProducerEnforcer() { @Override public void enable() { } @Override public void disable() { } @Override public boolean isPrimary() { return true; } @Override public void force() { } }) .build(); class Listeners extends BaseListener implements CycleListener { @Override public void onCycleSkip(CycleSkipReason reason) { Assert.fail(); } @Override public void onNewDeltaChain(long version) { reportCaller(); } @Override public void onCycleStart(long version) { reportCaller(); } @Override public void onCycleComplete( Status status, HollowProducer.ReadState readState, long version, Duration elapsed) { reportCaller(); } } Listeners ls = new Listeners(); producer.addListener(ls); producer.runCycle(ws -> ws.add(new Top(1))); Assert.assertEquals(3, ls.callCount.size()); } @Test public void testBlobPublishAsync() { ExecutorService executor = Executors.newCachedThreadPool(); HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withSnapshotPublishExecutor(executor) .build(); producer.initializeDataModel(Top.class); producer.runCycle(ws -> ws.add(new Top(1))); class Listeners extends BaseListener implements PublishListener { CompletableFuture<HollowProducer.Blob> snapshotBlob; @Override public void onNoDeltaAvailable(long version) { } @Override public void onPublishStart(long version) { } @Override public void onBlobStage(Status status, HollowProducer.Blob blob, Duration elapsed) { } @Override public void onBlobPublish(Status status, HollowProducer.Blob blob, Duration elapsed) { Assert.assertNotEquals(HollowProducer.Blob.Type.SNAPSHOT, blob.getType()); } @Override public void onBlobPublishAsync(CompletableFuture<HollowProducer.Blob> blob) { reportCaller(); this.snapshotBlob = blob.thenApply(b -> { Assert.assertEquals(HollowProducer.Blob.Type.SNAPSHOT, b.getType()); try { InputStream contents = b.newInputStream(); contents.read(); } catch (Exception e) { throw new RuntimeException(e); } return b; }); } @Override public void onPublishComplete(Status status, long version, Duration elapsed) { } } Listeners ls = new Listeners(); producer.addListener(ls); producer.runCycle(ws -> ws.add(new Top(2))); Assert.assertEquals(1, ls.callCount.size()); Assert.assertNotNull(ls.snapshotBlob); HollowProducer.Blob b = ls.snapshotBlob.join(); } @Test public void testBlobPublishAsyncExecutorFail() { Executor executor = (r) -> { throw new RejectedExecutionException(); }; HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withSnapshotPublishExecutor(executor) .build(); producer.initializeDataModel(Top.class); producer.runCycle(ws -> ws.add(new Top(1))); class Listeners extends BaseListener implements PublishListener { CompletableFuture<HollowProducer.Blob> snapshotBlob; @Override public void onNoDeltaAvailable(long version) { } @Override public void onPublishStart(long version) { } @Override public void onBlobStage(Status status, HollowProducer.Blob blob, Duration elapsed) { } @Override public void onBlobPublish(Status status, HollowProducer.Blob blob, Duration elapsed) { Assert.assertNotEquals(HollowProducer.Blob.Type.SNAPSHOT, blob.getType()); } @Override public void onBlobPublishAsync(CompletableFuture<HollowProducer.Blob> blob) { reportCaller(); this.snapshotBlob = blob; } @Override public void onPublishComplete(Status status, long version, Duration elapsed) { reportCaller(); Assert.assertEquals(Status.StatusType.FAIL, status.getType()); Assert.assertTrue(status.getCause() instanceof RejectedExecutionException); } } Listeners ls = new Listeners(); producer.addListener(ls); try { producer.runCycle(ws -> ws.add(new Top(2))); Assert.fail(); } catch (RejectedExecutionException e) { } Assert.assertEquals(2, ls.callCount.size()); Assert.assertNotNull(ls.snapshotBlob); Assert.assertTrue(ls.snapshotBlob.isCompletedExceptionally()); try { ls.snapshotBlob.join(); Assert.fail(); } catch (CompletionException e) { Assert.assertTrue(e.getCause() instanceof RejectedExecutionException); } } static class Top { final int id; Top(int id) { this.id = id; } } }
8,821
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/SchemaChangeTest.java
package com.netflix.hollow.api.producer; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.core.HollowBlobHeader; import com.netflix.hollow.core.HollowStateEngine; import com.netflix.hollow.core.read.engine.HollowBlobHeaderReader; import java.io.IOException; import java.util.function.Function; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Test; public class SchemaChangeTest { static class V1 { static class A { int i; A(int i) { this.i = i; } } } static class V2 { static class A { int i; String s; A(int i, String s) { this.i = i; this.s = s; } } } @Test public void test() throws Exception { InMemoryBlobStore bs = new InMemoryBlobStore(); HollowProducer producer = HollowProducer.withPublisher(bs) .withBlobStager(new HollowInMemoryBlobStager()) .build(); long v1 = producer.runCycle(ws -> { ws.add(new V1.A(1)); }); testChangeHeader(bs, Long.MIN_VALUE, v1, false); producer = HollowProducer.withPublisher(bs) .withBlobStager(new HollowInMemoryBlobStager()) .build(); producer.initializeDataModel(V2.A.class); producer.restore(v1, bs); long v2 = producer.runCycle(ws -> { ws.add(new V2.A(1, "1")); }); HollowConsumer.Blob blob = bs.retrieveSnapshotBlob(v2); HollowBlobHeaderReader r = new HollowBlobHeaderReader(); HollowBlobHeader header = r.readHeader(blob.getInputStream()); testChangeHeader(bs, v1, v2, true); } void testChangeHeader(HollowConsumer.BlobRetriever br, long fromVersion, long toVersion, boolean present) throws IOException { testChangeHeader(getHeader(br, r -> r.retrieveSnapshotBlob(toVersion)), present); if (fromVersion != Long.MIN_VALUE) { testChangeHeader(getHeader(br, r -> r.retrieveDeltaBlob(fromVersion)), present); } } void testChangeHeader(HollowBlobHeader header, boolean present) { Assert.assertEquals( present, header.getHeaderTags().containsKey(HollowStateEngine.HEADER_TAG_SCHEMA_CHANGE)); if (present) { String v = header.getHeaderTags().get(HollowStateEngine.HEADER_TAG_SCHEMA_CHANGE); Assert.assertTrue(Boolean.parseBoolean(v)); } } HollowBlobHeader getHeader(HollowConsumer.BlobRetriever br, Function<HollowConsumer.BlobRetriever, HollowConsumer.Blob> f) throws IOException { HollowConsumer.Blob blob = f.apply(br); HollowBlobHeaderReader r = new HollowBlobHeaderReader(); return r.readHeader(blob.getInputStream()); } }
8,822
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/HollowProducerFakeListener.java
package com.netflix.hollow.api.producer; import java.util.concurrent.TimeUnit; public class HollowProducerFakeListener implements HollowProducerListener { public ProducerStatus getSuccessFakeStatus(long version) { return new ProducerStatus(Status.SUCCESS, null, version, null); } public ProducerStatus getFailFakeStatus(long version) { return new ProducerStatus(Status.FAIL, null, version, null); } @Override public void onProducerInit(long elapsed, TimeUnit unit) { } @Override public void onProducerRestoreStart(long restoreVersion) { } @Override public void onProducerRestoreComplete(RestoreStatus status, long elapsed, TimeUnit unit) { } @Override public void onNewDeltaChain(long version) { } @Override public void onCycleStart(long version) { } @Override public void onCycleComplete(ProducerStatus status, long elapsed, TimeUnit unit) { } @Override public void onNoDeltaAvailable(long version) { } @Override public void onPopulateStart(long version) { } @Override public void onPopulateComplete(ProducerStatus status, long elapsed, TimeUnit unit) { } @Override public void onPublishStart(long version) { } @Override public void onPublishComplete(ProducerStatus status, long elapsed, TimeUnit unit) { } @Override public void onArtifactPublish(PublishStatus publishStatus, long elapsed, TimeUnit unit) { } @Override public void onIntegrityCheckStart(long version) { } @Override public void onIntegrityCheckComplete(ProducerStatus status, long elapsed, TimeUnit unit) { } @Override public void onValidationStart(long version) { } @Override public void onValidationComplete(ProducerStatus status, long elapsed, TimeUnit unit) { } @Override public void onAnnouncementStart(long version) { } @Override public void onAnnouncementStart(HollowProducer.ReadState readState) { } @Override public void onAnnouncementComplete(ProducerStatus status, long elapsed, TimeUnit unit) { } }
8,823
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/HollowIncrementalProducerTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.producer; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.objects.HollowObject; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.api.producer.HollowProducer.Populator; import com.netflix.hollow.api.producer.HollowProducer.WriteState; import com.netflix.hollow.api.producer.enforcer.SingleProducerEnforcer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.core.index.HollowPrimaryKeyIndex; import com.netflix.hollow.core.read.dataaccess.HollowTypeDataAccess; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.read.engine.HollowTypeReadState; import com.netflix.hollow.core.util.AllHollowRecordCollection; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import com.netflix.hollow.core.write.objectmapper.HollowTypeName; import com.netflix.hollow.core.write.objectmapper.RecordPrimaryKey; import com.netflix.hollow.core.write.objectmapper.flatrecords.FakeHollowSchemaIdentifierMapper; import com.netflix.hollow.core.write.objectmapper.flatrecords.FlatRecordWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; public class HollowIncrementalProducerTest { private InMemoryBlobStore blobStore; @Before public void setUp() { blobStore = new InMemoryBlobStore(); } @Rule public final ExpectedException exception = ExpectedException.none(); @Test public void publishAndLoadASnapshot() { HollowProducer producer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. initializeData(producer); /// now we'll be incrementally updating the state by mutating individual records HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(producer); incrementalProducer.addOrModify(new TypeA(1, "one", 100)); incrementalProducer.addOrModify(new TypeA(2, "two", 2)); incrementalProducer.addOrModify(new TypeA(3, "three", 300)); incrementalProducer.addOrModify(new TypeA(3, "three", 3)); incrementalProducer.addOrModify(new TypeA(4, "five", 6)); incrementalProducer.delete(new TypeA(5, "five", 5)); incrementalProducer.delete(new TypeB(2, "3")); incrementalProducer.addOrModify(new TypeB(5, "5")); incrementalProducer.addOrModify(new TypeB(5, "6")); incrementalProducer.delete(new RecordPrimaryKey("TypeB", new Object[]{3})); /// .runCycle() flushes the changes to a new data state. long nextVersion = incrementalProducer.runCycle(); incrementalProducer.addOrModify(new TypeA(1, "one", 1000)); /// another new state with a single change long finalVersion = incrementalProducer.runCycle(); /// now we read the changes and assert HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(nextVersion); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 100L); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 3, "three", 3L); assertTypeA(idx, 4, "four", 4L); assertTypeA(idx, 4, "five", 6L); assertTypeA(idx, 5, "five", null); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeB", "id"); Assert.assertFalse(idx.containsDuplicates()); assertTypeB(idx, 1, "1"); assertTypeB(idx, 2, null); assertTypeB(idx, 3, null); assertTypeB(idx, 4, "4"); assertTypeB(idx, 5, "6"); consumer.triggerRefreshTo(finalVersion); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 1000L); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 3, "three", 3L); assertTypeA(idx, 4, "four", 4L); assertTypeA(idx, 4, "five", 6L); assertTypeA(idx, 5, "five", null); } @Test public void addIfAbsentWillInitializeNewRecordsButNotOverwriteExistingRecords() { HollowProducer producer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. initializeData(producer); /// now we'll be incrementally updating the state by mutating individual records HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(producer); incrementalProducer.addIfAbsent(new TypeA(100, "one hundred", 9999)); // new incrementalProducer.addIfAbsent(new TypeA(101, "one hundred and one", 9998)); // new incrementalProducer.addIfAbsent(new TypeA(1, "one", 9997)); // exists in prior state incrementalProducer.addIfAbsent(new TypeA(2, "two", 9996)); // exists in prior state incrementalProducer.addOrModify(new TypeA(102, "one hundred and two", 9995)); // new incrementalProducer.addIfAbsent(new TypeA(102, "one hundred and two", 9994)); // new, but already added incrementalProducer.addIfAbsent(new TypeA(103, "one hundred and three", 9993)); // new incrementalProducer.addOrModify(new TypeA(103, "one hundred and three", 9992)); // overwrites prior call to addIfAbsent long version = incrementalProducer.runCycle(); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(version); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 100, "one hundred", 9999L); assertTypeA(idx, 101, "one hundred and one", 9998L); assertTypeA(idx, 1, "one", 1L); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 102, "one hundred and two", 9995L); assertTypeA(idx, 103, "one hundred and three", 9992L); } @Test public void updateStateWithUnavailableCollectionElementTypes() { // Producer is created but not initialized IncrementalProducer will directly initialize the first snapshot HollowProducer producer = createInMemoryProducer(); HollowWriteStateEngine dataset = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(dataset); mapper.doNotUseDefaultHashKeys(); mapper.initializeTypeState(TypeWithChildCollections.class); producer.initializeDataModel(dataset.getSchema("TypeWithChildCollections"), dataset.getSchema("SetOfElementType"), dataset.getSchema("ListOfElementType"), dataset.getSchema("MapOfElementTypeToElementType")); /// add/modify state of a producer with an empty previous state. delete requests for non-existent records will be ignored HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(producer); FlatRecordWriter writer = new FlatRecordWriter(dataset, new FakeHollowSchemaIdentifierMapper(dataset)); mapper.writeFlat(new TypeWithChildCollections(100, null), writer); incrementalProducer.addOrModify(writer.generateFlatRecord()); long version = incrementalProducer.runCycle(); incrementalProducer.delete(new RecordPrimaryKey("TypeWithChildCollections", new Object[] {100})); writer.reset(); mapper.writeFlat(new TypeWithChildCollections(101, null), writer); incrementalProducer.addOrModify(writer.generateFlatRecord()); long nextVersion = incrementalProducer.runCycle(); Assert.assertTrue(nextVersion > 0); } @HollowPrimaryKey(fields="id") public static class TypeWithChildCollections { int id; Set<ElementType> set; List<ElementType> list; Map<ElementType, ElementType> map; public TypeWithChildCollections(int id, Integer val) { ElementType el = val == null ? null : new ElementType(val); this.id = id; this.set = el == null ? Collections.emptySet() : Collections.singleton(el); this.list = el == null ? Collections.emptyList() : Collections.singletonList(el); this.map = el == null ? Collections.emptyMap() : Collections.singletonMap(el, el); } } public static class ElementType { int value; public ElementType(int value) { this.value = value; } } @Test public void publishAndLoadASnapshotDirectly() { // Producer is created but not initialized IncrementalProducer will directly initialize the first snapshot HollowProducer producer = createInMemoryProducer(); /// add/modify state of a producer with an empty previous state. delete requests for non-existent records will be ignored HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(producer); incrementalProducer.addOrModify(new TypeA(1, "one", 100)); incrementalProducer.addOrModify(new TypeA(2, "two", 2)); incrementalProducer.addOrModify(new TypeA(3, "three", 300)); incrementalProducer.addOrModify(new TypeA(3, "three", 3)); incrementalProducer.addOrModify(new TypeA(4, "five", 6)); incrementalProducer.delete(new TypeA(5, "five", 5)); incrementalProducer.delete(new TypeB(2, "3")); incrementalProducer.addOrModify(new TypeB(5, "5")); incrementalProducer.addOrModify(new TypeB(5, "6")); incrementalProducer.delete(new RecordPrimaryKey("TypeB", new Object[]{3})); incrementalProducer.addOrModify(new TypeA(4, "four", 4)); /// .runCycle() flushes the changes to a new data state. long nextVersion = incrementalProducer.runCycle(); incrementalProducer.addOrModify(new TypeA(1, "one", 1000)); /// another new state with a single change long finalVersion = incrementalProducer.runCycle(); /// now we read the changes and assert HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(nextVersion); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 100L); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 3, "three", 3L); assertTypeA(idx, 4, "four", 4L); assertTypeA(idx, 4, "five", 6L); assertTypeA(idx, 5, "five", null); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeB", "id"); Assert.assertFalse(idx.containsDuplicates()); // backing producer was never initialized, so only records added to the incremental producer are here assertTypeB(idx, 1, null); assertTypeB(idx, 2, null); assertTypeB(idx, 3, null); assertTypeB(idx, 4, null); assertTypeB(idx, 5, "6"); consumer.triggerRefreshTo(finalVersion); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 1000L); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 3, "three", 3L); assertTypeA(idx, 4, "four", 4L); assertTypeA(idx, 4, "five", 6L); assertTypeA(idx, 5, "five", null); } @Test public void publishDirectlyAndRestore() { // Producer is created but not initialized. IncrementalProducer will directly initialize the first snapshot /// add/modify state of a producer with an empty previous state. delete requests for non-existent records will be ignored HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(createInMemoryProducer()); incrementalProducer.addOrModify(new TypeA(1, "one", 100)); incrementalProducer.addOrModify(new TypeA(2, "two", 2)); incrementalProducer.addOrModify(new TypeA(3, "three", 300)); incrementalProducer.addOrModify(new TypeA(3, "three", 3)); incrementalProducer.addOrModify(new TypeA(4, "five", 6)); incrementalProducer.delete(new TypeA(5, "five", 5)); incrementalProducer.delete(new TypeB(2, "2")); incrementalProducer.addOrModify(new TypeB(4, "four")); incrementalProducer.addOrModify(new TypeB(5, "6")); incrementalProducer.addOrModify(new TypeB(5, "5")); incrementalProducer.delete(new RecordPrimaryKey("TypeB", new Object[] { 4 })); incrementalProducer.addOrModify(new TypeB(6, "6")); /// .runCycle() flushes the changes to a new data state. long nextVersion = incrementalProducer.runCycle(); /// now we read the changes and assert HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(nextVersion); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 100L); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 3, "three", 3L); assertTypeA(idx, 4, "five", 6L); assertTypeA(idx, 5, "five", null); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeB", "id"); Assert.assertFalse(idx.containsDuplicates()); // backing producer was never initialized, so only records added to the incremental producer are here assertTypeB(idx, 1, null); assertTypeB(idx, 2, null); assertTypeB(idx, 3, null); assertTypeB(idx, 4, null); assertTypeB(idx, 5, "5"); assertTypeB(idx, 6, "6"); // Create NEW incremental producer which will restore from the state left by the previous incremental producer /// adding a new type this time (TypeB). HollowProducer backingProducer = createInMemoryProducer(); backingProducer.initializeDataModel(TypeA.class, TypeB.class); backingProducer.restore(nextVersion, blobStore); HollowIncrementalProducer incrementalProducer2 = new HollowIncrementalProducer(backingProducer); incrementalProducer2.delete(new TypeA(1, "one", 100)); incrementalProducer2.delete(new TypeA(2, "one", 100)); incrementalProducer2.addOrModify(new TypeA(5, "five", 5)); incrementalProducer2.addOrModify(new TypeB(1, "1")); incrementalProducer2.addOrModify(new TypeB(2, "2")); incrementalProducer2.addOrModify(new TypeB(3, "3")); incrementalProducer2.addOrModify(new TypeB(4, "4")); incrementalProducer2.delete(new TypeB(5, "ignored")); /// .runCycle() flushes the changes to a new data state. long finalVersion = incrementalProducer2.runCycle(); /// now we read the changes and assert consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(finalVersion); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", null); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 3, "three", 3L); assertTypeA(idx, 4, "five", 6L); assertTypeA(idx, 5, "five", 5L); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeB", "id"); Assert.assertFalse(idx.containsDuplicates()); // backing producer was never initialized, so only records added to the incremental producer are here assertTypeB(idx, 1, "1"); assertTypeB(idx, 2, "2"); assertTypeB(idx, 3, "3"); assertTypeB(idx, 4, "4"); assertTypeB(idx, 5, null); assertTypeB(idx, 6, "6"); } @Test public void continuesARestoredState() { HollowProducer genesisProducer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. long originalVersion = genesisProducer.runCycle(new Populator() { public void populate(WriteState state) throws Exception { state.add(new TypeA(1, "one", 1)); } }); /// now at some point in the future, we will start up and create a new classic producer /// to back the HollowIncrementalProducer. HollowProducer backingProducer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); /// adding a new type this time (TypeB). backingProducer.initializeDataModel(TypeA.class, TypeB.class); /// now create our HollowIncrementalProducer HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(backingProducer); incrementalProducer.restore(originalVersion, blobStore); incrementalProducer.addOrModify(new TypeA(1, "one", 2)); incrementalProducer.addOrModify(new TypeA(2, "two", 2)); incrementalProducer.addOrModify(new TypeB(3, "three")); long version = incrementalProducer.runCycle(); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(originalVersion); consumer.triggerRefreshTo(version); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 2L); assertTypeA(idx, 2, "two", 2L); /// consumers with established data models don't have visibility into new types. consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(version); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeB", "id"); Assert.assertFalse(idx.containsDuplicates()); assertTypeB(idx, 3, "three"); } @Test public void canRemoveAndModifyNewTypesFromRestoredState() { HollowProducer genesisProducer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. long originalVersion = genesisProducer.runCycle(new Populator() { public void populate(WriteState state) throws Exception { state.add(new TypeA(1, "one", 1)); } }); /// now at some point in the future, we will start up and create a new classic producer /// to back the HollowIncrementalProducer. HollowProducer backingProducer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .noIntegrityCheck() .build(); /// adding a new type this time (TypeB). backingProducer.initializeDataModel(TypeA.class, TypeB.class); /// now create our HollowIncrementalProducer HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(backingProducer); incrementalProducer.restore(originalVersion, blobStore); incrementalProducer.addOrModify(new TypeA(1, "one", 2)); incrementalProducer.addOrModify(new TypeA(2, "two", 2)); incrementalProducer.addOrModify(new TypeB(3, "three")); incrementalProducer.addOrModify(new TypeB(4, "four")); incrementalProducer.runCycle(); incrementalProducer.delete(new RecordPrimaryKey("TypeB", new Object[] { 3 })); incrementalProducer.addOrModify(new TypeB(4, "four!")); long version2 = incrementalProducer.runCycle(); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(originalVersion); consumer.triggerRefreshTo(version2); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 2L); assertTypeA(idx, 2, "two", 2L); /// consumers with established data models don't have visibility into new types. consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(version2); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeB", "id"); Assert.assertFalse(idx.containsDuplicates()); assertEquals(-1, idx.getMatchingOrdinal(3)); assertTypeB(idx, 4, "four!"); } @Test public void continuesARestoredStateWithBuilder() { HollowProducer genesisProducer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. long originalVersion = genesisProducer.runCycle(new Populator() { public void populate(WriteState state) throws Exception { state.add(new TypeA(1, "one", 1)); } }); /// now at some point in the future, we will start up and create a new classic producer /// to back the HollowIncrementalProducer. HollowProducer backingProducer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); HollowIncrementalProducer incrementalProducer = HollowIncrementalProducer.withProducer(backingProducer) .withBlobRetriever(blobStore) .withAnnouncementWatcher(new FakeAnnouncementWatcher(originalVersion)) .withDataModel(TypeA.class, TypeB.class) .build(); incrementalProducer.restoreFromLastState(); incrementalProducer.addOrModify(new TypeA(1, "one", 2)); incrementalProducer.addOrModify(new TypeA(2, "two", 2)); incrementalProducer.addOrModify(new TypeB(3, "three")); long version = incrementalProducer.runCycle(); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(originalVersion); consumer.triggerRefreshTo(version); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 2L); assertTypeA(idx, 2, "two", 2L); /// consumers with established data models don't have visibility into new types. consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(version); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeB", "id"); Assert.assertFalse(idx.containsDuplicates()); assertTypeB(idx, 3, "three"); } @Test(expected = RuntimeException.class) public void failsWhenLastStateIsNotAvailable() { HollowProducer backingProducer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); HollowIncrementalProducer incrementalProducer = HollowIncrementalProducer.withProducer(backingProducer) .withBlobRetriever(blobStore) .withAnnouncementWatcher(new FakeAnnouncementWatcher(0)) .withDataModel(TypeA.class, TypeB.class) .build(); incrementalProducer.restoreFromLastState(); } @Test(expected = IllegalArgumentException.class) public void failsWithNoProducer() { //No Hollow Producer HollowIncrementalProducer.withProducer(null) .build(); } @Test(expected = NullPointerException.class) public void failsWhenNotEnoughArgs() { HollowProducer backingProducer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); //No AnnouncementWatcher, BlobRetriever and DataModel to restore HollowIncrementalProducer incrementalProducer = HollowIncrementalProducer.withProducer(backingProducer) .build(); incrementalProducer.restoreFromLastState(); } @Test public void publishUsingThreadConfig() { HollowProducer producer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. initializeData(producer); /// now we'll be incrementally updating the state by mutating individual records HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(producer, 2.0d); incrementalProducer.addOrModify(new TypeA(1, "one", 100)); incrementalProducer.addOrModify(new TypeA(2, "two", 2)); incrementalProducer.addOrModify(new TypeA(3, "three", 300)); incrementalProducer.addOrModify(new TypeA(3, "three", 3)); incrementalProducer.addOrModify(new TypeA(4, "five", 6)); incrementalProducer.delete(new TypeA(5, "five", 5)); incrementalProducer.delete(new TypeB(2, "3")); incrementalProducer.addOrModify(new TypeB(5, "5")); incrementalProducer.addOrModify(new TypeB(5, "6")); incrementalProducer.delete(new RecordPrimaryKey("TypeB", new Object[]{3})); /// .runCycle() flushes the changes to a new data state. long nextVersion = incrementalProducer.runCycle(); incrementalProducer.addOrModify(new TypeA(1, "one", 1000)); /// another new state with a single change long finalVersion = incrementalProducer.runCycle(); /// now we read the changes and assert HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(nextVersion); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 100L); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 3, "three", 3L); assertTypeA(idx, 4, "four", 4L); assertTypeA(idx, 4, "five", 6L); assertTypeA(idx, 5, "five", null); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeB", "id"); Assert.assertFalse(idx.containsDuplicates()); assertTypeB(idx, 1, "1"); assertTypeB(idx, 2, null); assertTypeB(idx, 3, null); assertTypeB(idx, 4, "4"); assertTypeB(idx, 5, "6"); consumer.triggerRefreshTo(finalVersion); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 1000L); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 3, "three", 3L); assertTypeA(idx, 4, "four", 4L); assertTypeA(idx, 4, "five", 6L); assertTypeA(idx, 5, "five", null); } @Test public void discardChanges() { HollowProducer producer = createInMemoryProducer(); initializeData(producer); HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(producer); incrementalProducer.addOrModify(new TypeB(1, "one")); long nextVersion = incrementalProducer.runCycle(); /// now we read the changes and assert HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(nextVersion); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeB", "id"); assertTypeB(idx, 1, "one"); incrementalProducer.delete(new TypeB(1, "one")); Assert.assertTrue(incrementalProducer.hasChanges()); //Discard with an object incrementalProducer.discard(new TypeB(1, "one")); Assert.assertFalse(incrementalProducer.hasChanges()); long version = incrementalProducer.runCycle(); consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(version); assertTypeB(idx, 1, "one"); incrementalProducer.delete(new TypeB(1, "one")); Assert.assertTrue(incrementalProducer.hasChanges()); //Discard with a PrimaryKey incrementalProducer.discard(new RecordPrimaryKey("TypeB", new Object[]{1})); Assert.assertFalse(incrementalProducer.hasChanges()); long finalVersion = incrementalProducer.runCycle(); consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(finalVersion); assertTypeB(idx, 1, "one"); } @Test public void clearMutations() { HollowProducer producer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. initializeData(producer); /// now we'll be incrementally updating the state by mutating individual records HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(producer); incrementalProducer.addOrModify(new TypeA(1, "one", 100)); incrementalProducer.addOrModify(new TypeA(2, "two", 2)); incrementalProducer.addOrModify(new TypeA(3, "three", 300)); incrementalProducer.addOrModify(new TypeA(3, "three", 3)); incrementalProducer.addOrModify(new TypeA(4, "five", 6)); incrementalProducer.delete(new TypeA(5, "five", 5)); incrementalProducer.delete(new TypeB(2, "3")); incrementalProducer.addOrModify(new TypeB(5, "5")); incrementalProducer.addOrModify(new TypeB(5, "6")); incrementalProducer.delete(new RecordPrimaryKey("TypeB", new Object[]{3})); Assert.assertTrue(incrementalProducer.hasChanges()); /// .runCycle() flushes the changes to a new data state. incrementalProducer.runCycle(); Assert.assertFalse(incrementalProducer.hasChanges()); } @Test public void addAndDeleteCollections() { HollowProducer producer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. initializeData(producer); /// now we'll be incrementally updating the state by mutating individual records HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(producer); Collection<Object> addOrModifyList = Arrays.asList( new TypeA(1, "one", 100), new TypeA(2, "two", 2), new TypeA(3, "three", 300), new TypeA(3, "three", 3), new TypeA(4, "five", 6) ); Collection<Object> deleteList = Arrays.asList( new TypeA(5, "five", 5), new TypeB(2, "3") ); incrementalProducer.addOrModify(addOrModifyList); incrementalProducer.delete(deleteList); /// .runCycle() flushes the changes to a new data state. long nextVersion = incrementalProducer.runCycle(); incrementalProducer.addOrModify(new TypeA(1, "one", 1000)); /// another new state with a single change long finalVersion = incrementalProducer.runCycle(); /// now we read the changes and assert HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(nextVersion); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 100L); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 3, "three", 3L); assertTypeA(idx, 4, "four", 4L); assertTypeA(idx, 4, "five", 6L); assertTypeA(idx, 5, "five", null); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeB", "id"); Assert.assertFalse(idx.containsDuplicates()); assertTypeB(idx, 1, "1"); assertTypeB(idx, 2, null); assertTypeB(idx, 3, "3"); assertTypeB(idx, 4, "4"); assertTypeB(idx, 5, null); consumer.triggerRefreshTo(finalVersion); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 1000L); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 3, "three", 3L); assertTypeA(idx, 4, "four", 4L); assertTypeA(idx, 4, "five", 6L); assertTypeA(idx, 5, "five", null); } @Test public void addAndDeleteCollectionsInParallel() { HollowProducer producer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. initializeData(producer); /// now we'll be incrementally updating the state by mutating individual records HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(producer); Collection<Object> addOrModifyList = Arrays.asList( new TypeA(1, "one", 100), new TypeA(2, "two", 2), new TypeA(3, "three", 3), new TypeA(4, "five", 6) ); Collection<Object> deleteList = Arrays.asList( new TypeA(5, "five", 5), new TypeB(2, "3") ); incrementalProducer.addOrModifyInParallel(addOrModifyList); incrementalProducer.deleteInParallel(deleteList); /// .runCycle() flushes the changes to a new data state. long nextVersion = incrementalProducer.runCycle(); incrementalProducer.addOrModify(new TypeA(1, "one", 1000)); /// another new state with a single change long finalVersion = incrementalProducer.runCycle(); /// now we read the changes and assert HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(nextVersion); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 100L); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 3, "three", 3L); assertTypeA(idx, 4, "four", 4L); assertTypeA(idx, 4, "five", 6L); assertTypeA(idx, 5, "five", null); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeB", "id"); Assert.assertFalse(idx.containsDuplicates()); assertTypeB(idx, 1, "1"); assertTypeB(idx, 2, null); assertTypeB(idx, 3, "3"); assertTypeB(idx, 4, "4"); assertTypeB(idx, 5, null); consumer.triggerRefreshTo(finalVersion); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 1000L); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 3, "three", 3L); assertTypeA(idx, 4, "four", 4L); assertTypeA(idx, 4, "five", 6L); assertTypeA(idx, 5, "five", null); } @Test public void discardCollections() { HollowProducer producer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. initializeData(producer); /// now we'll be incrementally updating the state by mutating individual records HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(producer); Collection<Object> addOrModifyList = Arrays.asList( new TypeA(1, "one", 100), new TypeA(2, "two", 2), new TypeA(3, "three", 300), new TypeA(3, "three", 3), new TypeA(4, "five", 6) ); Collection<Object> deleteList = Arrays.asList( new TypeA(5, "five", 5), new TypeB(2, "3") ); incrementalProducer.addOrModify(addOrModifyList); incrementalProducer.delete(deleteList); Assert.assertTrue(incrementalProducer.hasChanges()); incrementalProducer.discard(addOrModifyList); incrementalProducer.discard(deleteList); Assert.assertFalse(incrementalProducer.hasChanges()); long finalVersion = incrementalProducer.runCycle(); /// now we read the changes and assert HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(finalVersion); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 1L); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 3, "three", 3L); assertTypeA(idx, 4, "four", 4L); assertTypeA(idx, 5, "five", 5L); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeB", "id"); Assert.assertFalse(idx.containsDuplicates()); assertTypeB(idx, 1, "1"); assertTypeB(idx, 2, "2"); assertTypeB(idx, 3, "3"); assertTypeB(idx, 4, "4"); assertTypeB(idx, 5, null); } @Test public void discardCollectionsInParallel() { HollowProducer producer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. initializeData(producer); /// now we'll be incrementally updating the state by mutating individual records HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(producer); Collection<Object> addOrModifyList = Arrays.asList( new TypeA(1, "one", 100), new TypeA(2, "two", 2), new TypeA(3, "three", 300), new TypeA(3, "three", 3), new TypeA(4, "five", 6) ); Collection<Object> deleteList = Arrays.asList( new TypeA(5, "five", 5), new TypeB(2, "3") ); incrementalProducer.addOrModify(addOrModifyList); incrementalProducer.delete(deleteList); Assert.assertTrue(incrementalProducer.hasChanges()); incrementalProducer.discardInParallel(addOrModifyList); incrementalProducer.discardInParallel(deleteList); Assert.assertFalse(incrementalProducer.hasChanges()); long finalVersion = incrementalProducer.runCycle(); /// now we read the changes and assert HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(finalVersion); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 1L); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 3, "three", 3L); assertTypeA(idx, 4, "four", 4L); assertTypeA(idx, 5, "five", 5L); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeB", "id"); Assert.assertFalse(idx.containsDuplicates()); assertTypeB(idx, 1, "1"); assertTypeB(idx, 2, "2"); assertTypeB(idx, 3, "3"); assertTypeB(idx, 4, "4"); assertTypeB(idx, 5, null); } @Test public void writeOnlyWhenPrimary() { FakeSingleProducerEnforcer fakeSingleProducerEnforcer = new FakeSingleProducerEnforcer(); HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withVersionMinter(new TestVersionMinter()) .withSingleProducerEnforcer(fakeSingleProducerEnforcer) .build(); /// initialize the data -- classic producer creates the first state in the delta chain. long initialVersion = initializeData(producer); /// now we'll be incrementally updating the state by mutating individual records HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(producer); incrementalProducer.addOrModify(new TypeA(1, "one", 100)); incrementalProducer.addOrModify(new TypeA(2, "two", 2)); incrementalProducer.addOrModify(new TypeA(3, "three", 300)); incrementalProducer.addOrModify(new TypeA(3, "three", 3)); incrementalProducer.addOrModify(new TypeA(4, "five", 6)); incrementalProducer.delete(new TypeA(5, "five", 5)); incrementalProducer.delete(new TypeB(2, "3")); incrementalProducer.addOrModify(new TypeB(5, "5")); incrementalProducer.addOrModify(new TypeB(5, "6")); incrementalProducer.delete(new RecordPrimaryKey("TypeB", new Object[] { 3 })); Assert.assertTrue(incrementalProducer.hasChanges()); /// .runCycle() flushes the changes to a new data state. long version = incrementalProducer.runCycle(); Assert.assertEquals(initialVersion, version); Assert.assertTrue(incrementalProducer.hasChanges()); //Enable producer as primary fakeSingleProducerEnforcer.force(); long latestVersion = incrementalProducer.runCycle(); Assert.assertFalse(incrementalProducer.hasChanges()); Assert.assertEquals(1, latestVersion); } @Test public void resumeWorkAfterAnnouncementFail() { FakeAnnouncer fakeAnnouncer = new FakeAnnouncer(); FakeAnnouncer fakeAnnouncerSpy = Mockito.spy(fakeAnnouncer); HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withAnnouncer(fakeAnnouncerSpy) .withVersionMinter(new HollowProducer.VersionMinter() { long counter = 0; public long mint() { return ++counter; } }) .withNumStatesBetweenSnapshots(5) .build(); initializeData(producer); HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(producer); incrementalProducer.addOrModify(new TypeA(11, "eleven", 11)); incrementalProducer.runCycle(); incrementalProducer.addOrModify(new TypeA(1, "one", 100)); incrementalProducer.addOrModify(new TypeA(2, "two", 2)); incrementalProducer.addOrModify(new TypeA(3, "three", 300)); //Fail announcement on this cycle Mockito.doThrow(new RuntimeException("oops")).when(fakeAnnouncerSpy).announce(3); try { incrementalProducer.runCycle(); } catch (RuntimeException e) { } //Incremental producer still has changes Assert.assertTrue(incrementalProducer.hasChanges()); incrementalProducer.addOrModify(new TypeA(10, "ten", 100)); long version = incrementalProducer.runCycle(); Assert.assertFalse(incrementalProducer.hasChanges()); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(version); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 10, "ten", 100L); } @Test public void removeOrphanObjectsWithTypeInSnapshot() { HollowProducer producer = createInMemoryProducer(); producer.runCycle(new Populator() { public void populate(WriteState state) throws Exception { state.add(new TypeC(1, new TypeD(1, "one"))); } }); HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(producer); TypeD typeD2 = new TypeD(2, "two"); TypeC typeC2 = new TypeC(2, typeD2); incrementalProducer.addOrModify(typeC2); long nextVersion = incrementalProducer.runCycle(); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(nextVersion); Collection<HollowObject> allHollowObjectsTypeD = getAllHollowObjects(consumer, "TypeD"); List<String> typeDNames = new ArrayList<>(); for (HollowObject hollowObject : allHollowObjectsTypeD) { typeDNames.add(((GenericHollowObject) hollowObject).getObject("value").toString()); } Assert.assertTrue(typeDNames.contains("two")); TypeD typeD3 = new TypeD(3, "three"); typeC2 = new TypeC(2, typeD3); incrementalProducer.addOrModify(typeC2); long finalVersion = incrementalProducer.runCycle(); consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(finalVersion); allHollowObjectsTypeD = getAllHollowObjects(consumer, "TypeD"); List<String> finalTypeDNames = new ArrayList<>(); for (HollowObject hollowObject : allHollowObjectsTypeD) { finalTypeDNames.add(((GenericHollowObject) hollowObject).getObject("value").toString()); } Assert.assertFalse(finalTypeDNames.contains("two")); } @Test public void removeOrphanObjectsWithoutTypeInDelta() { HollowProducer producer = createInMemoryProducer(); producer.initializeDataModel(TypeC.class); producer.runCycle(new Populator() { public void populate(WriteState state) throws Exception { state.add(new TypeA(1, "one", 1)); } }); HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(producer); TypeD typeD2 = new TypeD(2, "two"); TypeC typeC2 = new TypeC(2, typeD2); incrementalProducer.addOrModify(typeC2); incrementalProducer.runCycle(); TypeD typeD3 = new TypeD(3, "three"); typeC2 = new TypeC(2, typeD3); //Modify typeC2 to point to a new TypeD object incrementalProducer.addOrModify(typeC2); //Cycle writes a snapshot long finalVersion = incrementalProducer.runCycle(); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(finalVersion); Collection<HollowObject> allHollowObjectsTypeD = getAllHollowObjects(consumer, "TypeD"); List<String> finalTypeDNames = new ArrayList<>(); for (HollowObject hollowObject : allHollowObjectsTypeD) { finalTypeDNames.add(((GenericHollowObject) hollowObject).getObject("value").toString()); } Assert.assertFalse(finalTypeDNames.contains("two")); } @Test public void fireSuccessListener() { HollowProducer producer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. initializeData(producer); FakeIncrementalCycleListener listener = new FakeIncrementalCycleListener(); /// now we'll be incrementally updating the state by mutating individual records HollowIncrementalProducer incrementalProducer = HollowIncrementalProducer .withProducer(producer) .withListener(listener) .build(); incrementalProducer.addOrModify(new TypeA(1, "one", 100)); incrementalProducer.addOrModify(new TypeA(2, "two", 2)); incrementalProducer.addOrModify(new TypeA(3, "three", 300)); incrementalProducer.delete(new TypeA(5, "five", 5)); /// .runCycle() flushes the changes to a new data state. long nextVersion = incrementalProducer.runCycle(); Assert.assertEquals(nextVersion, listener.getVersion()); Assert.assertEquals(IncrementalCycleListener.Status.SUCCESS, listener.getStatus()); Assert.assertEquals(3L, listener.getRecordsAddedOrModified()); Assert.assertEquals(1L, listener.getRecordsRemoved()); Assert.assertNull(listener.getCause()); incrementalProducer.addOrModify(new TypeA(1, "one", 1000)); /// another new state with a single change long finalVersion = incrementalProducer.runCycle(); Assert.assertEquals(finalVersion, listener.getVersion()); Assert.assertEquals(IncrementalCycleListener.Status.SUCCESS, listener.getStatus()); Assert.assertEquals(1L, listener.getRecordsAddedOrModified()); Assert.assertEquals(0L, listener.getRecordsRemoved()); Assert.assertNull(listener.getCause()); } @Test public void fireFailureListener() { HollowProducer producer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. initializeData(producer); FakeIncrementalCycleListener listener = new FakeIncrementalCycleListener(); HollowProducer fakeHollowProducer = FakeHollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withVersionMinter(new TestVersionMinter()) .build(); HollowProducer fakeHollowProducerSpy = Mockito.spy(fakeHollowProducer); /// now we'll be incrementally updating the state by mutating individual records HollowIncrementalProducer incrementalProducer = HollowIncrementalProducer .withProducer(fakeHollowProducerSpy) .withListener(listener) .build(); incrementalProducer.addOrModify(new TypeA(1, "one", 100)); incrementalProducer.addOrModify(new TypeA(2, "two", 2)); incrementalProducer.addOrModify(new TypeA(3, "three", 300)); incrementalProducer.addOrModify(new TypeA(3, "three", 3)); incrementalProducer.addOrModify(new TypeA(4, "five", 6)); incrementalProducer.delete(new TypeA(5, "five", 5)); Mockito.doThrow(new RuntimeException("oops")).when(fakeHollowProducerSpy).runCycle(any(HollowProducer.Populator.class)); long nextVersion = incrementalProducer.runCycle(); Assert.assertEquals(nextVersion, listener.getVersion()); Assert.assertEquals(IncrementalCycleListener.Status.FAIL, listener.getStatus()); Assert.assertEquals(4L, listener.getRecordsAddedOrModified()); Assert.assertEquals(1L, listener.getRecordsRemoved()); Assert.assertNotNull(listener.getCause()); } @Test public void successListenerWithMetadata() { HollowProducer producer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. initializeData(producer); FakeIncrementalCycleListener listener = new FakeIncrementalCycleListener(); /// now we'll be incrementally updating the state by mutating individual records HollowIncrementalProducer incrementalProducer = HollowIncrementalProducer .withProducer(producer) .withListener(listener) .build(); HashMap<String, Object> cycleMetadata = new HashMap<>(); cycleMetadata.put("foo", "bar"); incrementalProducer.addAllCycleMetadata(cycleMetadata); Assert.assertTrue(incrementalProducer.hasMetadata()); //Add more metadata incrementalProducer.addCycleMetadata("key2", "baz"); incrementalProducer.addCycleMetadata("key3", "baz"); incrementalProducer.addOrModify(new TypeA(1, "one", 100)); //Remove metadata incrementalProducer.removeFromCycleMetadata("key2"); /// .runCycle() flushes the changes to a new data state. long nextVersion = incrementalProducer.runCycle(); Assert.assertTrue(listener.getCycleMetadata().containsKey("foo")); Assert.assertFalse(listener.getCycleMetadata().containsKey("key2")); Assert.assertTrue(listener.getCycleMetadata().containsKey("key3")); Assert.assertEquals(nextVersion, listener.getVersion()); Assert.assertEquals(IncrementalCycleListener.Status.SUCCESS, listener.getStatus()); Assert.assertFalse(incrementalProducer.hasMetadata()); incrementalProducer.addOrModify(new TypeA(1, "one", 1000)); incrementalProducer.runCycle(); Assert.assertEquals(new HashMap<String, Object>(), listener.getCycleMetadata()); } @Test public void fireFailureListenerWithMetadata() { HollowProducer producer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. initializeData(producer); FakeIncrementalCycleListener listener = new FakeIncrementalCycleListener(); HollowProducer fakeHollowProducer = FakeHollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withVersionMinter(new TestVersionMinter()) .build(); HollowProducer fakeHollowProducerSpy = Mockito.spy(fakeHollowProducer); /// now we'll be incrementally updating the state by mutating individual records HollowIncrementalProducer incrementalProducer = HollowIncrementalProducer .withProducer(fakeHollowProducerSpy) .withListener(listener) .build(); HashMap<String, Object> cycleMetadata = new HashMap<>(); cycleMetadata.put("foo", "bar"); incrementalProducer.addAllCycleMetadata(cycleMetadata); Assert.assertTrue(incrementalProducer.hasMetadata()); incrementalProducer.addOrModify(new TypeA(1, "one", 100)); Mockito.doThrow(new RuntimeException("oops")).when(fakeHollowProducerSpy).runCycle(any(HollowProducer.Populator.class)); incrementalProducer.runCycle(); Assert.assertEquals(IncrementalCycleListener.Status.FAIL, listener.getStatus()); Assert.assertEquals(cycleMetadata, listener.getCycleMetadata()); Assert.assertFalse(incrementalProducer.hasMetadata()); } @Test public void addsListenersAfterInitialization() { HollowProducer producer = createInMemoryProducer(); initializeData(producer); FakeIncrementalCycleListener listener = new FakeIncrementalCycleListener(); HollowIncrementalProducer incrementalProducer = HollowIncrementalProducer .withProducer(producer) .build(); //Adding the listener after initialization incrementalProducer.addListener(listener); incrementalProducer.addOrModify(new TypeA(1, "one", 100)); /// .runCycle() flushes the changes to a new data state. long nextVersion = incrementalProducer.runCycle(); Assert.assertEquals(nextVersion, listener.getVersion()); Assert.assertEquals(IncrementalCycleListener.Status.SUCCESS, listener.getStatus()); Assert.assertEquals(1L, listener.getRecordsAddedOrModified()); Assert.assertNull(listener.getCause()); } private class FakeIncrementalCycleListener extends AbstractIncrementalCycleListener { private long recordsRemoved; private long recordsAddedOrModified; private long version; private Status status; private Throwable cause; private Map<String, Object> cycleMetadata; @Override public void onCycleComplete(IncrementalCycleStatus status, long elapsed, TimeUnit unit) { this.status = status.getStatus(); this.recordsAddedOrModified = status.getRecordsAddedOrModified(); this.recordsRemoved = status.getRecordsRemoved(); this.version = status.getVersion(); this.cycleMetadata = status.getCycleMetadata(); } @Override public void onCycleFail(IncrementalCycleStatus status, long elapsed, TimeUnit unit) { this.status = status.getStatus(); this.recordsAddedOrModified = status.getRecordsAddedOrModified(); this.recordsRemoved = status.getRecordsRemoved(); this.version = status.getVersion(); this.cause = status.getCause(); this.cycleMetadata = status.getCycleMetadata(); } public long getRecordsRemoved() { return recordsRemoved; } public long getRecordsAddedOrModified() { return recordsAddedOrModified; } public Status getStatus() { return status; } public long getVersion() { return version; } public Map<String, Object> getCycleMetadata() { return cycleMetadata; } public Throwable getCause() { return cause; } } private static final class TestVersionMinter implements HollowProducer.VersionMinter { private static int versionCounter = 0; @Override public long mint() { return ++versionCounter; } } private static final class FakeHollowProducer extends HollowProducer { public FakeHollowProducer(Publisher publisher, Announcer announcer) { super(publisher, announcer); } public long runCycle() { return runCycle(new Populator() { @Override public void populate(WriteState newState) throws Exception { throw new Exception("something went wrong"); } }); } } private static class FakeAnnouncer implements HollowProducer.Announcer { @Override public void announce(long stateVersion) { } } private HollowProducer createInMemoryProducer() { return HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); } private long initializeData(HollowProducer producer) { return producer.runCycle(new Populator() { public void populate(WriteState state) throws Exception { state.add(new TypeA(1, "one", 1)); state.add(new TypeA(2, "two", 2)); state.add(new TypeA(3, "three", 3)); state.add(new TypeA(4, "four", 4)); state.add(new TypeA(5, "five", 5)); state.add(new TypeB(1, "1")); state.add(new TypeB(2, "2")); state.add(new TypeB(3, "3")); state.add(new TypeB(4, "4")); } }); } private void assertTypeA(HollowPrimaryKeyIndex typeAIdx, int id1, String id2, Long expectedValue) { int ordinal = typeAIdx.getMatchingOrdinal(id1, id2); if (expectedValue == null) { Assert.assertEquals(-1, ordinal); } else { Assert.assertNotEquals(-1, ordinal); GenericHollowObject obj = new GenericHollowObject( typeAIdx.getTypeState(), ordinal); Assert.assertEquals(expectedValue.longValue(), obj.getLong("value")); } } private void assertTypeB(HollowPrimaryKeyIndex typeBIdx, int id1, String expectedValue) { int ordinal = typeBIdx.getMatchingOrdinal(id1); if (expectedValue == null) { Assert.assertEquals(-1, ordinal); } else { Assert.assertNotEquals(-1, ordinal); GenericHollowObject obj = new GenericHollowObject( typeBIdx.getTypeState(), ordinal); Assert.assertEquals(expectedValue, obj.getObject("value") .getString("value")); } } @SuppressWarnings("unused") @HollowPrimaryKey(fields = {"id1", "id2"}) private static class TypeA { int id1; String id2; long value; public TypeA(int id1, String id2, long value) { this.id1 = id1; this.id2 = id2; this.value = value; } } @SuppressWarnings("unused") @HollowPrimaryKey(fields = "id") private static class TypeB { int id; @HollowTypeName(name = "TypeBValue") String value; public TypeB(int id, String value) { this.id = id; this.value = value; } } @SuppressWarnings("unused") @HollowPrimaryKey(fields = "id") private static class TypeC { int id; TypeD typeD; public TypeC(int id, TypeD typeD) { this.id = id; this.typeD = typeD; } } @SuppressWarnings("unused") private static class TypeD { int id; String value; public TypeD(int id, String name) { this.id = id; this.value = name; } } private Collection<HollowObject> getAllHollowObjects(HollowConsumer hollowConsumer, final String type) { final HollowReadStateEngine readStateEngine = hollowConsumer.getStateEngine(); final HollowTypeDataAccess typeDataAccess = readStateEngine.getTypeDataAccess(type); final HollowTypeReadState typeState = typeDataAccess.getTypeState(); return new AllHollowRecordCollection<HollowObject>(typeState) { @Override protected HollowObject getForOrdinal(int ordinal) { return new GenericHollowObject(readStateEngine, type, ordinal); } }; } private static class FakeAnnouncementWatcher implements HollowConsumer.AnnouncementWatcher { private final long fakeVersion; FakeAnnouncementWatcher(long fakeVersion) { this.fakeVersion = fakeVersion; } @Override public long getLatestVersion() { return fakeVersion; } @Override public void subscribeToUpdates(HollowConsumer consumer) { } public long getFakeVersion() { return fakeVersion; } } private static class FakeSingleProducerEnforcer implements SingleProducerEnforcer { private boolean primary = false; @Override public void enable() { primary = true; } @Override public void disable() { primary = false; } @Override public boolean isPrimary() { return primary; } @Override public void force() { primary = true; } } }
8,824
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/HollowProducerIncrementalTest.java
/* * * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.producer; import static org.junit.Assert.assertEquals; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.objects.HollowObject; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.api.producer.listener.IncrementalPopulateListener; import com.netflix.hollow.core.index.HollowPrimaryKeyIndex; import com.netflix.hollow.core.read.dataaccess.HollowTypeDataAccess; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.read.engine.HollowTypeReadState; import com.netflix.hollow.core.util.AllHollowRecordCollection; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import com.netflix.hollow.core.write.objectmapper.HollowTypeName; import com.netflix.hollow.core.write.objectmapper.RecordPrimaryKey; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class HollowProducerIncrementalTest { private InMemoryBlobStore blobStore; @Before public void setUp() { blobStore = new InMemoryBlobStore(); } @Rule public final ExpectedException exception = ExpectedException.none(); @Test public void publishAndLoadASnapshot() { HollowProducer.Incremental producer = createInMemoryIncrementalProducer(); /// initialize the data initializeData(producer); long nextVersion = producer.runIncrementalCycle(iws -> { iws.addOrModify(new TypeA(1, "one", 100)); iws.addOrModify(new TypeA(2, "two", 2)); iws.addOrModify(new TypeA(3, "three", 300)); iws.addOrModify(new TypeA(3, "three", 3)); iws.addOrModify(new TypeA(4, "five", 6)); iws.delete(new TypeA(5, "five", 5)); iws.delete(new TypeB(2, "3")); iws.addOrModify(new TypeB(5, "5")); iws.addOrModify(new TypeB(5, "6")); iws.delete(new RecordPrimaryKey("TypeB", new Object[] {3})); }); long finalVersion = producer.runIncrementalCycle(iws -> { iws.addOrModify(new TypeA(1, "one", 1000)); }); /// now we read the changes and assert HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(nextVersion); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 100L); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 3, "three", 3L); assertTypeA(idx, 4, "four", 4L); assertTypeA(idx, 4, "five", 6L); assertTypeA(idx, 5, "five", null); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeB", "id"); Assert.assertFalse(idx.containsDuplicates()); assertTypeB(idx, 1, "1"); assertTypeB(idx, 2, null); assertTypeB(idx, 3, null); assertTypeB(idx, 4, "4"); assertTypeB(idx, 5, "6"); consumer.triggerRefreshTo(finalVersion); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 1000L); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 3, "three", 3L); assertTypeA(idx, 4, "four", 4L); assertTypeA(idx, 4, "five", 6L); assertTypeA(idx, 5, "five", null); } @Test public void addIfAbsentWillInitializeNewRecordsButNotOverwriteExistingRecords() { HollowProducer.Incremental producer = createInMemoryIncrementalProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. initializeData(producer); long version = producer.runIncrementalCycle(iws -> { iws.addIfAbsent(new TypeA(100, "one hundred", 9999)); // new iws.addIfAbsent(new TypeA(101, "one hundred and one", 9998)); // new iws.addIfAbsent(new TypeA(1, "one", 9997)); // exists in prior state iws.addIfAbsent(new TypeA(2, "two", 9996)); // exists in prior state iws.addOrModify(new TypeA(102, "one hundred and two", 9995)); // new iws.addIfAbsent(new TypeA(102, "one hundred and two", 9994)); // new, but already added iws.addIfAbsent(new TypeA(103, "one hundred and three", 9993)); // new iws.addOrModify(new TypeA(103, "one hundred and three", 9992)); // overwrites prior call to addIfAbsent }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(version); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 100, "one hundred", 9999L); assertTypeA(idx, 101, "one hundred and one", 9998L); assertTypeA(idx, 1, "one", 1L); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 102, "one hundred and two", 9995L); assertTypeA(idx, 103, "one hundred and three", 9992L); } @Test public void publishDirectlyAndRestore() { HollowProducer.Incremental producer = createInMemoryIncrementalProducer(); long nextVersion = producer.runIncrementalCycle(iws -> { iws.addOrModify(new TypeA(1, "one", 100)); iws.addOrModify(new TypeA(2, "two", 2)); iws.addOrModify(new TypeA(3, "three", 300)); iws.addOrModify(new TypeA(3, "three", 3)); iws.addOrModify(new TypeA(4, "five", 6)); iws.delete(new TypeA(5, "five", 5)); iws.delete(new TypeB(2, "2")); iws.addOrModify(new TypeB(4, "four")); iws.addOrModify(new TypeB(5, "6")); iws.addOrModify(new TypeB(5, "5")); iws.delete(new RecordPrimaryKey("TypeB", new Object[] {4})); iws.addOrModify(new TypeB(6, "6")); }); /// now we read the changes and assert HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(nextVersion); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 100L); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 3, "three", 3L); assertTypeA(idx, 4, "five", 6L); assertTypeA(idx, 5, "five", null); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeB", "id"); Assert.assertFalse(idx.containsDuplicates()); // backing producer was never initialized, so only records added to the incremental producer are here assertTypeB(idx, 1, null); assertTypeB(idx, 2, null); assertTypeB(idx, 3, null); assertTypeB(idx, 4, null); assertTypeB(idx, 5, "5"); assertTypeB(idx, 6, "6"); // Create NEW incremental producer which will restore from the state left by the previous incremental producer /// adding a new type this time (TypeB). HollowProducer.Incremental restoringProducer = createInMemoryIncrementalProducer(); restoringProducer.initializeDataModel(TypeA.class, TypeB.class); restoringProducer.restore(nextVersion, blobStore); long finalVersion = producer.runIncrementalCycle(iws -> { iws.delete(new TypeA(1, "one", 100)); iws.delete(new TypeA(2, "one", 100)); iws.addOrModify(new TypeA(5, "five", 5)); iws.addOrModify(new TypeB(1, "1")); iws.addOrModify(new TypeB(2, "2")); iws.addOrModify(new TypeB(3, "3")); iws.addOrModify(new TypeB(4, "4")); iws.delete(new TypeB(5, "ignored")); }); /// now we read the changes and assert consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(finalVersion); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", null); assertTypeA(idx, 2, "two", 2L); assertTypeA(idx, 3, "three", 3L); assertTypeA(idx, 4, "five", 6L); assertTypeA(idx, 5, "five", 5L); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeB", "id"); Assert.assertFalse(idx.containsDuplicates()); // backing producer was never initialized, so only records added to the incremental producer are here assertTypeB(idx, 1, "1"); assertTypeB(idx, 2, "2"); assertTypeB(idx, 3, "3"); assertTypeB(idx, 4, "4"); assertTypeB(idx, 5, null); assertTypeB(idx, 6, "6"); } @Test public void continuesARestoredState() { HollowProducer genesisProducer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. long originalVersion = genesisProducer.runCycle(state -> { state.add(new TypeA(1, "one", 1)); }); /// now at some point in the future, we will start up and create a new classic producer /// to back the HollowIncrementalProducer. HollowProducer.Incremental restoringProducer = createInMemoryIncrementalProducer(); /// adding a new type this time (TypeB). restoringProducer.initializeDataModel(TypeA.class, TypeB.class); restoringProducer.restore(originalVersion, blobStore); long version = restoringProducer.runIncrementalCycle(iws -> { iws.addOrModify(new TypeA(1, "one", 2)); iws.addOrModify(new TypeA(2, "two", 2)); iws.addOrModify(new TypeB(3, "three")); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(originalVersion); consumer.triggerRefreshTo(version); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 2L); assertTypeA(idx, 2, "two", 2L); /// consumers with established data models don't have visibility into new types. consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(version); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeB", "id"); Assert.assertFalse(idx.containsDuplicates()); assertTypeB(idx, 3, "three"); } @Test public void canRemoveAndModifyNewTypesFromRestoredState() { HollowProducer genesisProducer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. long originalVersion = genesisProducer.runCycle(state -> { state.add(new TypeA(1, "one", 1)); }); /// now at some point in the future, we will start up and create a new classic producer /// to back the HollowIncrementalProducer. assertRemoveAndModifyNewTypes(originalVersion, createInMemoryIncrementalProducer()); assertRemoveAndModifyNewTypes(originalVersion, createInMemoryIncrementalProducerWithoutIntegrityCheck()); } private void assertRemoveAndModifyNewTypes(long originalVersion, HollowProducer.Incremental restoringProducer) { /// adding a new type this time (TypeB). restoringProducer.initializeDataModel(TypeA.class, TypeB.class); restoringProducer.restore(originalVersion, blobStore); restoringProducer.runIncrementalCycle(iws -> { iws.addOrModify(new TypeA(1, "one", 2)); iws.addOrModify(new TypeA(2, "two", 2)); iws.addOrModify(new TypeB(3, "three")); iws.addOrModify(new TypeB(4, "four")); }); long version2 = restoringProducer.runIncrementalCycle(iws -> { iws.delete(new RecordPrimaryKey("TypeB", new Object[] { 3 })); iws.addOrModify(new TypeB(4, "four!")); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(originalVersion); consumer.triggerRefreshTo(version2); HollowPrimaryKeyIndex idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeA", "id1", "id2"); Assert.assertFalse(idx.containsDuplicates()); assertTypeA(idx, 1, "one", 2L); assertTypeA(idx, 2, "two", 2L); /// consumers with established data models don't have visibility into new types. consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(version2); idx = new HollowPrimaryKeyIndex(consumer.getStateEngine(), "TypeB", "id"); Assert.assertFalse(idx.containsDuplicates()); assertEquals(-1, idx.getMatchingOrdinal(3)); assertTypeB(idx, 4, "four!"); } @Test public void removeOrphanObjectsWithTypeInSnapshot() { HollowProducer.Incremental producer = createInMemoryIncrementalProducer(); producer.runIncrementalCycle(iws -> { iws.addOrModify(new TypeC(1, new TypeD(1, "one"))); }); long nextVersion = producer.runIncrementalCycle(iws -> { TypeD typeD2 = new TypeD(2, "two"); TypeC typeC2 = new TypeC(2, typeD2); iws.addOrModify(typeC2); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(nextVersion); Collection<HollowObject> allHollowObjectsTypeD = getAllHollowObjects(consumer, "TypeD"); List<String> typeDNames = new ArrayList<>(); for (HollowObject hollowObject : allHollowObjectsTypeD) { typeDNames.add(((GenericHollowObject) hollowObject).getObject("value").toString()); } Assert.assertTrue(typeDNames.contains("two")); long finalVersion = producer.runIncrementalCycle(iws -> { TypeD typeD3 = new TypeD(3, "three"); TypeC typeC2 = new TypeC(2, typeD3); iws.addOrModify(typeC2); }); consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(finalVersion); allHollowObjectsTypeD = getAllHollowObjects(consumer, "TypeD"); List<String> finalTypeDNames = new ArrayList<>(); for (HollowObject hollowObject : allHollowObjectsTypeD) { finalTypeDNames.add(((GenericHollowObject) hollowObject).getObject("value").toString()); } Assert.assertFalse(finalTypeDNames.contains("two")); } @Test public void removeOrphanObjectsWithoutTypeInDelta() { HollowProducer.Incremental producer = createInMemoryIncrementalProducer(); producer.initializeDataModel(TypeC.class); producer.runIncrementalCycle(iws -> { iws.addOrModify(new TypeA(1, "one", 1)); }); producer.runIncrementalCycle(iws -> { TypeD typeD2 = new TypeD(2, "two"); TypeC typeC2 = new TypeC(2, typeD2); iws.addOrModify(typeC2); }); long finalVersion = producer.runIncrementalCycle(iws -> { TypeD typeD3 = new TypeD(3, "three"); TypeC typeC2 = new TypeC(2, typeD3); //Modify typeC2 to point to a new TypeD object iws.addOrModify(typeC2); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(finalVersion); Collection<HollowObject> allHollowObjectsTypeD = getAllHollowObjects(consumer, "TypeD"); List<String> finalTypeDNames = new ArrayList<>(); for (HollowObject hollowObject : allHollowObjectsTypeD) { finalTypeDNames.add(((GenericHollowObject) hollowObject).getObject("value").toString()); } Assert.assertFalse(finalTypeDNames.contains("two")); } @Test public void testOutOfScopeWriteStateAccess() { HollowProducer.Incremental producer = createInMemoryIncrementalProducer(); producer.initializeDataModel(TypeC.class); AtomicReference<HollowProducer.Incremental.IncrementalWriteState> ar = new AtomicReference<>(); producer.runIncrementalCycle(iws -> { ar.set(iws); iws.addOrModify(new TypeA(1, "one", 100)); iws.addOrModify(new TypeA(2, "two", 2)); iws.addOrModify(new TypeA(3, "three", 300)); iws.delete(new TypeA(5, "five", 5)); }); try { ar.get().addOrModify(new TypeA(1, "one", 100)); Assert.fail(); } catch (IllegalStateException e) { } try { ar.get().delete(new TypeA(1, "one", 100)); Assert.fail(); } catch (IllegalStateException e) { } try { ar.get().addIfAbsent(new TypeA(1, "one", 100)); Assert.fail(); } catch (IllegalStateException e) { } } @Test public void testIncrementalPopulateListenerSuccess() { HollowProducer.Incremental producer = createInMemoryIncrementalProducer(); producer.initializeDataModel(TypeC.class); class Listener implements IncrementalPopulateListener { long version; @Override public void onIncrementalPopulateStart(long version) { this.version = version; } long removed; long addedOrModified; @Override public void onIncrementalPopulateComplete( Status status, long removed, long addedOrModified, long version, Duration elapsed) { Assert.assertEquals(Status.StatusType.SUCCESS, status.getType()); Assert.assertNull(status.getCause()); Assert.assertEquals(this.version, version); this.removed = removed; this.addedOrModified = addedOrModified; } } Listener l = new Listener(); producer.addListener(l); long version = producer.runIncrementalCycle(iws -> { iws.addOrModify(new TypeA(1, "one", 100)); iws.addOrModify(new TypeA(2, "two", 2)); iws.addOrModify(new TypeA(3, "three", 300)); iws.delete(new TypeA(5, "five", 5)); }); Assert.assertEquals(version, l.version); Assert.assertEquals(1, l.removed); Assert.assertEquals(3, l.addedOrModified); version = producer.runIncrementalCycle(iws -> { iws.addOrModify(new TypeA(1, "one", 1000)); }); Assert.assertEquals(version, l.version); Assert.assertEquals(0, l.removed); Assert.assertEquals(1, l.addedOrModified); } @Test public void testIncrementalPopulateListenerFailure() { HollowProducer.Incremental producer = createInMemoryIncrementalProducer(); producer.initializeDataModel(TypeC.class); class Listener implements IncrementalPopulateListener { @Override public void onIncrementalPopulateStart(long version) { } @Override public void onIncrementalPopulateComplete( Status status, long removed, long addedOrModified, long version, Duration elapsed) { Assert.assertEquals(Status.StatusType.FAIL, status.getType()); Assert.assertNotNull(status.getCause()); } } Listener l = new Listener(); producer.addListener(l); try { producer.runIncrementalCycle(iws -> { iws.addOrModify(new TypeA(1, "one", 100)); iws.addOrModify(new TypeA(2, "two", 2)); iws.addOrModify(new TypeA(3, "three", 300)); iws.delete(new TypeA(5, "five", 5)); throw new RuntimeException("runIncrementalCycle failed"); }); Assert.fail(); } catch (RuntimeException e) { Assert.assertEquals("runIncrementalCycle failed", e.getMessage()); } } private HollowProducer.Incremental createInMemoryIncrementalProducer() { return new HollowProducer.Builder<>() .withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .buildIncremental(); } private HollowProducer.Incremental createInMemoryIncrementalProducerWithoutIntegrityCheck() { return new HollowProducer.Builder<>() .withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .noIntegrityCheck() .buildIncremental(); } private HollowProducer createInMemoryProducer() { return new HollowProducer.Builder<>() .withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); } private long initializeData(HollowProducer.Incremental producer) { return producer.runIncrementalCycle(state -> { state.addOrModify(new TypeA(1, "one", 1)); state.addOrModify(new TypeA(2, "two", 2)); state.addOrModify(new TypeA(3, "three", 3)); state.addOrModify(new TypeA(4, "four", 4)); state.addOrModify(new TypeA(5, "five", 5)); state.addOrModify(new TypeB(1, "1")); state.addOrModify(new TypeB(2, "2")); state.addOrModify(new TypeB(3, "3")); state.addOrModify(new TypeB(4, "4")); }); } private void assertTypeA( HollowPrimaryKeyIndex typeAIdx, int id1, String id2, Long expectedValue) { int ordinal = typeAIdx.getMatchingOrdinal(id1, id2); if (expectedValue == null) { Assert.assertEquals(-1, ordinal); } else { Assert.assertNotEquals(-1, ordinal); GenericHollowObject obj = new GenericHollowObject( typeAIdx.getTypeState(), ordinal); Assert.assertEquals(expectedValue.longValue(), obj.getLong("value")); } } private void assertTypeB( HollowPrimaryKeyIndex typeBIdx, int id1, String expectedValue) { int ordinal = typeBIdx.getMatchingOrdinal(id1); if (expectedValue == null) { Assert.assertEquals(-1, ordinal); } else { Assert.assertNotEquals(-1, ordinal); GenericHollowObject obj = new GenericHollowObject( typeBIdx.getTypeState(), ordinal); Assert.assertEquals(expectedValue, obj.getObject("value") .getString("value")); } } @SuppressWarnings("unused") @HollowPrimaryKey(fields = {"id1", "id2"}) private static class TypeA { int id1; String id2; long value; public TypeA(int id1, String id2, long value) { this.id1 = id1; this.id2 = id2; this.value = value; } } @SuppressWarnings("unused") @HollowPrimaryKey(fields = "id") private static class TypeB { int id; @HollowTypeName(name = "TypeBValue") String value; public TypeB(int id, String value) { this.id = id; this.value = value; } } @SuppressWarnings("unused") @HollowPrimaryKey(fields = "id") private static class TypeC { int id; TypeD typeD; public TypeC(int id, TypeD typeD) { this.id = id; this.typeD = typeD; } } @SuppressWarnings("unused") private static class TypeD { int id; String value; public TypeD(int id, String name) { this.id = id; this.value = name; } } private Collection<HollowObject> getAllHollowObjects(HollowConsumer hollowConsumer, final String type) { final HollowReadStateEngine readStateEngine = hollowConsumer.getStateEngine(); final HollowTypeDataAccess typeDataAccess = readStateEngine.getTypeDataAccess(type); final HollowTypeReadState typeState = typeDataAccess.getTypeState(); return new AllHollowRecordCollection<HollowObject>(typeState) { @Override protected HollowObject getForOrdinal(int ordinal) { return new GenericHollowObject(readStateEngine, type, ordinal); } }; } }
8,825
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/HollowIncrementalProducerMultithreadingTest.java
package com.netflix.hollow.api.producer; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.core.index.HollowPrimaryKeyIndex; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import java.util.Arrays; import java.util.stream.Collectors; import java.util.stream.IntStream; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class HollowIncrementalProducerMultithreadingTest { private static final int ELEMENTS = 20000; private static final double THREADS = 4.0d; private static final int ITERATIONS = 10; private InMemoryBlobStore blobStore; @Before public void setUp() { blobStore = new InMemoryBlobStore(); } @Rule public final ExpectedException exception = ExpectedException.none(); @Test public void updateAndPublishUsingMultithreading() { // run within a loop to increase the likelihood of a race condition to occur for (int iterationCounter = 0; iterationCounter < ITERATIONS; ++iterationCounter) { HollowProducer producer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. initializeData(producer); /// now we'll be incrementally updating the state by mutating individual records HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(producer, THREADS); int[] notModifiedElementIds = IntStream.range(0, ELEMENTS / 2).toArray(); int[] modifiedElementIds = IntStream.range(ELEMENTS / 2, ELEMENTS).toArray(); incrementalProducer.addOrModify(Arrays.stream(modifiedElementIds).mapToObj(i -> new SimpleType(i, i + 1)).collect(Collectors.toList())); /// .runCycle() flushes the changes to a new data state. long versionAfterUpdate = incrementalProducer.runCycle(); /// now we read the changes and assert HollowPrimaryKeyIndex idx = createPrimaryKeyIndex(versionAfterUpdate); Assert.assertFalse(idx.containsDuplicates()); Assert.assertTrue(Arrays.stream(notModifiedElementIds) .boxed() .map(elementId -> getHollowObject(idx, elementId)) .allMatch(obj -> obj.getInt("value") == obj.getInt("id"))); Assert.assertTrue(Arrays.stream(modifiedElementIds) .boxed() .map(elementId -> getHollowObject(idx, elementId)) .allMatch(obj -> obj.getInt("value") != obj.getInt("id"))); } } @Test public void removeAndPublishUsingMultithreading() { // run within a loop to increase the likelihood of a race condition to occur for (int iterationCounter = 0; iterationCounter < ITERATIONS; ++iterationCounter) { HollowProducer producer = createInMemoryProducer(); /// initialize the data -- classic producer creates the first state in the delta chain. initializeData(producer); /// now we'll be incrementally updating the state by mutating individual records HollowIncrementalProducer incrementalProducer = new HollowIncrementalProducer(producer, THREADS); int[] notModifiedElementIds = IntStream.range(0, ELEMENTS / 2).toArray(); int[] deletedElementIds = IntStream.range(ELEMENTS / 2, ELEMENTS).toArray(); incrementalProducer.delete(Arrays.stream(deletedElementIds).mapToObj(i -> new SimpleType(i, i)).collect(Collectors.toList())); /// .runCycle() flushes the changes to a new data state. long versionAfterDelete = incrementalProducer.runCycle(); /// now we read the changes and assert HollowPrimaryKeyIndex idx = createPrimaryKeyIndex(versionAfterDelete); Assert.assertTrue(Arrays.stream(notModifiedElementIds) .boxed() .map(elementId -> getHollowObject(idx, elementId)) .allMatch(obj -> obj.getInt("value") == obj.getInt("id"))); Assert.assertTrue(Arrays.stream(deletedElementIds) .boxed() .map(elementId -> getOrdinal(idx, elementId)) .allMatch(ordinal -> ordinal == -1)); } } private HollowProducer createInMemoryProducer() { return HollowProducer.withPublisher(blobStore).withBlobStager(new HollowInMemoryBlobStager()).build(); } private void initializeData(HollowProducer producer) { producer.runCycle(state -> { for (int i = 0; i < ELEMENTS; ++i) { state.add(new SimpleType(i, i)); } }); } private HollowPrimaryKeyIndex createPrimaryKeyIndex(long version) { HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(version); return new HollowPrimaryKeyIndex(consumer.getStateEngine(), "SimpleType", "id"); } private GenericHollowObject getHollowObject(HollowPrimaryKeyIndex idx, Object... keys) { int ordinal = getOrdinal(idx, keys); return new GenericHollowObject(idx.getTypeState(), ordinal); } private int getOrdinal(HollowPrimaryKeyIndex idx, Object... keys) { return idx.getMatchingOrdinal(keys); } @HollowPrimaryKey(fields = "id") private static class SimpleType { int id; int value; SimpleType(int id, int value) { this.id = id; this.value = value; } } }
8,826
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/metrics/AbstractProducerMetricsListenerTest.java
package com.netflix.hollow.api.producer.metrics; import static org.mockito.Mockito.when; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.Status; import com.netflix.hollow.api.producer.listener.CycleListener; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import java.time.Duration; import java.util.Optional; import java.util.OptionalLong; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class AbstractProducerMetricsListenerTest { private final long TEST_VERSION = 123l; private final long TEST_LAST_CYCLE_NANOS = 100l; private final long TEST_LAST_ANNOUNCEMENT_NANOS = 200l; private final long TEST_DATA_SIZE = 55l; private final com.netflix.hollow.api.producer.Status TEST_STATUS_SUCCESS = new Status(Status.StatusType.SUCCESS, null); private final com.netflix.hollow.api.producer.Status TEST_STATUS_FAIL = new Status(Status.StatusType.FAIL, null); private final Duration TEST_CYCLE_DURATION_MILLIS = Duration.ofMillis(4l); private final long TEST_ANNOUNCEMENT_DURATION_MILLIS = 2l; @Mock private HollowProducer.ReadState mockReadState; @Mock private HollowReadStateEngine mockStateEngine; @Before public void setup() { MockitoAnnotations.initMocks(this); when(mockReadState.getStateEngine()).thenReturn(mockStateEngine); when(mockStateEngine.calcApproxDataSize()).thenReturn(TEST_DATA_SIZE); } @Test public void testCycleSkipWhenNeverBeenPrimaryProducer() { final class TestProducerMetricsListener extends AbstractProducerMetricsListener { @Override public void cycleMetricsReporting(CycleMetrics cycleMetrics) { Assert.assertNotNull(cycleMetrics); Assert.assertEquals(0l, cycleMetrics.getConsecutiveFailures()); Assert.assertEquals(Optional.empty(), cycleMetrics.getIsCycleSuccess()); Assert.assertEquals(OptionalLong.empty(), cycleMetrics.getCycleDurationMillis()); Assert.assertEquals(OptionalLong.empty(), cycleMetrics.getLastCycleSuccessTimeNano()); } } AbstractProducerMetricsListener concreteProducerMetricsListener = new TestProducerMetricsListener(); concreteProducerMetricsListener.onCycleSkip(CycleListener.CycleSkipReason.NOT_PRIMARY_PRODUCER); } @Test public void testCycleSkipWhenPreviouslyPrimaryProducer() { final class TestProducerMetricsListener extends AbstractProducerMetricsListener { @Override public void cycleMetricsReporting(CycleMetrics cycleMetrics) { Assert.assertNotNull(cycleMetrics); Assert.assertEquals(0l, cycleMetrics.getConsecutiveFailures()); Assert.assertEquals(Optional.empty(), cycleMetrics.getIsCycleSuccess()); Assert.assertEquals(OptionalLong.empty(), cycleMetrics.getCycleDurationMillis()); Assert.assertEquals(OptionalLong.of(TEST_LAST_CYCLE_NANOS), cycleMetrics.getLastCycleSuccessTimeNano()); } } AbstractProducerMetricsListener concreteProducerMetricsListener = new TestProducerMetricsListener(); concreteProducerMetricsListener.lastCycleSuccessTimeNanoOptional = OptionalLong.of(TEST_LAST_CYCLE_NANOS); concreteProducerMetricsListener.onCycleSkip(CycleListener.CycleSkipReason.NOT_PRIMARY_PRODUCER); } @Test public void testCycleCompleteWithSuccess() { final class TestProducerMetricsListener extends AbstractProducerMetricsListener { @Override public void cycleMetricsReporting(CycleMetrics cycleMetrics) { Assert.assertNotNull(cycleMetrics); Assert.assertEquals(0l, cycleMetrics.getConsecutiveFailures()); Assert.assertEquals(Optional.of(true), cycleMetrics.getIsCycleSuccess()); Assert.assertEquals(OptionalLong.of(TEST_CYCLE_DURATION_MILLIS.toMillis()), cycleMetrics.getCycleDurationMillis()); Assert.assertNotEquals(OptionalLong.of(TEST_LAST_CYCLE_NANOS), cycleMetrics.getLastCycleSuccessTimeNano()); Assert.assertNotEquals(OptionalLong.empty(), cycleMetrics.getLastCycleSuccessTimeNano()); } } AbstractProducerMetricsListener concreteProducerMetricsListener = new TestProducerMetricsListener(); concreteProducerMetricsListener.lastCycleSuccessTimeNanoOptional = OptionalLong.of(TEST_LAST_CYCLE_NANOS); concreteProducerMetricsListener.onCycleStart(TEST_VERSION); concreteProducerMetricsListener.onCycleComplete(TEST_STATUS_SUCCESS, mockReadState, TEST_VERSION, TEST_CYCLE_DURATION_MILLIS); } @Test public void testCycleCompleteWithFail() { final class TestProducerMetricsListener extends AbstractProducerMetricsListener { @Override public void cycleMetricsReporting(CycleMetrics cycleMetrics) { Assert.assertNotNull(cycleMetrics); Assert.assertEquals(1l, cycleMetrics.getConsecutiveFailures()); Assert.assertEquals(Optional.of(false), cycleMetrics.getIsCycleSuccess()); Assert.assertEquals(OptionalLong.of(TEST_CYCLE_DURATION_MILLIS.toMillis()), cycleMetrics.getCycleDurationMillis()); Assert.assertEquals(OptionalLong.of(TEST_LAST_CYCLE_NANOS), cycleMetrics.getLastCycleSuccessTimeNano()); } } AbstractProducerMetricsListener concreteProducerMetricsListener = new TestProducerMetricsListener(); concreteProducerMetricsListener.lastCycleSuccessTimeNanoOptional = OptionalLong.of(TEST_LAST_CYCLE_NANOS); concreteProducerMetricsListener.onCycleStart(TEST_VERSION); concreteProducerMetricsListener.onCycleComplete(TEST_STATUS_FAIL, mockReadState, TEST_VERSION, TEST_CYCLE_DURATION_MILLIS); } @Test public void testAnnouncementCompleteWithSuccess() { final class TestProducerMetricsListener extends AbstractProducerMetricsListener { @Override public void announcementMetricsReporting(AnnouncementMetrics announcementMetrics) { Assert.assertNotNull(announcementMetrics); Assert.assertEquals(TEST_DATA_SIZE, announcementMetrics.getDataSizeBytes()); Assert.assertEquals(true, announcementMetrics.getIsAnnouncementSuccess()); Assert.assertEquals(TEST_ANNOUNCEMENT_DURATION_MILLIS, announcementMetrics.getAnnouncementDurationMillis()); Assert.assertNotEquals(OptionalLong.of(TEST_LAST_ANNOUNCEMENT_NANOS), announcementMetrics.getLastAnnouncementSuccessTimeNano()); } } AbstractProducerMetricsListener concreteProducerMetricsListener = new TestProducerMetricsListener(); concreteProducerMetricsListener.lastAnnouncementSuccessTimeNanoOptional = OptionalLong.of( TEST_LAST_ANNOUNCEMENT_NANOS); concreteProducerMetricsListener.onAnnouncementStart(TEST_VERSION); concreteProducerMetricsListener.onAnnouncementComplete(TEST_STATUS_SUCCESS, mockReadState, TEST_VERSION, Duration.ofMillis(TEST_ANNOUNCEMENT_DURATION_MILLIS)); } @Test public void testAnnouncementCompleteWithFail() { final class TestProducerMetricsListener extends AbstractProducerMetricsListener { @Override public void announcementMetricsReporting(AnnouncementMetrics announcementMetrics) { Assert.assertNotNull(announcementMetrics); Assert.assertEquals(TEST_DATA_SIZE, announcementMetrics.getDataSizeBytes()); Assert.assertFalse(announcementMetrics.getIsAnnouncementSuccess()); Assert.assertEquals(TEST_ANNOUNCEMENT_DURATION_MILLIS, announcementMetrics.getAnnouncementDurationMillis()); Assert.assertEquals(OptionalLong.of(TEST_LAST_ANNOUNCEMENT_NANOS), announcementMetrics.getLastAnnouncementSuccessTimeNano()); } } AbstractProducerMetricsListener concreteProducerMetricsListener = new TestProducerMetricsListener(); concreteProducerMetricsListener.lastAnnouncementSuccessTimeNanoOptional = OptionalLong.of( TEST_LAST_ANNOUNCEMENT_NANOS); concreteProducerMetricsListener.onAnnouncementStart(TEST_VERSION); concreteProducerMetricsListener.onAnnouncementComplete(TEST_STATUS_FAIL, mockReadState, TEST_VERSION, Duration.ofMillis(TEST_ANNOUNCEMENT_DURATION_MILLIS)); } }
8,827
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/enforcer/BasicSingleProducerEnforcerTest.java
package com.netflix.hollow.api.producer.enforcer; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test; public class BasicSingleProducerEnforcerTest { @Test public void testEnableDisable() { BasicSingleProducerEnforcer se = new BasicSingleProducerEnforcer(); Assert.assertTrue(se.isPrimary()); se.disable(); Assert.assertFalse(se.isPrimary()); se.enable(); Assert.assertTrue(se.isPrimary()); } @Test public void testEnabledDisabledCyle() { BasicSingleProducerEnforcer se = new BasicSingleProducerEnforcer(); Assert.assertTrue(se.isPrimary()); se.onCycleStart(1234L); se.onCycleComplete(null, 10L, TimeUnit.SECONDS); se.disable(); Assert.assertFalse(se.isPrimary()); } @Test public void testMultiCycle() { BasicSingleProducerEnforcer se = new BasicSingleProducerEnforcer(); for (int i = 0; i < 10; i++) { se.enable(); Assert.assertTrue(se.isPrimary()); se.onCycleStart(1234L); se.disable(); Assert.assertTrue(se.isPrimary()); se.onCycleComplete(null, 10L, TimeUnit.SECONDS); Assert.assertFalse(se.isPrimary()); } } @Test public void testTransitions() { BasicSingleProducerEnforcer se = new BasicSingleProducerEnforcer(); Assert.assertTrue(se.isPrimary()); se.onCycleStart(1234L); Assert.assertTrue(se.isPrimary()); se.disable(); Assert.assertTrue(se.isPrimary()); se.onCycleComplete(null, 10L, TimeUnit.SECONDS); Assert.assertFalse(se.isPrimary()); se.enable(); Assert.assertTrue(se.isPrimary()); se.onCycleStart(1235L); Assert.assertTrue(se.isPrimary()); se.disable(); Assert.assertTrue(se.isPrimary()); se.onCycleComplete(null, 10L, TimeUnit.SECONDS); Assert.assertFalse(se.isPrimary()); } }
8,828
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/validation/DuplicateDataDetectionValidatorTests.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.producer.validation; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class DuplicateDataDetectionValidatorTests { private InMemoryBlobStore blobStore; @Before public void setUp() { blobStore = new InMemoryBlobStore(); } @Test public void failTestMissingSchema() { try { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withListener(new DuplicateDataDetectionValidator("FakeType")).build(); producer.runCycle(writeState -> writeState.add("hello")); } catch (ValidationStatusException expected) { Assert.assertEquals(1, expected.getValidationStatus().getResults().size()); Assert.assertTrue(expected.getValidationStatus().getResults().get(0).getMessage() .endsWith("(see initializeDataModel)")); } } }
8,829
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/validation/RecordCountVarianceValidatorTests.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.producer.validation; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.HollowProducer.Populator; import com.netflix.hollow.api.producer.HollowProducer.WriteState; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class RecordCountVarianceValidatorTests { private InMemoryBlobStore blobStore; @Before public void setUp() { blobStore = new InMemoryBlobStore(); } @Test public void failTestTooManyAdded() { try { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withListener(new RecordCountVarianceValidator("TypeWithPrimaryKey", 1f)).build(); producer.runCycle(new Populator() { public void populate(WriteState newState) throws Exception { newState.add(new TypeWithPrimaryKey(1, "Brad Pitt", "klsdjfla;sdjkf")); newState.add(new TypeWithPrimaryKey(1, "Angelina Jolie", "as;dlkfjasd;l")); } }); producer.runCycle(new Populator() { public void populate(WriteState newState) throws Exception { newState.add(new TypeWithPrimaryKey(1, "Brad Pitt", "klsdjfla;sdjkf")); newState.add(new TypeWithPrimaryKey(2, "Angelina Jolie", "as;dlkfjasd;l")); newState.add(new TypeWithPrimaryKey(3, "Angelina Jolie1", "as;dlkfjasd;l")); newState.add(new TypeWithPrimaryKey(4, "Angelina Jolie2", "as;dlkfjasd;l")); newState.add(new TypeWithPrimaryKey(5, "Angelina Jolie3", "as;dlkfjasd;l")); newState.add(new TypeWithPrimaryKey(6, "Angelina Jolie4", "as;dlkfjasd;l")); newState.add(new TypeWithPrimaryKey(7, "Angelina Jolie5", "as;dlkfjasd;l")); } }); Assert.fail(); } catch (ValidationStatusException expected) { Assert.assertEquals(1, expected.getValidationStatus().getResults().size()); //System.out.println("Message:"+expected.getIndividualFailures().get(0).getMessage()); Assert.assertTrue(expected.getValidationStatus().getResults().get(0).getMessage() .startsWith("Record count validation for type")); } } @Test public void failTestTooManyRemoved() { try { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withListener(new RecordCountVarianceValidator("TypeWithPrimaryKey", 1f)).build(); producer.runCycle(new Populator() { public void populate(WriteState newState) throws Exception { newState.add(new TypeWithPrimaryKey(1, "Brad Pitt", "klsdjfla;sdjkf")); newState.add(new TypeWithPrimaryKey(1, "Angelina Jolie", "as;dlkfjasd;l")); } }); producer.runCycle(new Populator() { public void populate(WriteState newState) throws Exception { newState.add(new TypeWithPrimaryKey(1, "Brad Pitt", "klsdjfla;sdjkf")); newState.add(new TypeWithPrimaryKey(1, "Angelina Jolie", "as;dlkfjasd;l")); newState.add(new TypeWithPrimaryKey(1, "Bruce Willis", "as;dlkfjasd;l")); } }); Assert.fail(); } catch (ValidationStatusException expected) { //System.out.println("Message:"+expected.getIndividualFailures().get(0).getMessage()); Assert.assertEquals(1, expected.getValidationStatus().getResults().size()); Assert.assertTrue(expected.getValidationStatus().getResults().get(0).getMessage() .startsWith("Record count validation for type")); } } @Test public void passTestNoMoreChangeThanExpected() { HollowProducer producer = HollowProducer.withPublisher(blobStore).withBlobStager(new HollowInMemoryBlobStager()) .withListener(new RecordCountVarianceValidator("TypeWithPrimaryKey", 50f)).build(); // runCycle(producer, 1); producer.runCycle(new Populator() { public void populate(WriteState newState) throws Exception { newState.add(new TypeWithPrimaryKey(1, "Brad Pitt", "klsdjfla;sdjkf")); newState.add(new TypeWithPrimaryKey(1, "Angelina Jolie", "as;dlkfjasd;l")); } }); producer.runCycle(new Populator() { public void populate(WriteState newState) throws Exception { newState.add(new TypeWithPrimaryKey(1, "Brad Pitt", "klsdjfla;sdjkf")); newState.add(new TypeWithPrimaryKey(2, "Angelina Jolie", "as;dlkfjasd;l")); newState.add(new TypeWithPrimaryKey(7, "Bruce Willis", "as;dlkfjasd;l")); } }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefresh(); Assert.assertEquals(3, consumer.getStateEngine().getTypeState("TypeWithPrimaryKey").getPopulatedOrdinals() .cardinality()); } @Test public void testGetChangePercent() { RecordCountVarianceValidator val = new RecordCountVarianceValidator("someType", 3.0f); Assert.assertTrue((Float.compare(99.99999652463547f, val.getChangePercent(0, 28382664)) == 0)); Assert.assertTrue((Float.compare(99.646645f, val.getChangePercent(1, 283)) == 0)); } @HollowPrimaryKey(fields = {"id", "name"}) static class TypeWithPrimaryKey { int id; String name; String desc; TypeWithPrimaryKey(int id, String name, String desc) { this.id = id; this.name = name; this.desc = desc; } } }
8,830
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/validation/ObjectModificationValidatorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.producer.validation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.netflix.hollow.api.custom.HollowAPI; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import java.util.function.BiPredicate; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Test; import org.mockito.ArgumentCaptor; public class ObjectModificationValidatorTest { @HollowPrimaryKey(fields = {"id", "code"}) private static class TypeA { @SuppressWarnings("unused") private final int id; @SuppressWarnings("unused") private final String code; @SuppressWarnings("unused") private final String data; public TypeA(int id, String code, String data) { this.id = id; this.code = code; this.data = data; } } @Test public void testValidate_onlyAdditions() { BiPredicate<GenericHollowObject, GenericHollowObject> filter = getMockBiPredicate(); when(filter.test(any(GenericHollowObject.class), any(GenericHollowObject.class))).thenReturn(true); ObjectModificationValidator<HollowAPI, GenericHollowObject> validator = createValidator(filter); HollowProducer producer = getProducer(validator); producer.runCycle(writeState -> writeState.add(new TypeA(1, "fo", "bar"))); verify(filter, never()).test( any(GenericHollowObject.class), any(GenericHollowObject.class)); producer.runCycle(writeState -> { writeState.add(new TypeA(1, "fo", "bar")); writeState.add(new TypeA(2, "fo", "baz")); }); verify(filter, never()).test( any(GenericHollowObject.class), any(GenericHollowObject.class)); } @Test public void testValidate_onlyRemovals() { @SuppressWarnings("unchecked") BiPredicate<GenericHollowObject, GenericHollowObject> filter = getMockBiPredicate(); when(filter.test(any(GenericHollowObject.class), any(GenericHollowObject.class))).thenReturn(true); ObjectModificationValidator<HollowAPI, GenericHollowObject> validator = createValidator(filter); HollowProducer producer = getProducer(validator); producer.runCycle(writeState -> { writeState.add(new TypeA(1, "fo", "bar")); writeState.add(new TypeA(2, "fo", "baz")); }); verify(filter, never()).test( any(GenericHollowObject.class), any(GenericHollowObject.class)); producer.runCycle(writeState -> writeState.add(new TypeA(1, "fo", "bar"))); verify(filter, never()).test( any(GenericHollowObject.class), any(GenericHollowObject.class)); } @Test public void testValidate_onlyModifications() { BiPredicate<GenericHollowObject, GenericHollowObject> filter = getMockBiPredicate(); when(filter.test(any(GenericHollowObject.class), any(GenericHollowObject.class))).thenReturn(true); ObjectModificationValidator<HollowAPI, GenericHollowObject> validator = createValidator(filter); HollowProducer producer = getProducer(validator); producer.runCycle(writeState -> { writeState.add(new TypeA(1, "fo", "bar")); writeState.add(new TypeA(2, "fo", "baz")); }); verify(filter, never()).test( any(GenericHollowObject.class), any(GenericHollowObject.class)); producer.runCycle(writeState -> { writeState.add(new TypeA(1, "fo", "baz")); writeState.add(new TypeA(2, "fo", "baz")); }); ArgumentCaptor<GenericHollowObject> beforeCaptor = ArgumentCaptor.forClass(GenericHollowObject.class); ArgumentCaptor<GenericHollowObject> afterCaptor = ArgumentCaptor.forClass(GenericHollowObject.class); verify(filter).test(beforeCaptor.capture(), afterCaptor.capture()); assertEquals("Before value should be correct", "bar", beforeCaptor.getValue().getObject("data").getString("value")); assertEquals("After value should be correct", "baz", afterCaptor.getValue().getObject("data").getString("value")); } @Test public void testValidate_validationFailure() { BiPredicate<GenericHollowObject, GenericHollowObject> filter = (a, b) -> a.getObject("data").getString("value").length() <= b.getObject("data").getString("value").length(); ObjectModificationValidator<HollowAPI, GenericHollowObject> validator = createValidator(filter); HollowProducer producer = getProducer(validator); producer.runCycle(writeState -> writeState.add(new TypeA(1, "fo", "bar"))); try { producer.runCycle(writeState -> writeState.add(new TypeA(1, "fo", "ba"))); fail("Expected validation exception"); } catch (ValidationStatusException e) { // expected } } private static HollowProducer getProducer(ObjectModificationValidator validator) { return HollowProducer.withPublisher(new InMemoryBlobStore()) .withBlobStager(new HollowInMemoryBlobStager()) .withListener(validator) .build(); } @SuppressWarnings("unchecked") private BiPredicate<GenericHollowObject, GenericHollowObject> getMockBiPredicate() { return mock(BiPredicate.class); } private ObjectModificationValidator<HollowAPI, GenericHollowObject> createValidator( BiPredicate<GenericHollowObject, GenericHollowObject> filter) { return new ObjectModificationValidator<>(TypeA.class.getSimpleName(), filter, HollowAPI::new, (api, ordinal) -> new GenericHollowObject(api.getDataAccess(), TypeA.class.getSimpleName(), ordinal)); } }
8,831
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/validation/HollowProducerValidationListenerTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.producer.validation; import com.netflix.hollow.api.producer.AbstractHollowProducerListener; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.HollowProducer.Announcer; import com.netflix.hollow.api.producer.HollowProducer.Builder; import com.netflix.hollow.api.producer.HollowProducer.Publisher; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import java.time.Duration; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowProducerValidationListenerTest { private TestValidationStatusListener validationListener; private TestCycleAndValidationStatusListener cycleAndValidationListener; private Publisher publisher; private Announcer announcer; @Before public void setup() { publisher = new Publisher() { @Override public void publish(HollowProducer.PublishArtifact publishArtifact) { } }; announcer = version -> {}; } @Test public void testValidationListenerOnValidationSuccess() { createHollowProducerAndRunCycle("MovieWithPrimaryKey", true); assertOnValidationStatus(2, true); Assert.assertTrue(validationListener.getVersion() > 0); Assert.assertTrue(cycleAndValidationListener.getVersion() > 0); Assert.assertEquals(cycleAndValidationListener.getCycleVersion(), cycleAndValidationListener.getVersion()); Assert.assertEquals(cycleAndValidationListener.getCycleVersion(), validationListener.getVersion()); } @Test(expected = ValidationStatusException.class) public void testValidationListenerOnFailure() { createHollowProducerAndRunCycle("MovieWithoutPrimaryKey", true); assertOnValidationStatus(2, false); } @Test public void testValidationListenerWithOnlyRecordCountValidator() { createHollowProducerAndRunCycle("MovieWithPrimaryKey", false); assertOnValidationStatus(1, true); // Expecting only record count validator status ValidationResult validatorStatus = validationListener.getStatus().getResults().get(0); Assert.assertNotNull(validatorStatus); // ValidationStatus builds record validator status based toString of RecordCountValidatorStatus for now. Assert.assertEquals(ValidationResultType.PASSED, validatorStatus.getResultType()); Assert.assertNull(validatorStatus.getThrowable()); // Record count validator would have skipped validation because the previous record count is 0 in this test. // But that status for now is only passed as string through toString method of the validator. Assert.assertTrue(validatorStatus.getMessage().contains("MovieWithPrimaryKey")); Assert.assertTrue(validatorStatus.getMessage().contains("Previous record count is 0")); // Check details Assert.assertTrue(validatorStatus.getName().startsWith(RecordCountVarianceValidator.class.getName())); Assert.assertEquals("MovieWithPrimaryKey", validatorStatus.getDetails().get("Typename")); Assert.assertEquals("3.0", validatorStatus.getDetails().get("AllowableVariancePercent")); } private void createHollowProducerAndRunCycle(final String typeName, boolean addPrimaryKeyValidator) { ValidatorListener dupeValidator = new DuplicateDataDetectionValidator(typeName); ValidatorListener countValidator = new RecordCountVarianceValidator(typeName, 3.0f); validationListener = new TestValidationStatusListener(); cycleAndValidationListener = new TestCycleAndValidationStatusListener(); Builder builder = HollowProducer.withPublisher(publisher).withAnnouncer(announcer) .withListener(validationListener) .withListener(cycleAndValidationListener) .withListener(countValidator); if (addPrimaryKeyValidator) { builder = builder.withListener(dupeValidator); } HollowProducer hollowProducer = builder.build(); if (typeName.equals("MovieWithPrimaryKey")) { hollowProducer.initializeDataModel(MovieWithPrimaryKey.class); } else { hollowProducer.initializeDataModel(MovieWithoutPrimaryKey.class); } hollowProducer.runCycle(newState -> { List<String> actors = Arrays.asList("Angelina Jolie", "Brad Pitt"); if (typeName.equals("MovieWithPrimaryKey")) { newState.add(new MovieWithPrimaryKey(123, "someTitle1", actors)); newState.add(new MovieWithPrimaryKey(123, "someTitle1", actors)); } else { newState.add(new MovieWithoutPrimaryKey(123, "someTitle1", actors)); newState.add(new MovieWithoutPrimaryKey(1233, "someTitle2", actors)); } }); } private void assertOnValidationStatus(int size, boolean passed) { ValidationStatus status = validationListener.getStatus(); Assert.assertNotNull( "Stats null indicates HollowValidationFakeListener.onValidationComplete() was not called on runCycle.", status); Assert.assertEquals(size, status.getResults().size()); Assert.assertEquals(passed, status.passed()); } @HollowPrimaryKey(fields = {"id"}) static class MovieWithPrimaryKey extends MovieWithoutPrimaryKey { public MovieWithPrimaryKey(int id, String title, List<String> actors) { super(id, title, actors); } } static class MovieWithoutPrimaryKey { private final int id; private final String title; private final List<String> actors; public MovieWithoutPrimaryKey(int id, String title, List<String> actors) { this.id = id; this.title = title; this.actors = actors; } public int getId() { return id; } public String getTitle() { return title; } public List<String> getActors() { return actors; } } static class TestValidationStatusListener implements ValidationStatusListener { private long version; private ValidationStatus status; @Override public void onValidationStatusStart(long version) { this.version = version; } @Override public void onValidationStatusComplete( ValidationStatus status, long version, Duration elapsed) { this.status = status; } public long getVersion() { return version; } public ValidationStatus getStatus() { return status; } public void reset() { version = -1; status = null; } } static class TestCycleAndValidationStatusListener extends AbstractHollowProducerListener implements ValidationStatusListener { private long cycleVersion; private long version; private ValidationStatus status; @Override public void onCycleStart(long version) { this.cycleVersion = version; } @Override public void onValidationStatusStart(long version) { this.version = version; } @Override public void onValidationStatusComplete( ValidationStatus status, long version, Duration elapsed) { this.status = status; } @Override public void onCycleComplete(ProducerStatus status, long elapsed, TimeUnit unit) { } public long getCycleVersion() { return cycleVersion; } public long getVersion() { return version; } public ValidationStatus getStatus() { return status; } public void reset() { version = -1; status = null; } } }
8,832
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/producer/validation/ProducerValidationTests.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.producer.validation; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import com.netflix.hollow.core.write.objectmapper.HollowTypeName; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; public class ProducerValidationTests { private InMemoryBlobStore blobStore; @Before public void setUp() { blobStore = new InMemoryBlobStore(); } @Test public void duplicateDetectionFailureTest() { duplicateDetectionFailureTest(new DuplicateDataDetectionValidator("TypeWithPrimaryKey")); duplicateDetectionFailureTest( new DuplicateDataDetectionValidator("TypeWithPrimaryKey", new String[] {"id", "name"})); duplicateDetectionFailureTest(new DuplicateDataDetectionValidator(TypeWithPrimaryKey.class)); duplicateDetectionFailureTest(new DuplicateDataDetectionValidator(TypeWithPrimaryKey2.class)); duplicateDetectionFailureTest(null, true); duplicateDetectionFailureTest(new DuplicateDataDetectionValidator(TypeWithPrimaryKey.class), true); } void duplicateDetectionFailureTest(DuplicateDataDetectionValidator v) { duplicateDetectionFailureTest(v, false); } void duplicateDetectionFailureTest(DuplicateDataDetectionValidator v, boolean auto) { HollowProducer.Builder<?> b = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()); if (v != null) { b.withListener(v); } HollowProducer producer = b.build(); if (auto) { producer.initializeDataModel(TypeWithPrimaryKey.class); DuplicateDataDetectionValidator.addValidatorsForSchemaWithPrimaryKey(producer); } try { //runCycle(producer, 1); producer.runCycle(newState -> { newState.add(new TypeWithPrimaryKey(1, "Brad Pitt", "klsdjfla;sdjkf")); newState.add(new TypeWithPrimaryKey(1, "Angelina Jolie", "as;dlkfjasd;l")); newState.add(new TypeWithPrimaryKey(1, "Brad Pitt", "as;dlkfjasd;l")); }); Assert.fail(); } catch (ValidationStatusException expected) { Assert.assertEquals(1, expected.getValidationStatus().getResults().size()); Assert.assertTrue(expected.getValidationStatus().getResults().get(0).getMessage() .startsWith("Duplicate keys found for type TypeWithPrimaryKey")); } } @Test public void duplicateDetectionSuccessTest() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withListener(new DuplicateDataDetectionValidator("TypeWithPrimaryKey")) .build(); //runCycle(producer, 1); producer.runCycle(newState -> { newState.add(new TypeWithPrimaryKey(1, "Brad Pitt", "klsdjfla;sdjkf")); newState.add(new TypeWithPrimaryKey(1, "Angelina Jolie", "as;dlkfjasd;l")); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefresh(); Assert.assertEquals(2, consumer.getStateEngine().getTypeState("TypeWithPrimaryKey").getPopulatedOrdinals() .cardinality()); } @Test public void duplicateDetectionWithRestoreAndNewType() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withListener(new DuplicateDataDetectionValidator("TypeWithPrimaryKey")) .build(); // run an initial cycle to get data in, without Type3WithPrimaryKey long initialVersion = producer.runCycle(newState -> newState.add(new TypeWithPrimaryKey(1, "Foo", "bar"))); producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withListener(new DuplicateDataDetectionValidator("TypeWithPrimaryKey")) .withListener(new DuplicateDataDetectionValidator("TypeWithPrimaryKey3")) .build(); producer.initializeDataModel(TypeWithPrimaryKey.class, TypeWithPrimaryKey3.class); producer.restore(initialVersion, blobStore); producer.runCycle(newState -> newState.add(new TypeWithPrimaryKey3(1, "Bar"))); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefresh(); } @Test public void duplicateDetectionNewType() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withListener(new DuplicateDataDetectionValidator("TypeWithPrimaryKey")) .build(); producer.runCycle(newState -> newState.add(new TypeWithPrimaryKey(1, "Bar", "x"))); producer.addListener(new DuplicateDataDetectionValidator("TypeWithPrimaryKey3")); // this adds the type state for TypeWithPrimarkyKey3 producer.runCycle(newState -> newState.add(new TypeWithPrimaryKey3(1, "Bar"))); } @Test public void validationDetailOrdering() { Map<String, String> expectedDetails = new LinkedHashMap<>(); expectedDetails.put("detail_key1", "detail_val1"); expectedDetails.put("detail_key2", "detail_val2"); expectedDetails.put("detail_key3", "detail_val3"); ValidationResult.ValidationResultBuilder validationResultBuilder = ValidationResult.from("my_validator"); expectedDetails.forEach(validationResultBuilder::detail); ValidationResult result = validationResultBuilder.passed("everything is ok"); Assert.assertEquals(new ArrayList<>(expectedDetails.entrySet()), new ArrayList<>(result.getDetails().entrySet())); } @HollowPrimaryKey(fields = {"id", "name"}) static class TypeWithPrimaryKey { int id; String name; String desc; TypeWithPrimaryKey(int id, String name, String desc) { this.id = id; this.name = name; this.desc = desc; } } @HollowPrimaryKey(fields = {"id", "name"}) @HollowTypeName(name = "TypeWithPrimaryKey") static class TypeWithPrimaryKey2 { int id; String name; String desc; TypeWithPrimaryKey2(int id, String name, String desc) { this.id = id; this.name = name; this.desc = desc; } } @HollowPrimaryKey(fields = {"id"}) static class TypeWithPrimaryKey3 { int id; String name; TypeWithPrimaryKey3(int id, String name) { this.id = id; this.name = name; } } }
8,833
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/objects
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/objects/provider/Util.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.objects.provider; import static java.util.Objects.requireNonNull; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; interface Util { static <T> Supplier<T> memoize(Supplier<T> supplier) { AtomicReference<T> value = new AtomicReference<>(); return () -> { T val = value.get(); if (val == null) val = value.updateAndGet(v -> v == null ? requireNonNull(supplier.get()) : v); return val; }; } }
8,834
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/objects
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/objects/provider/HollowObjectCacheProviderTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.objects.provider; import static com.netflix.hollow.api.objects.provider.Util.memoize; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; import com.netflix.hollow.api.custom.HollowTypeAPI; import com.netflix.hollow.core.read.engine.HollowTypeReadState; import com.netflix.hollow.core.read.engine.PopulatedOrdinalListener; import java.util.function.Supplier; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; public class HollowObjectCacheProviderTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule().silent(); @Mock HollowTypeReadState typeReadState; @Mock HollowTypeAPI typeAPI; @Mock HollowFactory<TypeA> factory; PopulatedOrdinalListener populatedOrdinalListener; Supplier<HollowObjectCacheProvider<TypeA>> subject; @Before public void before() { populatedOrdinalListener = new PopulatedOrdinalListener(); when(typeReadState.getTypeState()) .thenReturn(typeReadState); when(typeReadState.getListener(PopulatedOrdinalListener.class)) .thenReturn(populatedOrdinalListener); subject = memoize(() -> new HollowObjectCacheProvider<>(typeReadState, typeAPI, factory)); } @Test public void adding_noPreExisting() { TypeA a0 = typeA(0); TypeA a1 = typeA(1); TypeA a2 = typeA(2); notifyAdded(a0, a1, a2); assertEquals(a0, subject.get().getHollowObject(a0.ordinal)); assertEquals(a1, subject.get().getHollowObject(a1.ordinal)); assertEquals(a2, subject.get().getHollowObject(a2.ordinal)); } @Test public void preExisting() { TypeA a0 = typeA(0); TypeA a1 = typeA(1); TypeA a2 = typeA(2); prepopulate(a0, a1, a2); assertEquals(a0, subject.get().getHollowObject(a0.ordinal)); assertEquals(a1, subject.get().getHollowObject(a1.ordinal)); assertEquals(a2, subject.get().getHollowObject(a2.ordinal)); } @Test public void adding_withPreExisting() { TypeA a2 = typeA(2); prepopulate(typeA(0), typeA(1)); notifyAdded(a2); assertEquals(a2, subject.get().getHollowObject(a2.ordinal)); } @Test public void adding_withOrdinalGaps() { TypeA a = typeA(1); notifyAdded(a); assertNull(subject.get().getHollowObject(0)); assertEquals(a, subject.get().getHollowObject(a.ordinal)); } @Test public void notification_afterDetaching() { subject.get().detach(); // FIXME(timt): assert that this shouldn't log an error notifyAdded(typeA(1)); try { // asserting on the absence of side effects, in this case no gaps should have been // filled with null subject.get().getHollowObject(0); fail("expected exception to be thrown"); } catch (IllegalStateException expected) {} } private void prepopulate(TypeA...population) { for (TypeA a : population) populatedOrdinalListener.addedOrdinal(a.ordinal); } private void notifyAdded(TypeA...added) { subject.get().beginUpdate(); for (TypeA a : added) subject.get().addedOrdinal(a.ordinal); subject.get().endUpdate(); } private TypeA typeA(int ordinal) { TypeA a = new TypeA(ordinal); when(factory.newCachedHollowObject(typeReadState, typeAPI, ordinal)) .thenReturn(a); return a; } static class TypeA { final int ordinal; TypeA(int ordinal) { this.ordinal = ordinal; } } }
8,835
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/objects
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/objects/delegate/HollowMapCachedDelegateTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.objects.delegate; import com.netflix.hollow.api.objects.HollowMap; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.map.HollowMapTypeReadState; import com.netflix.hollow.core.schema.HollowMapSchema; import com.netflix.hollow.core.write.HollowMapTypeWriteState; import com.netflix.hollow.core.write.HollowMapWriteRecord; import org.junit.Assert; import org.junit.Test; public class HollowMapCachedDelegateTest extends AbstractStateEngineTest { @Test public void testGetOnEmptyMap() throws Exception { addRecord(); addRecord(10, 20); roundTripSnapshot(); HollowMapCachedDelegate<Integer, Integer> delegate = new HollowMapCachedDelegate<Integer, Integer>((HollowMapTypeReadState)readStateEngine.getTypeState("TestMap"), 0); HollowMap<Integer, Integer> map = new HollowMap<Integer, Integer>(delegate, 0) { public Integer instantiateKey(int keyOrdinal) { return keyOrdinal; } public Integer instantiateValue(int valueOrdinal) { return valueOrdinal; } public boolean equalsKey(int keyOrdinal, Object testObject) { return keyOrdinal == (Integer)testObject; } public boolean equalsValue(int valueOrdinal, Object testObject) { return valueOrdinal == (Integer)testObject; } }; Assert.assertNull(delegate.get(map, 0, 10)); } private void addRecord(int... ordinals) { HollowMapWriteRecord rec = new HollowMapWriteRecord(); for(int i=0;i<ordinals.length;i+=2) { rec.addEntry(ordinals[i], ordinals[i+1]); } writeStateEngine.add("TestMap", rec); } @Override protected void initializeTypeStates() { HollowMapTypeWriteState writeState = new HollowMapTypeWriteState(new HollowMapSchema("TestMap", "TestKey", "TestValue")); writeStateEngine.addTypeState(writeState); } }
8,836
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/codegen/AbstractHollowAPIGeneratorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.api.codegen; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import com.netflix.hollow.core.write.objectmapper.HollowTypeName; import java.io.File; import java.io.IOException; import java.lang.annotation.Annotation; import java.net.URL; import java.net.URLClassLoader; import java.util.function.UnaryOperator; import org.junit.After; public class AbstractHollowAPIGeneratorTest { private String tmpFolder = System.getProperty("java.io.tmpdir"); protected String sourceFolder = String.format("%s/src", tmpFolder); protected String clazzFolder = String.format("%s/classes", tmpFolder); void runGenerator(String apiClassName, String packageName, Class<?> clazz, UnaryOperator<HollowAPIGenerator.Builder> generatorCustomizer) throws Exception { System.out.println(String.format("Folders (%s) : \n\tsource=%s \n\tclasses=%s", getClass().getSimpleName(), sourceFolder, clazzFolder)); // Setup Folders HollowCodeGenerationCompileUtil.cleanupFolder(new File(sourceFolder), null); HollowCodeGenerationCompileUtil.cleanupFolder(new File(clazzFolder), null); // Run Generator HollowAPIGenerator generator = generatorCustomizer.apply(new HollowAPIGenerator.Builder()) .withDataModel(clazz).withAPIClassname(apiClassName).withPackageName(packageName) .withDestination(sourceFolder).build(); generator.generateSourceFiles(); // Compile to validate generated files HollowCodeGenerationCompileUtil.compileSrcFiles(sourceFolder, clazzFolder); } protected void assertNonEmptyFileExists(String relativePath) throws IOException { if (relativePath.startsWith("/")) { throw new IllegalArgumentException("Relative paths should not start with /"); } File f = new File(sourceFolder + "/" + relativePath); assertTrue("File at " + relativePath + " should exist", f.exists() && f.length() > 0L); } void assertClassHasHollowTypeName(String clazz, String typeName) throws IOException, ClassNotFoundException { ClassLoader cl = new URLClassLoader(new URL[]{new File(clazzFolder).toURI().toURL()}); Class cls = cl.loadClass(clazz); Annotation annotation = cls.getAnnotation(HollowTypeName.class); assertNotNull(annotation); assertEquals(typeName, ((HollowTypeName) annotation).name()); } void assertFileDoesNotExist(String relativePath) { if (relativePath.startsWith("/")) { throw new IllegalArgumentException("Relative paths should not start with /"); } assertFalse("File should not exist at " + relativePath, new File(sourceFolder + "/" + relativePath).exists()); } @After public void cleanup() { HollowCodeGenerationCompileUtil.cleanupFolder(new File(sourceFolder), null); HollowCodeGenerationCompileUtil.cleanupFolder(new File(clazzFolder), null); } }
8,837
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/codegen/HollowCodeGenerationCompileUtil.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.api.codegen; import edu.umd.cs.findbugs.FindBugs2; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.tools.JavaCompiler; import javax.tools.ToolProvider; public class HollowCodeGenerationCompileUtil { private static final String FILENAME_FINDBUGS = "findbugs.xml"; private static final String PROPERTY_CLASSPATH = "java.class.path"; /** * Compiles java source files in the provided source directory, to the provided class directory. * This also runs findbugs on the compiled classes, throwing an exception if findbugs fails. */ public static void compileSrcFiles(String sourceDirPath, String classDirPath) throws Exception { List<String> srcFiles = new ArrayList<>(); addAllJavaFiles(new File(sourceDirPath), srcFiles); File classDir = new File(classDirPath); classDir.mkdir(); List<String> argList = new ArrayList<>(); argList.add("-d"); argList.add(classDir.getAbsolutePath()); argList.add("-classpath"); argList.add(System.getProperty(PROPERTY_CLASSPATH) + System.getProperty("path.separator") + classDirPath); argList.addAll(srcFiles); // argList.toArray() for large size had trouble String[] args = new String[argList.size()]; for (int i = 0; i < argList.size(); i++) { args[i] = argList.get(i); } JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); int err = compiler.run(null, System.out, System.out, args); if (err != 0) throw new RuntimeException("compiler errors, see system.out"); runFindbugs(classDir); } /** * Run findbugs on the provided directory. If findbugs fails, the first found bug is printed out as xml. */ private static void runFindbugs(File classDir) throws Exception { ClassLoader classLoader = HollowCodeGenerationCompileUtil.class.getClassLoader(); FindBugs2.main( new String[]{"-auxclasspath", System.getProperty(PROPERTY_CLASSPATH), "-output", classLoader.getResource("").getFile() + FILENAME_FINDBUGS, "-exclude", classLoader.getResource("findbugs_exclude.xml").getFile(), classDir.getAbsolutePath()}); BufferedReader reader = new BufferedReader(new InputStreamReader(classLoader.getResourceAsStream(FILENAME_FINDBUGS))); String line = ""; String foundBug = null; while ((line = reader.readLine()) != null) { // poor man's xml parser if (line.contains("<BugInstance")) { foundBug = line; } else if (foundBug != null) { foundBug += "\n" + line; } if (line.contains("</BugInstance>")) { throw new Exception("Findbugs found an error:\n" + foundBug); } } } private static void addAllJavaFiles(File folder, List<String> result) throws IOException { for (File f : folder.listFiles()) { if (f.isDirectory()) { addAllJavaFiles(f, result); } else if (f.getName().endsWith(".java")) { result.add(f.toString()); System.out.println("Java file: " + f.getName()); System.out.println("------------------------------\n"); Path path = f.toPath(); Files.copy(path, System.out); System.out.println("\n------------------------------\n"); } } } /** * Cleanup specified folder based on file older than specified timestamp * * @param folder - folder to be cleaned up * @param timestamp - specify timestamp to cleanup older files */ public static void cleanupFolder(File folder, Long timestamp) { System.out.println("Cleaning up folder: " + folder.getAbsolutePath()); if (folder.exists()) { for (File file : folder.listFiles()) { if (file.isDirectory()) { cleanupFolder(file, timestamp); file.delete(); } else if (timestamp == null || (timestamp.longValue() - file.lastModified() >= 5000)) { // cleanup file if it is older than specified timestamp with some buffer time System.out.println(String.format("\t deleting file: %s, lastModified=%s", file.getName(), new Date(file.lastModified()))); file.delete(); } } folder.delete(); } } }
8,838
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/codegen/HollowPackageErgonomicsAPIGeneratorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.api.codegen; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.UnaryOperator; import org.junit.Test; public class HollowPackageErgonomicsAPIGeneratorTest extends AbstractHollowAPIGeneratorTest { private static final String API_CLASS_NAME = "PackageErgoTestAPI"; private static final UnaryOperator<HollowAPIGenerator.Builder> customizeBuilder = builder -> builder.withErgonomicShortcuts().withPackageGrouping(); @Test public void test() throws Exception { runGenerator(API_CLASS_NAME, "codegen.subpackage.grouping", Movie.class, customizeBuilder); } @Test public void testDefaultPackage() throws Exception { runGenerator(API_CLASS_NAME, "", Movie.class, b -> b); } @SuppressWarnings("unused") @HollowPrimaryKey(fields = { "id" }) static class Movie { int id; // Collections List<Actor> actors; Map<String, Boolean> map; Set<Long> rankings; // Native Types Integer i; Long l; Boolean b; Float f; Double d; String s; } @SuppressWarnings("unused") static class Actor { String name; Role role; } @SuppressWarnings("unused") static class Role { Integer id; String name; } }
8,839
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/codegen/HollowPrimitiveTypesAPIGeneratorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.api.codegen; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Test; public class HollowPrimitiveTypesAPIGeneratorTest extends AbstractHollowAPIGeneratorTest { @Test public void test() throws Exception { String apiClassName = "PrimitiveTypeTestAPI"; String packageName = "codegen.primitive.types"; runGenerator(apiClassName, packageName, Movie.class, builder -> builder .withErgonomicShortcuts().withPackageGrouping().withHollowPrimitiveTypes(true)); } @SuppressWarnings("unused") @HollowPrimaryKey(fields = { "id" }) static class Movie { int id; // Collections List<Actor> actors; Map<String, Boolean> map; Set<Long> rankings; // Native Types Integer i; Long l; Boolean b; Float f; Double d; String s; } @SuppressWarnings("unused") static class Actor { String name; Role role; } @SuppressWarnings("unused") static class Role { Integer id; String name; } }
8,840
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/codegen/HollowPrimaryKeyAPIGeneratorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.api.codegen; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import org.junit.Test; public class HollowPrimaryKeyAPIGeneratorTest extends AbstractHollowAPIGeneratorTest { @Test public void test() throws Exception { String apiClassName = "PrimaryKeyIndexTestAPI"; String packageName = "codegen.primarykey"; runGenerator(apiClassName, packageName, Movie.class, builder -> builder.reservePrimaryKeyIndexForTypeWithPrimaryKey(true)); } @Test public void testWithPostfix() throws Exception { String apiClassName = "PrimaryKeyIndexTestAPI"; String packageName = "codegen.primarykey"; runGenerator(apiClassName, packageName, Movie.class, builder -> builder.withClassPostfix("Generated").withPackageGrouping()); } @HollowPrimaryKey(fields = {"id", "hasSubtitles", "actor", "role.id!", "role.rank"}) static class Movie { int id; Boolean hasSubtitles; Actor actor; Role role; BoxedBoolean b1; BoxedBytes b2; BoxedBytes b3; BoxedChar b4; BoxedChars b5; BoxedString b6; BoxedInt b7; BoxedLong b8; BoxedFloat b9; BoxedDouble b10; Everything everything; } static class Actor { String name; } static class Role { Integer id; Long rank; String name; } @HollowPrimaryKey(fields = {"v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "ref!"}) static class Everything { boolean v1; char v2; byte[] v3; char v4; char[] v5; String v6; int v7; long v8; float v9; double v10; BoxedInt ref; } @HollowPrimaryKey(fields = "v") static class BoxedBoolean { char v; } @HollowPrimaryKey(fields = "v") static class BoxedBytes { byte[] v; } @HollowPrimaryKey(fields = "v") static class BoxedChar { char v; } @HollowPrimaryKey(fields = "v") static class BoxedChars { char[] v; } @HollowPrimaryKey(fields = "v") static class BoxedString { String v; } @HollowPrimaryKey(fields = "v") static class BoxedInt { int v; } @HollowPrimaryKey(fields = "v") static class BoxedLong { long v; } @HollowPrimaryKey(fields = "v") static class BoxedFloat { float v; } @HollowPrimaryKey(fields = "v") static class BoxedDouble { double v; } }
8,841
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/codegen/ScalarFieldCodeGenTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.api.codegen; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Test; public class ScalarFieldCodeGenTest extends AbstractHollowAPIGeneratorTest { @Test public void test() throws Exception { String apiClassName = "ScalarFieldCodeGenAPI"; String packageName = "codegen.scalar.types"; runGenerator(apiClassName, packageName, Movie.class, builder -> builder.withErgonomicShortcuts().withPackageGrouping() .withHollowPrimitiveTypes(true).withRestrictApiToFieldType()); } @SuppressWarnings("unused") @HollowPrimaryKey(fields = { "id" }) private static class Movie { int id; // Collections List<Actor> actors; Map<String, Boolean> map; Set<Long> rankings; Integer intObj; int intPrimitive; Long longObj; long longPrimitive; Boolean boolObj; boolean boolPrimitive; Float floatObj; float floatPrimitive; Double doubleObj; double doublePrimitive; byte bytePrimitive; // -> INT byte[] byteArray; // -> BYTES char[] charArray; // -> STRING String stringType; // -> REFERENCE } @SuppressWarnings("unused") private static class Actor { String name; Role role; } @SuppressWarnings("unused") private static class Role { Integer roleId; String name; } }
8,842
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/codegen/HollowAPIGeneratorTest.java
package com.netflix.hollow.api.codegen; import org.junit.Test; public class HollowAPIGeneratorTest extends AbstractHollowAPIGeneratorTest { @Test public void generatesFileUsingDestinationPath() throws Exception { runGenerator("API", "com.netflix.hollow.example.api.generated", MyClass.class, b -> b); } @Test public void testGenerateWithPostfix() throws Exception { runGenerator("MyClassTestAPI", "codegen.api", MyClass.class, builder -> builder.withClassPostfix("Generated")); assertNonEmptyFileExists("codegen/api/StringGenerated.java"); assertClassHasHollowTypeName("codegen.api.MyClassGenerated", "MyClass"); } @Test public void testGenerateWithPostfixAndPackageGrouping() throws Exception { runGenerator("MyClassTestAPI", "codegen.api", MyClass.class, builder -> builder.withClassPostfix("Generated").withPackageGrouping()); assertNonEmptyFileExists("codegen/api/core/StringGenerated.java"); } @Test public void testGenerateWithPostfixAndPrimitiveTypes() throws Exception { runGenerator("MyClassTestAPI", "codegen.api", MyClass.class, builder -> builder.withClassPostfix("Generated").withPackageGrouping() .withHollowPrimitiveTypes(true)); assertFileDoesNotExist("codegen/api/core/StringGenerated.java"); assertFileDoesNotExist("codegen/api/StringGenerated.java"); } @Test public void testGenerateWithPostfixAndAggressiveSubstitutions() throws Exception { runGenerator("MyClassTestAPI", "codegen.api", MyClass.class, builder -> builder.withClassPostfix("Generated").withPackageGrouping() .withHollowPrimitiveTypes(true).withAggressiveSubstitutions(true)); assertFileDoesNotExist("codegen/api/core/StringGenerated.java"); assertFileDoesNotExist("codegen/api/StringGenerated.java"); } @SuppressWarnings("unused") private static class MyClass { int id; String foo; public MyClass(int id, String foo) { this.id = id; this.foo = foo; } } }
8,843
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/codegen/HollowErgonomicAPIShortcutsTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.codegen; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.objectmapper.HollowInline; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class HollowErgonomicAPIShortcutsTest { @Test public void test() throws IOException { HollowWriteStateEngine writeEngine = new HollowWriteStateEngine(); HollowObjectMapper mapper = new HollowObjectMapper(writeEngine); mapper.initializeTypeState(TypeA.class); HollowErgonomicAPIShortcuts shortcuts = new HollowErgonomicAPIShortcuts(writeEngine); Assert.assertEquals(5, shortcuts.numShortcuts()); Assert.assertArrayEquals(new String[] { "value" }, shortcuts.getShortcut("StringReferenceReference.ref").getPath()); Assert.assertArrayEquals(new String[] { "StringReference" }, shortcuts.getShortcut("StringReferenceReference.ref").getPathTypes()); Assert.assertArrayEquals(new String[] { "value" }, shortcuts.getShortcut("TypeA.a2").getPath()); Assert.assertArrayEquals(new String[] { "StringReference" }, shortcuts.getShortcut("TypeA.a2").getPathTypes()); Assert.assertArrayEquals(new String[] { "value" }, shortcuts.getShortcut("TypeB.b1").getPath()); Assert.assertArrayEquals(new String[] { "StringReference" }, shortcuts.getShortcut("TypeB.b1").getPathTypes()); Assert.assertArrayEquals(new String[] { "ref", "value" }, shortcuts.getShortcut("TypeA.a3").getPath()); Assert.assertArrayEquals(new String[] { "StringReferenceReference", "StringReference" }, shortcuts.getShortcut("TypeA.a3").getPathTypes()); Assert.assertArrayEquals(new String[] { "ref", "value" }, shortcuts.getShortcut("TypeB.b2").getPath()); Assert.assertArrayEquals(new String[] { "StringReferenceReference", "StringReference" }, shortcuts.getShortcut("TypeB.b2").getPathTypes()); Assert.assertEquals(FieldType.STRING, shortcuts.getShortcut("StringReferenceReference.ref").getType()); Assert.assertEquals(FieldType.STRING, shortcuts.getShortcut("TypeA.a2").getType()); Assert.assertEquals(FieldType.STRING, shortcuts.getShortcut("TypeB.b1").getType()); Assert.assertEquals(FieldType.STRING, shortcuts.getShortcut("TypeA.a3").getType()); Assert.assertEquals(FieldType.STRING, shortcuts.getShortcut("TypeB.b2").getType()); } @SuppressWarnings("unused") private static class TypeA { int a1; StringReference a2; StringReferenceReference a3; TypeB a4; } @SuppressWarnings("unused") private static class TypeB { StringReference b1; StringReferenceReference b2; @HollowInline String b3; } @SuppressWarnings("unused") private static class StringReferenceReference { StringReference ref; } private static class StringReference { @HollowInline String value; } }
8,844
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/codegen/HollowMapAPIGeneratorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.api.codegen; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Test; public class HollowMapAPIGeneratorTest extends AbstractHollowAPIGeneratorTest { private static class Weapon { } private static class Minion { } private static class Frank { } private static class Kevin { } @SuppressWarnings("unused") static class Gru { Map<String, Minion> minions; Map<String, List<Frank>> franks; Map<String, List<List<Kevin>>> kevins; Set<Weapon> weapons; } private static final String API_CLASS_NAME = "MapTestAPI"; private static final String PACKAGE_NAME = "codegen.map"; @Test public void test_withClassPostfix() throws Exception { runGenerator(API_CLASS_NAME, PACKAGE_NAME, Gru.class, builder -> builder.withPackageGrouping().withClassPostfix("Generated")); } @Test public void test_withPackageGrouping() throws Exception { runGenerator(API_CLASS_NAME, PACKAGE_NAME, Gru.class, HollowAPIGenerator.Builder::withPackageGrouping); } @Test public void test_withoutPackageGrouping() throws Exception { runGenerator(API_CLASS_NAME, PACKAGE_NAME, Gru.class, b -> b); } }
8,845
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/codegen/HollowDataAccessorAPIGeneratorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.api.codegen; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import org.junit.Test; public class HollowDataAccessorAPIGeneratorTest extends AbstractHollowAPIGeneratorTest { private static final String API_CLASS_NAME = "DataAccessorTestAPI"; private static final String PACKAGE_NAME = "codegen.data.accessor"; @Test public void test() throws Exception { runGenerator(API_CLASS_NAME, PACKAGE_NAME, Movie.class, builder -> builder.withAggressiveSubstitutions(true)); } @Test public void testGenerateWithPostfix() throws Exception { runGenerator(API_CLASS_NAME, PACKAGE_NAME, Movie.class, builder -> builder.withClassPostfix("Generated").withPackageGrouping()); } @HollowPrimaryKey(fields="id") static class Movie { int id; String name; } }
8,846
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/codegen/HollowBooleanFieldErgonomicsAPIGeneratorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.api.codegen; import org.junit.Test; public class HollowBooleanFieldErgonomicsAPIGeneratorTest extends AbstractHollowAPIGeneratorTest { @Test public void test() throws Exception { String apiClassName = "BooleanErgoTestAPI"; String packageName = "codegen.booleanfield.ergo"; runGenerator(apiClassName, packageName, Movie.class, builder -> builder.withBooleanFieldErgonomics(true)); } static class Movie { int id; boolean playable; boolean value; boolean isAction; Boolean hasSubtitles; } }
8,847
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/codegen/ArgumentParserTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.api.codegen; import static org.junit.Assert.assertEquals; import java.util.Arrays; import org.junit.Test; public class ArgumentParserTest { enum Commands { orderCoffee, drinkCoffee, tossCoffee, writeArgumentParserClass; }; @Test(expected = IllegalArgumentException.class) public void test_missingDash() { new ArgumentParser<Commands>(Commands.class, new String[]{"-orderCoffee=f"}); } @Test(expected = IllegalArgumentException.class) public void test_missingValue() { new ArgumentParser<Commands>(Commands.class, new String[]{"--orderCoffee"}); } @Test(expected = IllegalArgumentException.class) public void test_missingArgument() { new ArgumentParser<Commands>(Commands.class, new String[]{"--compileOnFirstTry=f"}); } @Test public void test_noCommands() { assertEquals(Arrays.asList(), new ArgumentParser<Commands>(Commands.class, new String[] {}).getParsedArguments()); } @Test public void test_validCommands() { assertEquals(3, new ArgumentParser<Commands>(Commands.class, new String[] { "--orderCoffee=first", "--drinkCoffee=next", "--writeArgumentParserClass=yay"}).getParsedArguments().size()); assertParsedArgument("--orderCoffee=fi.rst", Commands.orderCoffee, "fi.rst"); assertParsedArgument("--drinkCoffee=ne/x--t", Commands.drinkCoffee, "ne/x--t"); assertParsedArgument("--tossCoffee=with space", Commands.tossCoffee, "with space"); assertParsedArgument("--writeArgumentParserClass=compl_ete", Commands.writeArgumentParserClass, "compl_ete"); } private void assertParsedArgument(String commandLineArg, Commands key, String value) { ArgumentParser<Commands>.ParsedArgument parsed = new ArgumentParser<>(Commands.class, new String[] { commandLineArg}).getParsedArguments().get(0); assertEquals(key, parsed.getKey()); assertEquals(value, parsed.getValue()); } }
8,848
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/codegen
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/codegen/perfapi/HollowPerformanceAPIGeneratorTest.java
package com.netflix.hollow.api.codegen.perfapi; import com.netflix.hollow.api.codegen.AbstractHollowAPIGeneratorTest; import com.netflix.hollow.api.codegen.HollowCodeGenerationCompileUtil; import com.netflix.hollow.core.schema.SimpleHollowDataset; import java.io.File; import org.junit.Test; public class HollowPerformanceAPIGeneratorTest extends AbstractHollowAPIGeneratorTest { @Test public void testGeneratePerformanceApi() throws Exception { runGenerator("API", "com.netflix.hollow.example.api.performance.generated", MyClass.class); } @Test public void testGeneratedFilesArePlacedInPackageDirectory() throws Exception { runGenerator("API", "codegen.api", MyClass.class); assertNonEmptyFileExists("codegen/api/MyClassPerfAPI.java"); assertNonEmptyFileExists("codegen/api/StringPerfAPI.java"); assertNonEmptyFileExists("codegen/api/API.java"); } private void runGenerator(String apiClassName, String packageName, Class<?> clazz) throws Exception { System.out.println(String.format("Folders (%s) : \n\tsource=%s \n\tclasses=%s", getClass().getSimpleName(), sourceFolder, clazzFolder)); // Setup Folders HollowCodeGenerationCompileUtil.cleanupFolder(new File(sourceFolder), null); HollowCodeGenerationCompileUtil.cleanupFolder(new File(clazzFolder), null); // Run generator HollowPerformanceAPIGenerator generator = HollowPerformanceAPIGenerator.newBuilder() .withDestination(sourceFolder) .withPackageName(packageName) .withAPIClassname(apiClassName) .withDataset(SimpleHollowDataset.fromClassDefinitions(clazz)) .build(); generator.generateSourceFiles(); // Compile to validate generated files HollowCodeGenerationCompileUtil.compileSrcFiles(sourceFolder, clazzFolder); } @SuppressWarnings("unused") private static class MyClass { int id; String foo; public MyClass(int id, String foo) { this.id = id; this.foo = foo; } } }
8,849
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/HollowProducerConsumerTests.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.consumer; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.HollowProducer.ReadState; import com.netflix.hollow.api.producer.HollowProducer.VersionMinter; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.api.producer.validation.ValidationResult; import com.netflix.hollow.api.producer.validation.ValidationResultType; import com.netflix.hollow.api.producer.validation.ValidationStatus; import com.netflix.hollow.api.producer.validation.ValidationStatusException; import com.netflix.hollow.api.producer.validation.ValidationStatusListener; import com.netflix.hollow.api.producer.validation.ValidatorListener; import com.netflix.hollow.core.memory.MemoryMode; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.read.filter.TypeFilter; import com.netflix.hollow.test.InMemoryBlobStore; import com.netflix.hollow.tools.compact.HollowCompactor.CompactionConfig; import java.time.Duration; import java.util.BitSet; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowProducerConsumerTests { private InMemoryBlobStore blobStore; private InMemoryAnnouncement announcement; @Before public void setUp() { blobStore = new InMemoryBlobStore(); announcement = new InMemoryAnnouncement(); } @Test public void publishAndLoadASnapshot() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); /// Showing verbose version of `runCycle(producer, 1);` long version = producer.runCycle(state -> state.add(1)); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(version); Assert.assertEquals(version, consumer.getCurrentVersionId()); } @Test public void initializationTraversesDeltasToGetUpToDate() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withNumStatesBetweenSnapshots(2) /// do not produce snapshots for v2 or v3 .build(); long v1 = runCycle(producer, 1); long v2 = runCycle(producer, 2); long v3 = runCycle(producer, 3); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(v3); Assert.assertEquals(v3, consumer.getCurrentVersionId()); Assert.assertEquals(v1, blobStore.retrieveSnapshotBlob(v3).getToVersion()); Assert.assertEquals(v2, blobStore.retrieveDeltaBlob(v1).getToVersion()); Assert.assertEquals(v3, blobStore.retrieveDeltaBlob(v2).getToVersion()); } @Test public void consumerAutomaticallyUpdatesBasedOnAnnouncement() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withAnnouncer(announcement) .withBlobStager(new HollowInMemoryBlobStager()) .build(); long v1 = runCycle(producer, 1); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore) .withAnnouncementWatcher(announcement) .build(); consumer.triggerRefresh(); Assert.assertEquals(v1, consumer.getCurrentVersionId()); long v2 = runCycle(producer, 2); Assert.assertEquals(v2, consumer.getCurrentVersionId()); } @Test public void consumerFollowsReverseDeltas() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withNumStatesBetweenSnapshots(2) /// do not produce snapshot for v2 or v3 .build(); long v1 = runCycle(producer, 1); runCycle(producer, 2); long v3 = runCycle(producer, 3); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(v3); Assert.assertEquals(v3, consumer.getCurrentVersionId()); blobStore.removeSnapshot( v1); // <-- not necessary to cause following of reverse deltas -- just asserting that's what happened. consumer.triggerRefreshTo(v1); Assert.assertEquals(v1, consumer.getCurrentVersionId()); } @Test public void consumerRespondsToPinnedAnnouncement() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withAnnouncer(announcement) .withBlobStager(new HollowInMemoryBlobStager()) .withNumStatesBetweenSnapshots(2) /// do not produce snapshot for v2 or v3 .build(); long v1 = runCycle(producer, 1); runCycle(producer, 2); long v3 = runCycle(producer, 3); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore) .withAnnouncementWatcher(announcement) .build(); consumer.triggerRefresh(); Assert.assertEquals(v3, consumer.getCurrentVersionId()); announcement.pin(v1); Assert.assertEquals(v1, consumer.getCurrentVersionId()); /// another cycle occurs while we're pinned long v4 = runCycle(producer, 4); announcement.unpin(); Assert.assertEquals(v4, consumer.getCurrentVersionId()); } @Test public void consumerFindsLatestPublishedVersionWithoutAnnouncementWatcher() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withAnnouncer(announcement) .withBlobStager(new HollowInMemoryBlobStager()) .build(); long v1 = runCycle(producer, 1); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefresh(); Assert.assertEquals(v1, consumer.getCurrentVersionId()); consumer.triggerRefresh(); Assert.assertEquals(v1, consumer.getCurrentVersionId()); long v2 = runCycle(producer, 2); consumer.triggerRefresh(); Assert.assertEquals(v2, consumer.getCurrentVersionId()); } @Test public void producerRestoresAndProducesDelta() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); long v1 = runCycle(producer, 1); HollowProducer redeployedProducer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); redeployedProducer.initializeDataModel(Integer.class); redeployedProducer.restore(v1, blobStore); long v2 = runCycle(producer, 2); Assert.assertNotNull(blobStore.retrieveDeltaBlob(v1)); Assert.assertEquals(v2, blobStore.retrieveDeltaBlob(v1).getToVersion()); } @Test public void producerUsesCustomSnapshotPublisherExecutor() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withSnapshotPublishExecutor(command -> { /// do not publish snapshots! }) .build(); long v1 = runCycle(producer, 1); long v2 = runCycle(producer, 2); long v3 = runCycle(producer, 3); long v4 = runCycle(producer, 4); /// first cycle always publishes in-band -- does not use the Executor, so we expect a snapshot for v1. Assert.assertEquals(v1, blobStore.retrieveSnapshotBlob(v1).getToVersion()); Assert.assertEquals(v1, blobStore.retrieveSnapshotBlob(v2).getToVersion()); Assert.assertEquals(v1, blobStore.retrieveSnapshotBlob(v3).getToVersion()); Assert.assertEquals(v1, blobStore.retrieveSnapshotBlob(v4).getToVersion()); } @Test public void producerUsesCustomVersionMinter() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withVersionMinter(new VersionMinter() { long counter = 0; public long mint() { return ++counter; } }) .build(); long v1 = runCycle(producer, 1); long v2 = runCycle(producer, 2); long v3 = runCycle(producer, 3); Assert.assertEquals(1, v1); Assert.assertEquals(2, v2); Assert.assertEquals(3, v3); } @Test public void producerValidatesWithFailure() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withListener(new ValidatorListener() { @Override public String getName() { return "Test validator"; } @Override public ValidationResult onValidate(ReadState readState) { return ValidationResult.from(this).failed("Expected to fail!"); } }) .withListener(new ValidationStatusListener() { boolean isStartCalled; @Override public void onValidationStatusStart(long version) { isStartCalled = true; } @Override public void onValidationStatusComplete( ValidationStatus status, long version, Duration elapsed) { Assert.assertTrue(isStartCalled); Assert.assertTrue(status.failed()); Assert.assertEquals(1, status.getResults().size()); ValidationResult r = status.getResults().get(0); Assert.assertEquals("Test validator", r.getName()); Assert.assertEquals("Expected to fail!", r.getMessage()); Assert.assertEquals(ValidationResultType.FAILED, r.getResultType()); } }) .build(); try { runCycle(producer, 1); Assert.fail(); } catch (ValidationStatusException expected) { ValidationStatus status = expected.getValidationStatus(); Assert.assertTrue(status.failed()); Assert.assertEquals(1, status.getResults().size()); ValidationResult r = status.getResults().get(0); Assert.assertEquals("Test validator", r.getName()); Assert.assertEquals("Expected to fail!", r.getMessage()); Assert.assertEquals(ValidationResultType.FAILED, r.getResultType()); } } @Test public void producerValidatesWithError() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withListener(new ValidatorListener() { @Override public String getName() { return "Test validator"; } @Override public ValidationResult onValidate(ReadState readState) { throw new RuntimeException("Expected to fail!"); } }) .withListener(new ValidationStatusListener() { boolean isStartCalled; @Override public void onValidationStatusStart(long version) { isStartCalled = true; } @Override public void onValidationStatusComplete( ValidationStatus status, long version, Duration elapsed) { Assert.assertTrue(isStartCalled); Assert.assertTrue(status.failed()); Assert.assertEquals(1, status.getResults().size()); ValidationResult r = status.getResults().get(0); Assert.assertEquals("Test validator", r.getName()); Assert.assertEquals("Expected to fail!", r.getMessage()); Assert.assertEquals(ValidationResultType.ERROR, r.getResultType()); } }) .build(); try { runCycle(producer, 1); Assert.fail(); } catch (ValidationStatusException expected) { ValidationStatus status = expected.getValidationStatus(); Assert.assertTrue(status.failed()); Assert.assertEquals(1, status.getResults().size()); ValidationResult r = status.getResults().get(0); Assert.assertEquals("Test validator", r.getName()); Assert.assertEquals("Expected to fail!", r.getMessage()); Assert.assertEquals(ValidationResultType.ERROR, r.getResultType()); } } @Test public void producerCanContinueAfterValidationFailureNew() { AtomicInteger counter = new AtomicInteger(); HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withListener(new ValidatorListener() { @Override public String getName() { return "Test validator"; } @Override public ValidationResult onValidate(ReadState readState) { if (counter.incrementAndGet() == 2) { return ValidationResult.from(this).failed("Expected to fail!"); } else { return ValidationResult.from(this).passed("Pass"); } } }) .withListener(new ValidationStatusListener() { @Override public void onValidationStatusStart(long version) { } @Override public void onValidationStatusComplete( ValidationStatus status, long version, Duration elapsed) { if (counter.get() == 2) { Assert.assertTrue(status.failed()); Assert.assertEquals(1, status.getResults().size()); ValidationResult r = status.getResults().get(0); Assert.assertEquals("Test validator", r.getName()); Assert.assertEquals("Expected to fail!", r.getMessage()); Assert.assertEquals(ValidationResultType.FAILED, r.getResultType()); } else { Assert.assertTrue(status.passed()); Assert.assertEquals(1, status.getResults().size()); ValidationResult r = status.getResults().get(0); Assert.assertEquals("Test validator", r.getName()); Assert.assertEquals("Pass", r.getMessage()); Assert.assertEquals(ValidationResultType.PASSED, r.getResultType()); } } }) .build(); runCycle(producer, 1); try { runCycle(producer, 2); Assert.fail(); } catch (ValidationStatusException expected) { ValidationStatus status = expected.getValidationStatus(); Assert.assertTrue(status.failed()); Assert.assertEquals(1, status.getResults().size()); ValidationResult r = status.getResults().get(0); Assert.assertEquals("Test validator", r.getName()); Assert.assertEquals("Expected to fail!", r.getMessage()); Assert.assertEquals(ValidationResultType.FAILED, r.getResultType()); } runCycle(producer, 3); } @Test public void producerCompacts() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); producer.runCycle(state -> { for (int i = 0; i < 10000; i++) { state.add(i); } }); long v2 = producer.runCycle(state -> { for (int i = 10000; i < 20000; i++) { state.add(i); } }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(v2); /// assert that a compaction is now necessary long popOrdinalsLength = consumer.getStateEngine().getTypeState("Integer").getPopulatedOrdinals().length(); Assert.assertEquals(20000, popOrdinalsLength); /// run a compaction cycle long v3 = producer.runCompactionCycle(new CompactionConfig(0, 20)); /// assert that a compaction actually happened consumer.triggerRefreshTo(v3); popOrdinalsLength = consumer.getStateEngine().getTypeState("Integer").getPopulatedOrdinals().length(); Assert.assertEquals(10000, popOrdinalsLength); BitSet foundValues = new BitSet(20000); for (int i = 0; i < popOrdinalsLength; i++) { foundValues.set(((HollowObjectTypeReadState) consumer.getStateEngine().getTypeState("Integer")) .readInt(i, 0)); } for (int i = 10000; i < 20000; i++) { Assert.assertTrue(foundValues.get(i)); } } @Test public void consumerFilteringSupport() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); /// Showing verbose version of `runCycle(producer, 1);` long version = producer.runCycle(state -> state.add(1)); TypeFilter filterConfig = TypeFilter.newTypeFilter() .excludeAll() .include("String") .build(); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore) .withTypeFilter(filterConfig) .build(); consumer.triggerRefreshTo(version); Assert.assertEquals(version, consumer.getCurrentVersionId()); // Filtering is not supported in shared memory mode try { HollowConsumer.withBlobRetriever(blobStore) .withMemoryMode(MemoryMode.SHARED_MEMORY_LAZY) .withTypeFilter(filterConfig) .build(); } catch (UnsupportedOperationException e) { return; } Assert.fail(); // fail if UnsupportedOperationException was not thrown } private long runCycle(HollowProducer producer, final int cycleNumber) { return producer.runCycle(state -> state.add(cycleNumber)); } }
8,850
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/AbstractHollowHashIndexTests.java
package com.netflix.hollow.api.consumer; import com.netflix.hollow.api.consumer.index.AbstractHollowHashIndex; import com.netflix.hollow.api.custom.HollowAPI; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.core.index.HollowHashIndexResult; import com.netflix.hollow.core.read.iterator.EmptyOrdinalIterator; import com.netflix.hollow.core.read.iterator.HollowOrdinalIterator; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class AbstractHollowHashIndexTests { private InMemoryBlobStore blobStore; @Before public void setUp() { blobStore = new InMemoryBlobStore(); } static class TypeHashIndex extends AbstractHollowHashIndex<HollowAPI> { public TypeHashIndex( HollowConsumer consumer, String queryType, String selectFieldPath, String... matchFieldPaths) { super(consumer, false, queryType, selectFieldPath, matchFieldPaths); } public TypeHashIndex( HollowConsumer consumer, boolean isListenToDataRefresh, String queryType, String selectFieldPath, String... matchFieldPaths) { super(consumer, isListenToDataRefresh, queryType, selectFieldPath, matchFieldPaths); } public HollowOrdinalIterator findMatches(Object... keys) { HollowHashIndexResult matches = idx.findMatches(keys); return matches == null ? EmptyOrdinalIterator.INSTANCE : matches.iterator(); } } @Test public void deltaUpdates() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withNumStatesBetweenSnapshots(2) /// do not produce snapshots for v2 or v3 .build(); long v1 = producer.runCycle(ws -> { ws.add(new TypeA(1, 1.1d, new TypeB("one"))); ws.add(new TypeA(1, 1.1d, new TypeB("1"))); ws.add(new TypeA(2, 2.2d, new TypeB("two"), new TypeB("twenty"), new TypeB("two hundred"))); ws.add(new TypeA(3, 3.3d, new TypeB("three"), new TypeB("thirty"), new TypeB("three hundred"))); ws.add(new TypeA(4, 4.4d, new TypeB("four"))); ws.add(new TypeA(4, 4.5d, new TypeB("four"), new TypeB("forty"))); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(v1); TypeHashIndex index = new TypeHashIndex(consumer, true, "TypeA", "", "a1"); assertIteratorContainsAll(index.findMatches(0)); assertIteratorContainsAll(index.findMatches(1), 1, 0); assertIteratorContainsAll(index.findMatches(2), 2); assertIteratorContainsAll(index.findMatches(3), 3); assertIteratorContainsAll(index.findMatches(4), 4, 5); long v2 = producer.runCycle(ws -> { ws.add(new TypeA(1, 1.1d, new TypeB("one"))); ws.add(new TypeA(1, 1.1d, new TypeB("1"))); ws.add(new TypeA(3, 3.3d, new TypeB("three"), new TypeB("thirty"), new TypeB("three hundred"))); ws.add(new TypeA(4, 4.4d, new TypeB("four"), new TypeB("fore"))); ws.add(new TypeA(4, 4.5d, new TypeB("four"), new TypeB("fourfour"))); ws.add(new TypeA(4, 4.5d, new TypeB("four"), new TypeB("forty"))); }); consumer.triggerRefreshTo(v2); // verify the ordinals we get from the index match our new expected ones. assertIteratorContainsAll(index.findMatches(1), 1, 0); assertIteratorContainsAll(index.findMatches(2)); assertIteratorContainsAll(index.findMatches(3), 3); assertIteratorContainsAll(index.findMatches(4), 5, 6, 7); long v3 = producer.runCycle(ws -> { ws.add(new TypeA(1, 1.1d, new TypeB("one"))); ws.add(new TypeA(1, 1.1d, new TypeB("1"))); ws.add(new TypeA(2, 2.2d, new TypeB("two"), new TypeB("twenty"), new TypeB("two hundred"))); ws.add(new TypeA(3, 3.3d, new TypeB("three"), new TypeB("thirty"), new TypeB("three hundred"))); ws.add(new TypeA(4, 4.4d, new TypeB("four"))); ws.add(new TypeA(4, 4.5d, new TypeB("four"), new TypeB("forty"))); }); consumer.triggerRefreshTo(v3); assertIteratorContainsAll(index.findMatches(0)); assertIteratorContainsAll(index.findMatches(1), 1, 0); assertIteratorContainsAll(index.findMatches(2), 2); assertIteratorContainsAll(index.findMatches(3), 3); assertIteratorContainsAll(index.findMatches(4), 4, 5); } @Test public void deltaSnapshotUpdates() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withNumStatesBetweenSnapshots(2) /// do not produce snapshots for v2 or v3 .build(); long v1 = producer.runCycle(ws -> { ws.add(new TypeA(1, 1.1d, new TypeB("one"))); ws.add(new TypeA(1, 1.1d, new TypeB("1"))); ws.add(new TypeA(2, 2.2d, new TypeB("two"), new TypeB("twenty"), new TypeB("two hundred"))); ws.add(new TypeA(3, 3.3d, new TypeB("three"), new TypeB("thirty"), new TypeB("three hundred"))); ws.add(new TypeA(4, 4.4d, new TypeB("four"))); ws.add(new TypeA(4, 4.5d, new TypeB("four"), new TypeB("forty"))); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(v1); TypeHashIndex index = new TypeHashIndex(consumer, true, "TypeA", "", "a1"); assertIteratorContainsAll(index.findMatches(0)); assertIteratorContainsAll(index.findMatches(1), 1, 0); assertIteratorContainsAll(index.findMatches(2), 2); assertIteratorContainsAll(index.findMatches(3), 3); assertIteratorContainsAll(index.findMatches(4), 4, 5); long v2 = producer.runCycle(ws -> { ws.add(new TypeA(1, 1.1d, new TypeB("one"))); ws.add(new TypeA(1, 1.1d, new TypeB("1"))); ws.add(new TypeA(3, 3.3d, new TypeB("three"), new TypeB("thirty"), new TypeB("three hundred"))); ws.add(new TypeA(4, 4.4d, new TypeB("four"), new TypeB("fore"))); ws.add(new TypeA(4, 4.5d, new TypeB("four"), new TypeB("fourfour"))); ws.add(new TypeA(4, 4.5d, new TypeB("four"), new TypeB("forty"))); }); consumer.triggerRefreshTo(v2); // verify the ordinals we get from the index match our new expected ones. assertIteratorContainsAll(index.findMatches(1), 1, 0); assertIteratorContainsAll(index.findMatches(2)); assertIteratorContainsAll(index.findMatches(3), 3); assertIteratorContainsAll(index.findMatches(4), 5, 6, 7); long v3 = producer.runCycle(ws -> { ws.add(new TypeA(1, 1.1d, new TypeB("one"))); ws.add(new TypeA(1, 1.1d, new TypeB("1"))); ws.add(new TypeA(2, 2.2d, new TypeB("two"), new TypeB("twenty"), new TypeB("two hundred"))); ws.add(new TypeA(3, 3.3d, new TypeB("three"), new TypeB("thirty"), new TypeB("three hundred"))); ws.add(new TypeA(4, 4.4d, new TypeB("four"))); ws.add(new TypeA(4, 4.5d, new TypeB("four"), new TypeB("forty"))); }); consumer.triggerRefreshTo(v3); assertIteratorContainsAll(index.findMatches(0)); assertIteratorContainsAll(index.findMatches(1), 1, 0); assertIteratorContainsAll(index.findMatches(2), 2); assertIteratorContainsAll(index.findMatches(3), 3); assertIteratorContainsAll(index.findMatches(4), 4, 5); long v4 = producer.runCycle(ws -> { ws.add(new TypeA(1, 1.1d, new TypeB("one"))); }); consumer.forceDoubleSnapshotNextUpdate(); consumer.triggerRefreshTo(v4); assertIteratorContainsAll(index.findMatches(1), 0); } @Test public void snapshotDeltaUpdates() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withNumStatesBetweenSnapshots(2) /// do not produce snapshots for v2 or v3 .build(); long v1 = producer.runCycle(ws -> { ws.add(new TypeA(1, 1.1d, new TypeB("one"))); ws.add(new TypeA(1, 1.1d, new TypeB("1"))); ws.add(new TypeA(2, 2.2d, new TypeB("two"), new TypeB("twenty"), new TypeB("two hundred"))); ws.add(new TypeA(3, 3.3d, new TypeB("three"), new TypeB("thirty"), new TypeB("three hundred"))); ws.add(new TypeA(4, 4.4d, new TypeB("four"))); ws.add(new TypeA(4, 4.5d, new TypeB("four"), new TypeB("forty"))); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(v1); TypeHashIndex index = new TypeHashIndex(consumer, true, "TypeA", "", "a1"); assertIteratorContainsAll(index.findMatches(0)); assertIteratorContainsAll(index.findMatches(1), 1, 0); assertIteratorContainsAll(index.findMatches(2), 2); assertIteratorContainsAll(index.findMatches(3), 3); assertIteratorContainsAll(index.findMatches(4), 4, 5); long v2 = producer.runCycle(ws -> { ws.add(new TypeA(1, 1.1d, new TypeB("one"))); ws.add(new TypeA(1, 1.1d, new TypeB("1"))); ws.add(new TypeA(3, 3.3d, new TypeB("three"), new TypeB("thirty"), new TypeB("three hundred"))); ws.add(new TypeA(4, 4.4d, new TypeB("four"), new TypeB("fore"))); ws.add(new TypeA(4, 4.5d, new TypeB("four"), new TypeB("fourfour"))); ws.add(new TypeA(4, 4.5d, new TypeB("four"), new TypeB("forty"))); }); consumer.forceDoubleSnapshotNextUpdate(); consumer.triggerRefreshTo(v2); // verify the ordinals we get from the index match our new expected ones. assertIteratorContainsAll(index.findMatches(1), 1, 0); assertIteratorContainsAll(index.findMatches(2)); assertIteratorContainsAll(index.findMatches(3), 3); assertIteratorContainsAll(index.findMatches(4), 5, 6, 7); long v3 = producer.runCycle(ws -> { ws.add(new TypeA(1, 1.1d, new TypeB("one"))); ws.add(new TypeA(1, 1.1d, new TypeB("1"))); ws.add(new TypeA(2, 2.2d, new TypeB("two"), new TypeB("twenty"), new TypeB("two hundred"))); ws.add(new TypeA(3, 3.3d, new TypeB("three"), new TypeB("thirty"), new TypeB("three hundred"))); ws.add(new TypeA(4, 4.4d, new TypeB("four"))); ws.add(new TypeA(4, 4.5d, new TypeB("four"), new TypeB("forty"))); }); consumer.triggerRefreshTo(v3); assertIteratorContainsAll(index.findMatches(0)); assertIteratorContainsAll(index.findMatches(1), 1, 0); assertIteratorContainsAll(index.findMatches(2), 2); assertIteratorContainsAll(index.findMatches(3), 3); assertIteratorContainsAll(index.findMatches(4), 4, 5); } private void assertIteratorContainsAll(HollowOrdinalIterator iter, int... expectedOrdinals) { Set<Integer> ordinalSet = new HashSet<Integer>(); int ordinal = iter.next(); while (ordinal != HollowOrdinalIterator.NO_MORE_ORDINALS) { ordinalSet.add(ordinal); ordinal = iter.next(); } for (int ord : expectedOrdinals) { Assert.assertTrue(ordinalSet.contains(ord)); } Assert.assertEquals(expectedOrdinals.length, ordinalSet.size()); } private static class TypeA { private final int a1; private final double a2; private final List<TypeB> ab; public TypeA(int a1, double a2, TypeB... ab) { this.a1 = a1; this.a2 = a2; this.ab = Arrays.asList(ab); } } private static class TypeB { private final String b1; private final boolean isDuplicate; public TypeB(String b1) { this(b1, false); } public TypeB(String b1, boolean isDuplicate) { this.b1 = b1; this.isDuplicate = isDuplicate; } } }
8,851
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/CustomConsumerBuilderTest.java
package com.netflix.hollow.api.consumer; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import com.netflix.hollow.api.client.HollowAPIFactory; import com.netflix.hollow.api.metrics.HollowConsumerMetrics; import com.netflix.hollow.api.metrics.HollowMetricsCollector; import com.netflix.hollow.core.memory.MemoryMode; import com.netflix.hollow.core.read.filter.HollowFilterConfig; import com.netflix.hollow.core.read.filter.TypeFilter; import com.netflix.hollow.core.util.HollowObjectHashCodeFinder; import java.util.List; import java.util.concurrent.Executor; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Test; // this test doesn't do much beyond making sure that a custom builder will // compile and ensure that HollowConsumer.Builder is parameterized correctly // to allow custom builder methods to be interleaved with base class builder // methods public class CustomConsumerBuilderTest { private InMemoryBlobStore blobStore; @Before public void setUp() { blobStore = new InMemoryBlobStore(); } @Test public void defaultBehavior() { HollowConsumer consumer = new AugmentedBuilder() .withBlobRetriever(blobStore) .build(); Assert.assertNotNull(consumer); assertThat(consumer).isNotInstanceOf(AugmentedConsumer.class); } @Test public void augmentedBehavior_deprecatedConstructor() { HollowConsumer consumer = new AugmentedBuilder() .withBlobRetriever(blobStore) // should be called before custom builder methods .withDeprecatedAugmentation() .build(); assertThat(consumer).isInstanceOf(AugmentedConsumer.class); } @Test public void augmentedBehavior_builderConstructor() { HollowConsumer consumer = new AugmentedBuilder() .withBlobRetriever(blobStore) // should be called before custom builder methods .withAugmentation() .build(); assertThat(consumer).isInstanceOf(AugmentedConsumer.class); } @Test public void augmentedBehavior_breakingTypeFilter() { try { new AugmentedBuilder() .withBlobRetriever(blobStore) .withAugmentation() .withFilterConfig(new HollowFilterConfig(true)) .withTypeFilter(TypeFilter.newTypeFilter().build()) .build(); fail(); } catch (IllegalStateException ex) { assertThat(ex.getMessage()).startsWith("Only one of typeFilter"); } } private static class AugmentedBuilder extends HollowConsumer.Builder<AugmentedBuilder> { enum Augmentation { none, deprecatedConstructor, builderConstructor; } private Augmentation augmentation = Augmentation.none; AugmentedBuilder withDeprecatedAugmentation() { augmentation = Augmentation.deprecatedConstructor; return this; } AugmentedBuilder withAugmentation() { augmentation = Augmentation.builderConstructor; return this; } @Override public AugmentedBuilder withFilterConfig(HollowFilterConfig filterConfig) { /* * this intentionally breaks the migration to TypeFilter so we can test * our guard against the scenario where both filterConfig and typeFilter are set */ this.filterConfig = filterConfig; return this; } @Override public HollowConsumer build() { checkArguments(); HollowConsumer consumer; switch (augmentation) { case none: consumer = super.build(); break; case deprecatedConstructor: consumer = new AugmentedConsumer( blobRetriever, announcementWatcher, refreshListeners, apiFactory, filterConfig, objectLongevityConfig, objectLongevityDetector, doubleSnapshotConfig, hashCodeFinder, refreshExecutor, memoryMode, metricsCollector ); break; case builderConstructor: consumer = new AugmentedConsumer(this); break; default: throw new IllegalStateException(); } return consumer; } } private static class AugmentedConsumer extends HollowConsumer { AugmentedConsumer( HollowConsumer.BlobRetriever blobRetriever, HollowConsumer.AnnouncementWatcher announcementWatcher, List<RefreshListener> refreshListeners, HollowAPIFactory apiFactory, HollowFilterConfig filterConfig, ObjectLongevityConfig objectLongevityConfig, ObjectLongevityDetector objectLongevityDetector, DoubleSnapshotConfig doubleSnapshotConfig, HollowObjectHashCodeFinder hashCodeFinder, Executor refreshExecutor, MemoryMode memoryMode, HollowMetricsCollector<HollowConsumerMetrics> metricsCollector ) { super(blobRetriever, announcementWatcher, refreshListeners, apiFactory, filterConfig, objectLongevityConfig, objectLongevityDetector, doubleSnapshotConfig, hashCodeFinder, refreshExecutor, memoryMode, metricsCollector); } AugmentedConsumer(AugmentedBuilder builder) { super(builder); } @Override public String toString() { return "I am augmented"; } } }
8,852
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/LocalBlobStoreTest.java
package com.netflix.hollow.api.consumer; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.ProducerOptionalBlobPartConfig; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Collections; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Test; public class LocalBlobStoreTest { @Test public void testBlobStore() throws Exception { File localDir = createLocalDir(); InMemoryBlobStore bs = new InMemoryBlobStore(); HollowProducer producer = HollowProducer.withPublisher(bs) .withBlobStager(new HollowInMemoryBlobStager()) .build(); long v1 = producer.runCycle(ws -> { ws.add(1); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(bs) .withLocalBlobStore(localDir).build(); consumer.triggerRefreshTo(v1); Assert.assertEquals(v1, consumer.getCurrentVersionId()); assertNSnapshots(1, localDir); long v2 = producer.runCycle(ws -> { ws.add(2); }); consumer = HollowConsumer.withBlobRetriever(bs) .withLocalBlobStore(localDir).build(); consumer.triggerRefreshTo(v2); Assert.assertEquals(v2, consumer.getCurrentVersionId()); assertNSnapshots(2, localDir); assertNDeltas(0, localDir); } @Test public void testBlobStoreOverride() throws Exception { File localDir = createLocalDir(); InMemoryBlobStore bs = new InMemoryBlobStore(Collections.singleton("LONG")); HollowProducer producer = HollowProducer.withPublisher(bs) .withBlobStager(new HollowInMemoryBlobStager(optionalPartConfig())) .build(); long v1 = producer.runCycle(ws -> { ws.add(1); ws.add(1L); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(bs) .withLocalBlobStore(localDir, true).build(); consumer.triggerRefreshTo(v1); Assert.assertEquals(v1, consumer.getCurrentVersionId()); assertNSnapshots(1, localDir); long v2 = producer.runCycle(ws -> { ws.add(2); ws.add(2L); }); consumer = HollowConsumer.withBlobRetriever(bs) .withLocalBlobStore(localDir, true).build(); consumer.triggerRefreshTo(v2); Assert.assertEquals(v2, consumer.getCurrentVersionId()); assertNSnapshots(1, localDir); assertNSnapshots(1, "LONG", localDir); assertNDeltas(1, localDir); assertNDeltas(1, "LONG", localDir); } @Test public void testBlobStoreOverrideOptionalPartNotLoaded() throws Exception { File localDir = createLocalDir(); InMemoryBlobStore bs = new InMemoryBlobStore(Collections.emptySet()); HollowProducer producer = HollowProducer.withPublisher(bs) .withBlobStager(new HollowInMemoryBlobStager(optionalPartConfig())) .build(); long v1 = producer.runCycle(ws -> { ws.add(1); ws.add(1L); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(bs) .withLocalBlobStore(localDir, true).build(); consumer.triggerRefreshTo(v1); Assert.assertEquals(v1, consumer.getCurrentVersionId()); assertNSnapshots(1, localDir); long v2 = producer.runCycle(ws -> { ws.add(2); ws.add(2L); }); consumer = HollowConsumer.withBlobRetriever(bs) .withLocalBlobStore(localDir, true).build(); consumer.triggerRefreshTo(v2); Assert.assertEquals(v2, consumer.getCurrentVersionId()); assertNSnapshots(1, localDir); assertNSnapshots(0, "LONG", localDir); assertNDeltas(1, localDir); assertNDeltas(0, "LONG", localDir); } static ProducerOptionalBlobPartConfig optionalPartConfig() throws IOException { ProducerOptionalBlobPartConfig optionalPartConfig = new ProducerOptionalBlobPartConfig(); optionalPartConfig.addTypesToPart("LONG", "Long"); return optionalPartConfig; } static File createLocalDir() throws IOException { File localDir = Files.createTempDirectory("hollow").toFile(); localDir.deleteOnExit(); return localDir; } static void assertNSnapshots(int n, File localDir) throws IOException { long nSnapshots = Files.list(localDir.toPath()).filter(p -> p.getFileName().toString().startsWith("snapshot-")) .count(); Assert.assertEquals(n, nSnapshots); } static void assertNDeltas(int n, File localDir) throws IOException { long nDeltas = Files.list(localDir.toPath()).filter(p -> p.getFileName().toString().startsWith("delta-")) .count(); Assert.assertEquals(n, nDeltas); } static void assertNSnapshots(int n, String optionalPart, File localDir) throws IOException { long nSnapshots = Files.list(localDir.toPath()).filter(p -> p.getFileName().toString().startsWith("snapshot_" + optionalPart + "-")) .count(); Assert.assertEquals(n, nSnapshots); } static void assertNDeltas(int n, String optionalPart, File localDir) throws IOException { long nDeltas = Files.list(localDir.toPath()).filter(p -> p.getFileName().toString().startsWith("delta_" + optionalPart + "-")) .count(); Assert.assertEquals(n, nDeltas); } }
8,853
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/HollowUpdatePlanTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.consumer; import com.netflix.hollow.api.client.HollowUpdatePlan; import com.netflix.hollow.test.consumer.TestBlob; import org.junit.Assert; import org.junit.Test; public class HollowUpdatePlanTest { @Test public void testIsSnapshot() { HollowUpdatePlan plan = new HollowUpdatePlan(); plan.add(new TestBlob(1)); Assert.assertTrue(plan.isSnapshotPlan()); plan.add(new TestBlob(1, 2)); Assert.assertTrue(plan.isSnapshotPlan()); plan = new HollowUpdatePlan(); Assert.assertFalse(plan.isSnapshotPlan()); plan.add(new TestBlob(1, 2)); Assert.assertFalse(plan.isSnapshotPlan()); } @Test public void testGetSnapshotTransition() { TestBlob snapshotTransition = new TestBlob(1); HollowUpdatePlan plan = new HollowUpdatePlan(); plan.add(snapshotTransition); Assert.assertSame(snapshotTransition, plan.getSnapshotTransition()); plan.add(new TestBlob(1, 2)); Assert.assertSame(snapshotTransition, plan.getSnapshotTransition()); } @Test public void testGetDeltaTransitionsForSnapshotPlan() { TestBlob snapshotTransition = new TestBlob(1); HollowUpdatePlan plan = new HollowUpdatePlan(); plan.add(snapshotTransition); Assert.assertTrue(plan.getDeltaTransitions().isEmpty()); TestBlob delta1 = new TestBlob(1, 2); plan.add(delta1); Assert.assertEquals(1, plan.getDeltaTransitions().size()); TestBlob delta2 = new TestBlob(2, 3); plan.add(delta2); Assert.assertEquals(2, plan.getDeltaTransitions().size()); Assert.assertSame(snapshotTransition, plan.getSnapshotTransition()); Assert.assertSame(delta1, plan.getDeltaTransitions().get(0)); Assert.assertSame(delta2, plan.getDeltaTransitions().get(1)); } @Test public void testGetDeltaTransitionsForDeltaPlan() { HollowUpdatePlan plan = new HollowUpdatePlan(); Assert.assertTrue(plan.getDeltaTransitions().isEmpty()); TestBlob delta1 = new TestBlob(1, 2); plan.add(delta1); Assert.assertEquals(1, plan.getDeltaTransitions().size()); TestBlob delta2 = new TestBlob(2, 3); plan.add(delta2); Assert.assertEquals(2, plan.getDeltaTransitions().size()); Assert.assertNull(plan.getSnapshotTransition()); Assert.assertSame(delta1, plan.getDeltaTransitions().get(0)); Assert.assertSame(delta2, plan.getDeltaTransitions().get(1)); } }
8,854
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/HollowUpdatePlannerTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.consumer; import com.netflix.hollow.api.client.HollowUpdatePlan; import com.netflix.hollow.api.client.HollowUpdatePlanner; import com.netflix.hollow.api.consumer.HollowConsumer.Blob; import com.netflix.hollow.test.consumer.TestBlob; import com.netflix.hollow.test.consumer.TestBlobRetriever; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowUpdatePlannerTest { TestBlobRetriever mockTransitionCreator; HollowUpdatePlanner planner; @Before public void setUp() { mockTransitionCreator = new TestBlobRetriever(); planner = new HollowUpdatePlanner(mockTransitionCreator, new HollowConsumer.DoubleSnapshotConfig() { @Override public int maxDeltasBeforeDoubleSnapshot() { return 3; } @Override public boolean allowDoubleSnapshot() { return true; } }); } @Test public void initiallyIncludesSnapshot() throws Exception { addMockSnapshot(5, 1); addMockDelta(1, 2); addMockDelta(2, 3); addMockDelta(3, 4); addMockDelta(4, 5); addMockDelta(5, 6); HollowUpdatePlan plan = planner.planInitializingUpdate(5); Assert.assertEquals(plan.numTransitions(), 5); assertTransition(plan.getTransition(0), Long.MIN_VALUE, 1); assertTransition(plan.getTransition(1), 1, 2); assertTransition(plan.getTransition(2), 2, 3); assertTransition(plan.getTransition(3), 3, 4); assertTransition(plan.getTransition(4), 4, 5); } @Test public void followsDeltaAfterInstantiated() throws Exception { addMockSnapshot(5, 1); addMockDelta(1, 2); addMockDelta(2, 3); addMockDelta(3, 4); addMockDelta(4, 5); addMockDelta(5, 6); HollowUpdatePlan plan = planner.planUpdate(3, 5, true); Assert.assertEquals(plan.numTransitions(), 2); assertTransition(plan.getTransition(0), 3, 4); assertTransition(plan.getTransition(1), 4, 5); } @Test public void attemptsDoubleSnapshotIfDeltaChainIsOverThreshold() throws Exception { addMockDelta(1, 2); addMockDelta(2, 3); addMockDelta(3, 4); addMockSnapshot(6, 4); addMockDelta(4, 5); addMockDelta(5, 6); HollowUpdatePlan plan = planner.planUpdate(1, 6, true); Assert.assertEquals(plan.numTransitions(), 3); assertTransition(plan.getTransition(0), Long.MIN_VALUE, 4); assertTransition(plan.getTransition(1), 4, 5); assertTransition(plan.getTransition(2), 5, 6); } @Test public void doesNotattemptDoubleSnapshotIfNotAllowed() throws Exception { addMockDelta(1, 2); addMockDelta(2, 3); addMockDelta(3, 4); addMockSnapshot(6, 4); addMockDelta(4, 5); addMockDelta(5, 6); HollowUpdatePlan plan = planner.planUpdate(1, 6, false); Assert.assertEquals(plan.numTransitions(), 3); assertTransition(plan.getTransition(0), 1, 2); assertTransition(plan.getTransition(1), 2, 3); assertTransition(plan.getTransition(2), 3, 4); } @Test public void followsReverseDeltas() throws Exception { addMockReverseDelta(5, 4); addMockReverseDelta(4, 3); HollowUpdatePlan plan = planner.planUpdate(5, 3, true); Assert.assertEquals(plan.numTransitions(), 2); assertTransition(plan.getTransition(0), 5, 4); assertTransition(plan.getTransition(1), 4, 3); } @Test public void followsDoubleSnapshotForLongReverseDeltaChains() throws Exception { addMockReverseDelta(5, 4); addMockReverseDelta(4, 3); addMockReverseDelta(3, 2); addMockReverseDelta(2, 1); addMockSnapshot(1, 0); addMockDelta(0, 1); HollowUpdatePlan plan = planner.planUpdate(5, 1, true); Assert.assertEquals(plan.numTransitions(), 2); assertTransition(plan.getTransition(0), Long.MIN_VALUE, 0); assertTransition(plan.getTransition(1), 0, 1); } @Test public void doesNotFollowDoubleSnapshotForLongReverseDeltaChainIfNotAllowed() throws Exception { addMockReverseDelta(5, 4); addMockReverseDelta(4, 3); addMockReverseDelta(3, 2); addMockReverseDelta(2, 1); addMockSnapshot(1, 0); addMockDelta(0, 1); HollowUpdatePlan plan = planner.planUpdate(5, 1, false); Assert.assertEquals(plan.numTransitions(), 3); assertTransition(plan.getTransition(0), 5, 4); assertTransition(plan.getTransition(1), 4, 3); assertTransition(plan.getTransition(2), 3, 2); } @Test public void deltaChainStopsBeforeDesiredStateIfDesiredStateDoesNotExist() throws Exception { addMockSnapshot(5, 0); addMockDelta(0, 3); addMockDelta(3, 6); HollowUpdatePlan plan = planner.planInitializingUpdate(5); Assert.assertEquals(plan.numTransitions(), 2); assertTransition(plan.getTransition(0), Long.MIN_VALUE, 0); assertTransition(plan.getTransition(1), 0, 3); } @Test public void loadsSnapshotIfDeltaChainCannotReachDesiredStateButSnapshotPlanCan() throws Exception { addMockDelta(0, 1); addMockDelta(1, 2); addMockDelta(2, 3); addMockSnapshot(7, 6); addMockDelta(6, 7); HollowUpdatePlan plan = planner.planUpdate(0, 7, true); Assert.assertEquals(plan.numTransitions(), 2); Assert.assertTrue(plan.isSnapshotPlan()); assertTransition(plan.getSnapshotTransition(), Long.MIN_VALUE, 6); assertTransition(plan.getTransition(1), 6, 7); } @Test public void doesNotPreferSnapshotUnlessItGetsToDesiredState() throws Exception { addMockDelta(0, 1); addMockDelta(1, 2); addMockSnapshot(7, 2); addMockDelta(2, 3); HollowUpdatePlan plan = planner.planUpdate(0, 7, true); Assert.assertEquals(plan.numTransitions(), 3); assertTransition(plan.getTransition(0), 0, 1); assertTransition(plan.getTransition(1), 1, 2); assertTransition(plan.getTransition(2), 2, 3); } @Test public void reverseDeltaChainStopsBeforeDesiredStateIfDesiredStateDoesNotExist() throws Exception { addMockReverseDelta(10, 8); addMockReverseDelta(8, 6); addMockReverseDelta(6, 3); HollowUpdatePlan plan = planner.planUpdate(10, 5, true); Assert.assertEquals(plan.numTransitions(), 3); assertTransition(plan.getTransition(0), 10, 8); assertTransition(plan.getTransition(1), 8, 6); assertTransition(plan.getTransition(2), 6, 3); } @Test public void unavailableDeltaUpdatesToLatest() throws Exception { addMockDelta(1, 2); addMockDelta(2, 3); HollowUpdatePlan plan = planner.planUpdate(1, 5, true); Assert.assertEquals(2, plan.numTransitions()); assertTransition(plan.getTransition(0), 1, 2); assertTransition(plan.getTransition(1), 2, 3); } @Test public void unavailableReverseDeltaAttemptsEarlierSnapshot() throws Exception { addMockReverseDelta(5, 4); addMockSnapshot(3, 1); addMockDelta(1, 2); HollowUpdatePlan plan = planner.planUpdate(5, 3, true); Assert.assertEquals(2, plan.numTransitions()); assertTransition(plan.getTransition(0), Long.MIN_VALUE, 1); assertTransition(plan.getTransition(1), 1, 2); } private void assertTransition(HollowConsumer.Blob transition, long expectedFrom, long expectedTo) { Assert.assertEquals(transition.getFromVersion(), expectedFrom); Assert.assertEquals(transition.getToVersion(), expectedTo); } private void addMockSnapshot(long desiredVersion, long actualVersion) { Blob result = new TestBlob(Long.MIN_VALUE, actualVersion); mockTransitionCreator.addSnapshot(desiredVersion, result); } private void addMockDelta(long fromVersion, long toVersion) { Blob result = new TestBlob(fromVersion, toVersion); mockTransitionCreator.addDelta(fromVersion, result); } private void addMockReverseDelta(long fromVersion, long toVersion) { Blob result = new TestBlob(fromVersion, toVersion); mockTransitionCreator.addReverseDelta(fromVersion, result); } }
8,855
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/HollowRefreshListenerTests.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.consumer; import com.netflix.hollow.api.consumer.HollowConsumer.AbstractRefreshListener; import com.netflix.hollow.api.consumer.HollowConsumer.Blob; import com.netflix.hollow.api.consumer.HollowConsumer.ObjectLongevityConfig; import com.netflix.hollow.api.custom.HollowAPI; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.HollowProducer.Populator; import com.netflix.hollow.api.producer.HollowProducer.WriteState; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import java.util.ArrayList; import java.util.List; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowRefreshListenerTests { private InMemoryBlobStore blobStore; private RecordingRefreshListener listener; private HollowProducer producer; private HollowConsumer consumer; @Before public void setUp() { blobStore = new InMemoryBlobStore(); listener = new RecordingRefreshListener(); producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withNumStatesBetweenSnapshots(Integer.MAX_VALUE) .build(); consumer = HollowConsumer.withBlobRetriever(blobStore) .withRefreshListener(listener) .withObjectLongevityConfig(new ObjectLongevityConfig() { @Override public long usageDetectionPeriodMillis() { return 100L; } @Override public long gracePeriodMillis() { return 100L; } @Override public boolean forceDropData() { return false; } @Override public boolean enableLongLivedObjectSupport() { return true; } @Override public boolean enableExpiredUsageStackTraces() { return false; } @Override public boolean dropDataAutomatically() { return true; } }) .build(); } @Test public void testRemoveDuplicateRefreshListeners() { HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore) .withRefreshListener(listener) .withRefreshListener(listener) .build(); long v1 = runCycle(producer, 1); consumer.triggerRefreshTo(v1+1); Assert.assertEquals(1, listener.cycles); listener.clear(); long v2 = runCycle(producer, 2); consumer.addRefreshListener(listener); consumer.triggerRefreshTo(v2+1); Assert.assertEquals(1, listener.cycles); } @Test public void testCopyRefreshListeners() { List<HollowConsumer.RefreshListener> listeners = new ArrayList<>(); listeners.add(listener); HollowConsumer.Builder<?> b = new HollowConsumer.Builder() { @Override public HollowConsumer build() { return new HollowConsumer(blobRetriever, announcementWatcher, listeners, apiFactory, filterConfig, objectLongevityConfig, objectLongevityDetector, doubleSnapshotConfig, hashCodeFinder, refreshExecutor, memoryMode, metricsCollector); } }; HollowConsumer consumer = b.withBlobRetriever(blobStore).build(); long v1 = runCycle(producer, 1); listeners.clear(); consumer.triggerRefreshTo(v1+1); Assert.assertEquals(1, listener.cycles); } @Test public void testMethodSemanticsOnInitialRefresh() { long v1 = runCycle(producer, 1); long v2 = runCycle(producer, 2); long v3 = runCycle(producer, 3); long v4 = runCycle(producer, 4); long v5 = runCycle(producer, 5); consumer.triggerRefreshTo(v5+1); /// update occurred semantics Assert.assertEquals(1, listener.snapshotUpdateOccurredVersions.size()); Assert.assertEquals(v5, listener.snapshotUpdateOccurredVersions.get(0).longValue()); Assert.assertTrue(listener.deltaUpdateOccurredVersions.isEmpty()); /// applied semantics Assert.assertEquals(1, listener.snapshotAppliedVersions.size()); Assert.assertEquals(v1, listener.snapshotAppliedVersions.get(0).longValue()); Assert.assertEquals(4, listener.deltaAppliedVersions.size()); Assert.assertEquals(v2, listener.deltaAppliedVersions.get(0).longValue()); Assert.assertEquals(v3, listener.deltaAppliedVersions.get(1).longValue()); Assert.assertEquals(v4, listener.deltaAppliedVersions.get(2).longValue()); Assert.assertEquals(v5, listener.deltaAppliedVersions.get(3).longValue()); /// blobs loaded semantics Assert.assertEquals(5, listener.blobsLoadedVersions.size()); Assert.assertEquals(v1, listener.blobsLoadedVersions.get(0).longValue()); Assert.assertEquals(v2, listener.blobsLoadedVersions.get(1).longValue()); Assert.assertEquals(v3, listener.blobsLoadedVersions.get(2).longValue()); Assert.assertEquals(v4, listener.blobsLoadedVersions.get(3).longValue()); Assert.assertEquals(v5, listener.blobsLoadedVersions.get(4).longValue()); Assert.assertEquals(Long.MIN_VALUE, listener.refreshStartCurrentVersion); Assert.assertEquals(v5+1, listener.refreshStartRequestedVersion); Assert.assertEquals(Long.MIN_VALUE, listener.refreshSuccessBeforeVersion); Assert.assertEquals(v5, listener.refreshSuccessAfterVersion); Assert.assertEquals(v5+1, listener.refreshSuccessRequestedVersion); } @Test public void testMethodSemanticsOnSubsequentRefreshes() { long v0 = runCycle(producer, 0); consumer.triggerRefreshTo(v0); listener.clear(); long v1 = runCycle(producer, 1); long v2 = runCycle(producer, 2); long v3 = runCycle(producer, 3); consumer.triggerRefreshTo(v3); /// update occurred semantics Assert.assertEquals(0, listener.snapshotUpdateOccurredVersions.size()); Assert.assertEquals(3, listener.deltaUpdateOccurredVersions.size()); Assert.assertEquals(v1, listener.deltaUpdateOccurredVersions.get(0).longValue()); Assert.assertEquals(v2, listener.deltaUpdateOccurredVersions.get(1).longValue()); Assert.assertEquals(v3, listener.deltaUpdateOccurredVersions.get(2).longValue()); /// applied semantics Assert.assertEquals(0, listener.snapshotAppliedVersions.size()); Assert.assertEquals(3, listener.deltaAppliedVersions.size()); Assert.assertEquals(v1, listener.deltaAppliedVersions.get(0).longValue()); Assert.assertEquals(v2, listener.deltaAppliedVersions.get(1).longValue()); Assert.assertEquals(v3, listener.deltaAppliedVersions.get(2).longValue()); /// blobs loaded semantics Assert.assertEquals(3, listener.blobsLoadedVersions.size()); Assert.assertEquals(v1, listener.blobsLoadedVersions.get(0).longValue()); Assert.assertEquals(v2, listener.blobsLoadedVersions.get(1).longValue()); Assert.assertEquals(v3, listener.blobsLoadedVersions.get(2).longValue()); Assert.assertEquals(v0, listener.refreshStartCurrentVersion); Assert.assertEquals(v3, listener.refreshStartRequestedVersion); Assert.assertEquals(v0, listener.refreshSuccessBeforeVersion); Assert.assertEquals(v3, listener.refreshSuccessAfterVersion); Assert.assertEquals(v3, listener.refreshSuccessRequestedVersion); } @Test public void testObjectLongevityOnInitialUpdateCallbacks() { runCycle(producer, 1); runCycle(producer, 2); runCycle(producer, 3); runCycle(producer, 4); long v5 = runCycle(producer, 5); final List<GenericHollowObject> snapshotOrdinal0Objects = new ArrayList<GenericHollowObject>(); final List<GenericHollowObject> deltaOrdinal0Objects = new ArrayList<GenericHollowObject>(); final List<GenericHollowObject> deltaOrdinal1Objects = new ArrayList<GenericHollowObject>(); HollowConsumer.RefreshListener longevityListener = new AbstractRefreshListener() { public void snapshotApplied(HollowAPI api, HollowReadStateEngine stateEngine, long version) throws Exception { snapshotOrdinal0Objects.add(new GenericHollowObject(api.getDataAccess(), "Integer", 0)); } public void deltaApplied(HollowAPI api, HollowReadStateEngine stateEngine, long version) throws Exception { deltaOrdinal0Objects.add(new GenericHollowObject(api.getDataAccess(), "Integer", 0)); deltaOrdinal1Objects.add(new GenericHollowObject(api.getDataAccess(), "Integer", 1)); } }; consumer.addRefreshListener(longevityListener); consumer.triggerRefreshTo(v5); Assert.assertEquals(1, snapshotOrdinal0Objects.get(0).getInt("value")); Assert.assertEquals(2, deltaOrdinal1Objects.get(0).getInt("value")); Assert.assertEquals(3, deltaOrdinal0Objects.get(1).getInt("value")); Assert.assertEquals(4, deltaOrdinal1Objects.get(2).getInt("value")); Assert.assertEquals(5, deltaOrdinal0Objects.get(3).getInt("value")); } @Test public void testAddListenerDuringRefresh() { HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore) .build(); class SecondRefreshListener extends AbstractRefreshListener { int refreshStarted; int refreshSuccessful; @Override public void refreshStarted(long currentVersion, long requestedVersion) { refreshStarted++; } @Override public void refreshSuccessful(long beforeVersion, long afterVersion, long requestedVersion) { refreshSuccessful++; } }; class FirstRefreshListener extends SecondRefreshListener { SecondRefreshListener srl = new SecondRefreshListener(); @Override public void refreshStarted(long currentVersion, long requestedVersion) { super.refreshStarted(currentVersion, requestedVersion); // Add the second listener concurrently during a refresh consumer.addRefreshListener(srl); } }; FirstRefreshListener frl = new FirstRefreshListener(); consumer.addRefreshListener(frl); long v1 = runCycle(producer, 1); consumer.triggerRefreshTo(v1+1); Assert.assertEquals(1, frl.refreshStarted); Assert.assertEquals(1, frl.refreshSuccessful); Assert.assertEquals(0, frl.srl.refreshStarted); Assert.assertEquals(0, frl.srl.refreshSuccessful); long v2 = runCycle(producer, 2); consumer.triggerRefreshTo(v2+1); Assert.assertEquals(2, frl.refreshStarted); Assert.assertEquals(2, frl.refreshSuccessful); Assert.assertEquals(1, frl.srl.refreshStarted); Assert.assertEquals(1, frl.srl.refreshSuccessful); } @Test public void testRemoveListenerDuringRefresh() { HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore) .build(); class SecondRefreshListener extends AbstractRefreshListener { int refreshStarted; int refreshSuccessful; @Override public void refreshStarted(long currentVersion, long requestedVersion) { refreshStarted++; } @Override public void refreshSuccessful(long beforeVersion, long afterVersion, long requestedVersion) { refreshSuccessful++; } }; class FirstRefreshListener extends SecondRefreshListener { SecondRefreshListener srl; FirstRefreshListener(SecondRefreshListener srl) { this.srl = srl; } @Override public void refreshStarted(long currentVersion, long requestedVersion) { super.refreshStarted(currentVersion, requestedVersion); // Remove the second listener concurrently during a refresh consumer.removeRefreshListener(srl); } }; SecondRefreshListener srl = new SecondRefreshListener(); FirstRefreshListener frl = new FirstRefreshListener(srl); consumer.addRefreshListener(frl); consumer.addRefreshListener(srl); long v1 = runCycle(producer, 1); consumer.triggerRefreshTo(v1+1); Assert.assertEquals(1, frl.refreshStarted); Assert.assertEquals(1, frl.refreshSuccessful); Assert.assertEquals(1, frl.srl.refreshStarted); Assert.assertEquals(1, frl.srl.refreshSuccessful); long v2 = runCycle(producer, 2); consumer.triggerRefreshTo(v2+1); Assert.assertEquals(2, frl.refreshStarted); Assert.assertEquals(2, frl.refreshSuccessful); Assert.assertEquals(1, frl.srl.refreshStarted); Assert.assertEquals(1, frl.srl.refreshSuccessful); } private long runCycle(HollowProducer producer, final int cycleNumber) { return producer.runCycle(new Populator() { public void populate(WriteState state) throws Exception { state.add(Integer.valueOf(cycleNumber)); } }); } private class RecordingRefreshListener extends AbstractRefreshListener { long cycles; long refreshStartCurrentVersion; long refreshStartRequestedVersion; long refreshSuccessBeforeVersion; long refreshSuccessAfterVersion; long refreshSuccessRequestedVersion; List<Long> snapshotUpdateOccurredVersions = new ArrayList<Long>(); List<Long> deltaUpdateOccurredVersions = new ArrayList<Long>(); List<Long> blobsLoadedVersions = new ArrayList<Long>(); List<Long> snapshotAppliedVersions = new ArrayList<Long>(); List<Long> deltaAppliedVersions = new ArrayList<Long>(); @Override public void refreshStarted(long currentVersion, long requestedVersion) { cycles++; this.refreshStartCurrentVersion = currentVersion; this.refreshStartRequestedVersion = requestedVersion; } @Override public void snapshotUpdateOccurred(HollowAPI api, HollowReadStateEngine stateEngine, long version) throws Exception { snapshotUpdateOccurredVersions.add(version); } @Override public void deltaUpdateOccurred(HollowAPI api, HollowReadStateEngine stateEngine, long version) throws Exception { deltaUpdateOccurredVersions.add(version); } @Override public void blobLoaded(Blob transition) { blobsLoadedVersions.add(transition.getToVersion()); } @Override public void refreshSuccessful(long beforeVersion, long afterVersion, long requestedVersion) { refreshSuccessBeforeVersion = beforeVersion; refreshSuccessAfterVersion = afterVersion; refreshSuccessRequestedVersion = requestedVersion; } @Override public void refreshFailed(long beforeVersion, long afterVersion, long requestedVersion, Throwable failureCause) { } @Override public void snapshotApplied(HollowAPI api, HollowReadStateEngine stateEngine, long version) throws Exception { snapshotAppliedVersions.add(version); } @Override public void deltaApplied(HollowAPI api, HollowReadStateEngine stateEngine, long version) throws Exception { deltaAppliedVersions.add(version); } public void clear() { cycles = 0; snapshotUpdateOccurredVersions.clear(); deltaUpdateOccurredVersions.clear(); blobsLoadedVersions.clear(); snapshotAppliedVersions.clear(); deltaAppliedVersions.clear(); } } }
8,856
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/AbstractHollowUniqueKeyIndexTests.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.consumer; import com.netflix.hollow.api.consumer.index.AbstractHollowUniqueKeyIndex; import com.netflix.hollow.api.custom.HollowAPI; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class AbstractHollowUniqueKeyIndexTests { private InMemoryBlobStore blobStore; @Before public void setUp() { blobStore = new InMemoryBlobStore(); } static class TypeAPrimaryKeyIndex extends AbstractHollowUniqueKeyIndex<HollowAPI, Object> { public TypeAPrimaryKeyIndex(HollowConsumer consumer, boolean isListenToDataRefresh) { this(consumer, isListenToDataRefresh, ((HollowObjectSchema) consumer.getStateEngine().getNonNullSchema("TypeA")).getPrimaryKey() .getFieldPaths()); } private TypeAPrimaryKeyIndex(HollowConsumer consumer, String... fieldPaths) { this(consumer, false, fieldPaths); } private TypeAPrimaryKeyIndex(HollowConsumer consumer, boolean isListenToDataRefresh, String... fieldPaths) { super(consumer, "TypeA", isListenToDataRefresh, fieldPaths); } public int findMatch(Object... keys) { return idx.getMatchingOrdinal(keys); } public Object[] getRecordKey(int ordinal) { return idx.getRecordKey(ordinal); } } @Test public void deltaUpdates() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withNumStatesBetweenSnapshots(2) /// do not produce snapshots for v2 or v3 .build(); long v1 = producer.runCycle(ws -> { ws.add(new TypeA(1, 1.1d, new TypeB("one"))); ws.add(new TypeA(1, 1.1d, new TypeB("1"))); ws.add(new TypeA(2, 2.2d, new TypeB("two"))); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(v1); TypeAPrimaryKeyIndex indexer = new TypeAPrimaryKeyIndex(consumer, true); int ord1 = indexer.findMatch(1, 1.1d, "1"); int ord0 = indexer.findMatch(1, 1.1d, "one"); int ord2 = indexer.findMatch(2, 2.2d, "two"); Assert.assertEquals(0, ord0); Assert.assertEquals(1, ord1); Assert.assertEquals(2, ord2); assertArrayEquals(indexer.getRecordKey(0), 1, 1.1d, "one"); assertArrayEquals(indexer.getRecordKey(1), 1, 1.1d, "1"); assertArrayEquals(indexer.getRecordKey(2), 2, 2.2d, "two"); long v2 = producer.runCycle(ws -> { ws.add(new TypeA(1, 1.1d, new TypeB("one"))); // mapper.add(new TypeA(1, 1.1d, new TypeB("1"))); ws.add(new TypeA(2, 2.2d, new TypeB("two"))); ws.add(new TypeA(3, 3.3d, new TypeB("three"))); }); consumer.triggerRefreshTo(v2); ord0 = indexer.findMatch(1, 1.1d, "one"); ord1 = indexer.findMatch(1, 1.1d, "1"); ord2 = indexer.findMatch(2, 2.2d, "two"); int ord3 = indexer.findMatch(3, 3.3d, "three"); Assert.assertEquals(0, ord0); Assert.assertEquals(-1, ord1); Assert.assertEquals(2, ord2); Assert.assertEquals(3, ord3); assertArrayEquals(indexer.getRecordKey(0), 1, 1.1d, "one"); assertArrayEquals(indexer.getRecordKey(1), 1, 1.1d, "1"); // it is a ghost record (marked deleted but it is available) assertArrayEquals(indexer.getRecordKey(2), 2, 2.2d, "two"); assertArrayEquals(indexer.getRecordKey(3), 3, 3.3d, "three"); } @Test public void snapshotUpdates() { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .withNumStatesBetweenSnapshots(2) /// do not produce snapshots for v2 or v3 .build(); long v1 = producer.runCycle(ws -> { ws.add(new TypeA(1, 1.1d, new TypeB("one"))); ws.add(new TypeA(1, 1.1d, new TypeB("1"))); ws.add(new TypeA(2, 2.2d, new TypeB("two"))); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore).build(); consumer.triggerRefreshTo(v1); long cv1 = consumer.getCurrentVersionId(); TypeAPrimaryKeyIndex indexer = new TypeAPrimaryKeyIndex(consumer, true); int ord1 = indexer.findMatch(1, 1.1d, "1"); int ord0 = indexer.findMatch(1, 1.1d, "one"); int ord2 = indexer.findMatch(2, 2.2d, "two"); Assert.assertEquals(0, ord0); Assert.assertEquals(1, ord1); Assert.assertEquals(2, ord2); assertArrayEquals(indexer.getRecordKey(0), 1, 1.1d, "one"); assertArrayEquals(indexer.getRecordKey(1), 1, 1.1d, "1"); assertArrayEquals(indexer.getRecordKey(2), 2, 2.2d, "two"); long v2 = producer.runCycle(ws -> { ws.add(new TypeA(1, 1.1d, new TypeB("one"))); // mapper.add(new TypeA(1, 1.1d, new TypeB("1"))); ws.add(new TypeA(2, 2.2d, new TypeB("two"))); ws.add(new TypeA(3, 3.3d, new TypeB("three"))); }); consumer.forceDoubleSnapshotNextUpdate(); consumer.triggerRefreshTo(v2); ord0 = indexer.findMatch(1, 1.1d, "one"); ord1 = indexer.findMatch(1, 1.1d, "1"); ord2 = indexer.findMatch(2, 2.2d, "two"); int ord3 = indexer.findMatch(3, 3.3d, "three"); Assert.assertEquals(0, ord0); Assert.assertEquals(-1, ord1); Assert.assertEquals(2, ord2); Assert.assertEquals(3, ord3); assertArrayEquals(indexer.getRecordKey(0), 1, 1.1d, "one"); // it is a ghost record (marked deleted but it is available) assertArrayEquals(indexer.getRecordKey(1), 1, 1.1d, "1"); assertArrayEquals(indexer.getRecordKey(2), 2, 2.2d, "two"); assertArrayEquals(indexer.getRecordKey(3), 3, 3.3d, "three"); long v3 = producer.runCycle(ws -> { ws.add(new TypeA(1, 1.1d, new TypeB("one"))); ws.add(new TypeA(1, 1.1d, new TypeB("1"))); ws.add(new TypeA(2, 2.2d, new TypeB("two"))); }); consumer.triggerRefreshTo(v3); ord0 = indexer.findMatch(1, 1.1d, "one"); ord1 = indexer.findMatch(1, 1.1d, "1"); ord2 = indexer.findMatch(2, 2.2d, "two"); ord3 = indexer.findMatch(3, 3.3d, "three"); Assert.assertEquals(0, ord0); Assert.assertEquals(1, ord1); Assert.assertEquals(2, ord2); Assert.assertEquals(-1, ord3); assertArrayEquals(indexer.getRecordKey(0), 1, 1.1d, "one"); assertArrayEquals(indexer.getRecordKey(1), 1, 1.1d, "1"); assertArrayEquals(indexer.getRecordKey(2), 2, 2.2d, "two"); // it is a ghost record (marked deleted but it is available) assertArrayEquals(indexer.getRecordKey(3), 3, 3.3d, "three"); } private static void assertArrayEquals(Object[] actual, Object... expected) { Assert.assertArrayEquals(expected, actual); } @HollowPrimaryKey(fields = {"a1", "a2", "ab.b1"}) private static class TypeA { private final int a1; private final double a2; private final TypeB ab; public TypeA(int a1, double a2, TypeB ab) { this.a1 = a1; this.a2 = a2; this.ab = ab; } } private static class TypeB { private final String b1; private final boolean isDuplicate; public TypeB(String b1) { this(b1, false); } public TypeB(String b1, boolean isDuplicate) { this.b1 = b1; this.isDuplicate = isDuplicate; } } }
8,857
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/FocusedShardHoleFillTest.java
package com.netflix.hollow.api.consumer; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.HollowProducer.WriteState; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.core.read.engine.list.HollowListTypeReadState; import com.netflix.hollow.core.read.engine.map.HollowMapTypeReadState; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.read.engine.set.HollowSetTypeReadState; import com.netflix.hollow.core.read.iterator.HollowMapEntryOrdinalIterator; import com.netflix.hollow.core.read.iterator.HollowOrdinalIterator; import com.netflix.hollow.core.write.objectmapper.HollowInline; import com.netflix.hollow.core.write.objectmapper.HollowShardLargeType; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Test; public class FocusedShardHoleFillTest { @Test public void focusChanges() { InMemoryBlobStore blobStore = new InMemoryBlobStore(); HollowProducer producer = HollowProducer.withPublisher(blobStore).withBlobStager(new HollowInMemoryBlobStager()).withFocusHoleFillInFewestShards(true).build(); long v1 = producer.runCycle(state -> { for(int i=1;i<=36;i++) { add(state, "val" + i, i); } }); HollowConsumer consumer = HollowConsumer.newHollowConsumer().withBlobRetriever(blobStore).withSkipTypeShardUpdateWithNoAdditions().build(); consumer.triggerRefreshTo(v1); Assert.assertEquals(4, consumer.getStateEngine().getTypeState("TestRec").numShards()); Assert.assertEquals(4, consumer.getStateEngine().getTypeState("ListOfTestRec").numShards()); Assert.assertEquals(4, consumer.getStateEngine().getTypeState("SetOfTestRec").numShards()); Assert.assertEquals(4, consumer.getStateEngine().getTypeState("MapOfTestRecToTestRec").numShards()); /// remove 4 from S0: 13, 21, 25, 29 /// remove 5 from S1: 6, 14, 18, 26, 30 /// remove 2 from S2: 11, 19 /// remove 1 from S3: 24 Set<Integer> removeSet = new HashSet<>(Arrays.asList(13, 21, 25, 29, 6, 14, 18, 26, 30, 11, 19, 24)); long v2 = producer.runCycle(state -> { for(int i=1;i<=36;i++) { if(!removeSet.contains(i)) add(state, "val" + i, i); } add(state, "newval37", 37); }); consumer.triggerRefreshTo(v2); removeSet.add(5); long v3 = producer.runCycle(state -> { for(int i=1;i<=36;i++) { if(!removeSet.contains(i)) add(state, "val" + i, i); } add(state, "newval37", 37); for(int i=1000;i<1005;i++) { add(state, "bigval"+i, i); } }); consumer.triggerRefreshTo(v3); /// all changes focused in shard 1 assertRecordOrdinal(consumer, 5, "bigval1000", 1000); assertRecordOrdinal(consumer, 13, "bigval1001", 1001); assertRecordOrdinal(consumer, 17, "bigval1002", 1002); assertRecordOrdinal(consumer, 25, "bigval1003", 1003); assertRecordOrdinal(consumer, 29, "bigval1004", 1004); assertRecordOrdinal(consumer, 32, "val33", 33); // shard1 assertRecordOrdinal(consumer, 9, "val10", 10); // shard2 assertRecordOrdinal(consumer, 14, "val15", 15); assertRecordOrdinal(consumer, 11, "val12", 12); long v4 = producer.runCycle(state -> { for(int i=1;i<=36;i++) { if(!removeSet.contains(i)) add(state, "val" + i, i); } add(state, "newval37", 37); for(int i=1000;i<1010;i++) { add(state, "bigval"+i, i); } }); consumer.triggerRefreshTo(v4); /// all changes focused in shard 0 assertRecordOrdinal(consumer, 4, "bigval1005", 1005); assertRecordOrdinal(consumer, 12, "bigval1006", 1006); assertRecordOrdinal(consumer, 20, "bigval1007", 1007); assertRecordOrdinal(consumer, 24, "bigval1008", 1008); assertRecordOrdinal(consumer, 28, "bigval1009", 1009); assertRecordOrdinal(consumer, 32, "val33", 33); // shard1 assertRecordOrdinal(consumer, 9, "val10", 10); // shard2 assertRecordOrdinal(consumer, 14, "val15", 15); assertRecordOrdinal(consumer, 11, "val12", 12); long v5 = producer.runCycle(state -> { for(int i=1;i<=36;i++) { if(!removeSet.contains(i)) add(state, "val" + i, i); } add(state, "newval37", 37); for(int i=1000;i<1013;i++) { add(state, "bigval"+i, i); } }); consumer.triggerRefreshTo(v5); /// all changes focused in shards 2 and 3 assertRecordOrdinal(consumer, 10, "bigval1010", 1010); assertRecordOrdinal(consumer, 18, "bigval1011", 1011); assertRecordOrdinal(consumer, 23, "bigval1012", 1012); assertRecordOrdinal(consumer, 32, "val33", 33); // shard1 assertRecordOrdinal(consumer, 9, "val10", 10); // shard2 assertRecordOrdinal(consumer, 14, "val15", 15); assertRecordOrdinal(consumer, 11, "val12", 12); consumer.triggerRefreshTo(v1); BitSet ordinals = consumer.getStateEngine().getTypeState("TestRec").getPopulatedOrdinals(); for(int i=0;i<36;i++) { Assert.assertTrue(ordinals.get(i)); assertRecordOrdinal(consumer, i, "val"+(i+1), i+1); } Assert.assertEquals(36, ordinals.cardinality()); } private void add(WriteState state, String sVal, int iVal) { TestRec rec = new TestRec(sVal, iVal); state.add(rec); state.add(new ListRec(rec)); state.add(new SetRec(rec)); state.add(new MapRec(rec)); } private void assertRecordOrdinal(HollowConsumer consumer, int ordinal, String sVal, int iVal) { HollowObjectTypeReadState typeState = (HollowObjectTypeReadState)consumer.getStateEngine().getTypeState("TestRec"); Assert.assertEquals(iVal, typeState.readInt(ordinal, typeState.getSchema().getPosition("intVal"))); Assert.assertEquals(sVal, typeState.readString(ordinal, typeState.getSchema().getPosition("strVal"))); HollowListTypeReadState listState = (HollowListTypeReadState)consumer.getStateEngine().getTypeState("ListOfTestRec"); HollowOrdinalIterator iter = listState.ordinalIterator(ordinal); Assert.assertEquals(ordinal, iter.next()); Assert.assertEquals(HollowOrdinalIterator.NO_MORE_ORDINALS, iter.next()); HollowSetTypeReadState setState = (HollowSetTypeReadState)consumer.getStateEngine().getTypeState("SetOfTestRec"); iter = setState.ordinalIterator(ordinal); Assert.assertEquals(ordinal, iter.next()); Assert.assertEquals(HollowOrdinalIterator.NO_MORE_ORDINALS, iter.next()); HollowMapTypeReadState mapState = (HollowMapTypeReadState)consumer.getStateEngine().getTypeState("MapOfTestRecToTestRec"); HollowMapEntryOrdinalIterator mapIter = mapState.ordinalIterator(ordinal); Assert.assertTrue(mapIter.next()); Assert.assertEquals(ordinal, mapIter.getKey()); Assert.assertEquals(ordinal, mapIter.getValue()); Assert.assertEquals(HollowOrdinalIterator.NO_MORE_ORDINALS, iter.next()); } private static class ListRec { @HollowShardLargeType(numShards = 4) private final List<TestRec> list; public ListRec(TestRec rec) { this.list = Collections.singletonList(rec); } } private static class SetRec { @HollowShardLargeType(numShards = 4) private final Set<TestRec> set; public SetRec(TestRec rec) { this.set = Collections.singleton(rec); } } private static class MapRec { @HollowShardLargeType(numShards = 4) private final Map<TestRec, TestRec> map; public MapRec(TestRec rec) { this.map = Collections.singletonMap(rec, rec); } } @HollowShardLargeType(numShards = 4) private static class TestRec { @HollowInline private final String strVal; private final int intVal; public TestRec(String strVal, int intVal) { this.strVal = strVal; this.intVal = intVal; } } }
8,858
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/FailedTransitionTest.java
package com.netflix.hollow.api.consumer; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BooleanSupplier; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Test; public class FailedTransitionTest { @Test public void testSnapshotBlobFailure() { InMemoryBlobStore bs = new InMemoryBlobStore(); HollowProducer producer = HollowProducer.withPublisher(bs) .withBlobStager(new HollowInMemoryBlobStager()) .build(); long version = producer.runCycle(ws -> { ws.add(1); }); AtomicBoolean failer = new AtomicBoolean(); HollowConsumer consumer = HollowConsumer .withBlobRetriever(new FailingBlobRetriever(failer::get, bs)) .build(); // Fail transitioning to snapshot failer.set(true); try { consumer.triggerRefreshTo(version); Assert.fail(); } catch (Exception e) { Throwable cause = e.getCause(); Assert.assertNotNull(cause); Assert.assertTrue(cause instanceof IOException); Assert.assertEquals("FAILED", cause.getMessage()); Assert.assertEquals(1, consumer.getNumFailedSnapshotTransitions()); } // Fail for existing transition failer.set(false); try { consumer.triggerRefreshTo(version); Assert.fail(); } catch (RuntimeException e) { Assert.assertEquals(1, consumer.getNumFailedSnapshotTransitions()); } try { consumer.triggerRefreshTo(version); Assert.fail(); } catch (RuntimeException e) { Assert.assertEquals(1, consumer.getNumFailedSnapshotTransitions()); } version = producer.runCycle(ws -> { ws.add(2); }); // Pass for new transition // Consumer double snapshots consumer.triggerRefreshTo(version); Assert.assertEquals(1, consumer.getNumFailedSnapshotTransitions()); } @Test public void testDeltaBlobFailure() { InMemoryBlobStore bs = new InMemoryBlobStore(); HollowProducer producer = HollowProducer.withPublisher(bs) .withBlobStager(new HollowInMemoryBlobStager()) .build(); long version = producer.runCycle(ws -> { ws.add(1); }); AtomicBoolean failer = new AtomicBoolean(); HollowConsumer consumer = HollowConsumer .withBlobRetriever(new FailingBlobRetriever(failer::get, bs)) .build(); // Transition to snapshot consumer.triggerRefreshTo(version); version = producer.runCycle(ws -> { ws.add(2); }); // Fail transitioning to delta failer.set(true); try { consumer.triggerRefreshTo(version); Assert.fail(); } catch (Exception e) { Throwable cause = e.getCause(); Assert.assertNotNull(cause); Assert.assertTrue(cause instanceof IOException); Assert.assertEquals("FAILED", cause.getMessage()); Assert.assertEquals(1, consumer.getNumFailedDeltaTransitions()); } // Pass for new transition // Consumer double snapshots failer.set(false); consumer.triggerRefreshTo(version); } @Test public void testSnapshotBlobFailureNoDoubleSnapshot() { InMemoryBlobStore bs = new InMemoryBlobStore(); HollowProducer producer = HollowProducer.withPublisher(bs) .withBlobStager(new HollowInMemoryBlobStager()) .build(); long version = producer.runCycle(ws -> { ws.add(1); }); AtomicBoolean failer = new AtomicBoolean(); HollowConsumer consumer = HollowConsumer .withBlobRetriever(new FailingBlobRetriever(failer::get, bs)) .withDoubleSnapshotConfig(new NoDoubleSnapshotConfig()) .build(); // Fail transitioning to snapshot failer.set(true); try { consumer.triggerRefreshTo(version); Assert.fail(); } catch (Exception e) { Throwable cause = e.getCause(); Assert.assertNotNull(cause); Assert.assertTrue(cause instanceof IOException); Assert.assertEquals("FAILED", cause.getMessage()); Assert.assertEquals(1, consumer.getNumFailedSnapshotTransitions()); } // Pass on retry failer.set(false); consumer.triggerRefreshTo(version); } @Test public void testDeltaBlobFailureNoDoubleSnapshot() { InMemoryBlobStore bs = new InMemoryBlobStore(); HollowProducer producer = HollowProducer.withPublisher(bs) .withBlobStager(new HollowInMemoryBlobStager()) .build(); long version = producer.runCycle(ws -> { ws.add(1); }); AtomicBoolean failer = new AtomicBoolean(); HollowConsumer consumer = HollowConsumer .withBlobRetriever(new FailingBlobRetriever(failer::get, bs)) .withDoubleSnapshotConfig(new NoDoubleSnapshotConfig()) .build(); // Transition to snapshot consumer.triggerRefreshTo(version); version = producer.runCycle(ws -> { ws.add(2); }); // Fail transitioning to delta failer.set(true); try { consumer.triggerRefreshTo(version); Assert.fail(); } catch (Exception e) { Throwable cause = e.getCause(); Assert.assertNotNull(cause); Assert.assertTrue(cause instanceof IOException); Assert.assertEquals("FAILED", cause.getMessage()); Assert.assertEquals(1, consumer.getNumFailedDeltaTransitions()); } // Pass on retry failer.set(false); consumer.triggerRefreshTo(version); } static class NoDoubleSnapshotConfig implements HollowConsumer.DoubleSnapshotConfig { @Override public boolean allowDoubleSnapshot() { return false; } @Override public int maxDeltasBeforeDoubleSnapshot() { return 32; } } static class FailingBlobRetriever implements HollowConsumer.BlobRetriever { final BooleanSupplier failer; final HollowConsumer.BlobRetriever br; FailingBlobRetriever(BooleanSupplier failer, HollowConsumer.BlobRetriever br) { this.failer = failer; this.br = br; } @Override public HollowConsumer.HeaderBlob retrieveHeaderBlob(long version) { HollowConsumer.HeaderBlob blob = br.retrieveHeaderBlob(version); return new HollowConsumer.HeaderBlob(version) { @Override public InputStream getInputStream() throws IOException { if (failer.getAsBoolean()) { throw new IOException("FAILED"); } return blob.getInputStream(); } }; } @Override public HollowConsumer.Blob retrieveSnapshotBlob(long desiredVersion) { HollowConsumer.Blob blob = br.retrieveSnapshotBlob(desiredVersion); return new HollowConsumer.Blob(desiredVersion) { @Override public InputStream getInputStream() throws IOException { if (failer.getAsBoolean()) { throw new IOException("FAILED"); } return blob.getInputStream(); } }; } @Override public HollowConsumer.Blob retrieveDeltaBlob(long currentVersion) { HollowConsumer.Blob blob = br.retrieveDeltaBlob(currentVersion); return new HollowConsumer.Blob(blob.getFromVersion(), blob.getToVersion()) { @Override public InputStream getInputStream() throws IOException { if (failer.getAsBoolean()) { throw new IOException("FAILED"); } return blob.getInputStream(); } }; } @Override public HollowConsumer.Blob retrieveReverseDeltaBlob(long currentVersion) { HollowConsumer.Blob blob = br.retrieveReverseDeltaBlob(currentVersion); return new HollowConsumer.Blob(blob.getFromVersion(), blob.getToVersion()) { @Override public InputStream getInputStream() throws IOException { if (failer.getAsBoolean()) { throw new IOException("FAILED"); } return blob.getInputStream(); } }; } } }
8,859
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/InMemoryAnnouncement.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.consumer; import com.netflix.hollow.api.consumer.HollowConsumer.AnnouncementWatcher; import com.netflix.hollow.api.producer.HollowProducer.Announcer; import java.util.ArrayList; import java.util.List; /// This InMemoryAnnouncement is both a HollowProducer.Announcer and HollowConsumer.AnnouncementWatcher! public class InMemoryAnnouncement implements Announcer, AnnouncementWatcher { private final List<HollowConsumer> subscribedConsumers; long latestAnnouncedVersion = NO_ANNOUNCEMENT_AVAILABLE; long pinnedVersion = NO_ANNOUNCEMENT_AVAILABLE; public InMemoryAnnouncement() { this.subscribedConsumers = new ArrayList<HollowConsumer>(); } @Override public long getLatestVersion() { if(pinnedVersion != NO_ANNOUNCEMENT_AVAILABLE) return pinnedVersion; return latestAnnouncedVersion; } @Override public void subscribeToUpdates(HollowConsumer consumer) { subscribedConsumers.add(consumer); } @Override public void announce(long stateVersion) { latestAnnouncedVersion = stateVersion; notifyConsumers(); } public void pin(long stateVersion) { pinnedVersion = stateVersion; notifyConsumers(); } public void unpin() { pinnedVersion = NO_ANNOUNCEMENT_AVAILABLE; notifyConsumers(); } private void notifyConsumers() { for(HollowConsumer consumer : subscribedConsumers) { consumer.triggerRefresh(); // triggering a blocking refresh so we can make assertions } }; }
8,860
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/FailedTransitionTrackerTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.consumer; import com.netflix.hollow.api.client.FailedTransitionTracker; import com.netflix.hollow.api.client.HollowUpdatePlan; import com.netflix.hollow.api.consumer.HollowConsumer.Blob; import java.io.IOException; import java.io.InputStream; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class FailedTransitionTrackerTest { private FailedTransitionTracker tracker; @Before public void setUp() { this.tracker = new FailedTransitionTracker(); tracker.markFailedTransition(new FakeHollowBlob(1)); HollowUpdatePlan plan = new HollowUpdatePlan(); plan.add(new FakeHollowBlob(100, 101)); plan.add(new FakeHollowBlob(101, 102)); tracker.markAllTransitionsAsFailed(plan); } @After public void tearDown() { this.tracker.clear(); } @Test public void testNoFailedTransitions() { HollowUpdatePlan plan = new HollowUpdatePlan(); plan.add(new FakeHollowBlob(50)); plan.add(new FakeHollowBlob(50, 51)); plan.add(new FakeHollowBlob(51, 52)); plan.add(new FakeHollowBlob(52, 53)); Assert.assertFalse(tracker.anyTransitionWasFailed(plan)); } @Test public void testFailedDeltaTransition() { HollowUpdatePlan plan = new HollowUpdatePlan(); plan.add(new FakeHollowBlob(99)); plan.add(new FakeHollowBlob(99, 100)); plan.add(new FakeHollowBlob(100, 101)); Assert.assertTrue(tracker.anyTransitionWasFailed(plan)); } @Test public void testFailedSnapshotTransition() { HollowUpdatePlan plan = new HollowUpdatePlan(); plan.add(new FakeHollowBlob(1)); plan.add(new FakeHollowBlob(1, 2)); plan.add(new FakeHollowBlob(2, 3)); Assert.assertTrue(tracker.anyTransitionWasFailed(plan)); } @Test public void testGetNumFailedSnapshotTransitions() { // setUp adds a single failed snapshot transition Assert.assertEquals(1, tracker.getNumFailedSnapshotTransitions()); } @Test public void testGetNumFailedDeltaTransitions() { // setUp adds a two failed delta transitions Assert.assertEquals(2, tracker.getNumFailedDeltaTransitions()); } static class FakeHollowBlob extends Blob { public FakeHollowBlob(long toVersion) { super(toVersion); } public FakeHollowBlob(long fromVersion, long toVersion) { super(fromVersion, toVersion); } public InputStream getInputStream() throws IOException { return null; } } }
8,861
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/HollowConsumerBuilderTest.java
package com.netflix.hollow.api.consumer; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.netflix.hollow.api.consumer.index.HashIndex; import com.netflix.hollow.test.HollowWriteStateEngineBuilder; import com.netflix.hollow.test.consumer.TestBlobRetriever; import com.netflix.hollow.test.consumer.TestHollowConsumer; import com.netflix.hollow.test.generated.Award; import com.netflix.hollow.test.generated.AwardsAPI; import com.netflix.hollow.test.generated.Movie; import com.netflix.hollow.test.generated.MoviePrimaryKeyIndex; import java.io.IOException; import java.util.HashSet; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class HollowConsumerBuilderTest { @Test public void testCachedTypes() throws IOException { TestHollowConsumer consumer = new TestHollowConsumer.Builder() .withBlobRetriever(new TestBlobRetriever()) .withGeneratedAPIClass(AwardsAPI.class, "Movie") .build(); testConsumerCache(true, false, consumer); } @Rule public ExpectedException expectedEx = ExpectedException.none(); @Test public void testCachedTypes_inputSanitization() { expectedEx.expect(NullPointerException.class); expectedEx.expectMessage("null detected for varargs parameter additionalCachedTypes"); TestHollowConsumer consumer = new TestHollowConsumer.Builder() .withBlobRetriever(new TestBlobRetriever()) .withGeneratedAPIClass(AwardsAPI.class, "Movie", null) .build(); } @Test(expected = IllegalStateException.class) public void testCachedTypesDetached() throws IOException { TestHollowConsumer consumer = new TestHollowConsumer.Builder() .withBlobRetriever(new TestBlobRetriever()) .withGeneratedAPIClass(AwardsAPI.class, "Movie") .build(); testConsumerCache(true, true, consumer); } @Test public void testNoCacheConsumer() throws IOException { TestHollowConsumer consumer = new TestHollowConsumer.Builder() .withBlobRetriever(new TestBlobRetriever()) .withGeneratedAPIClass(AwardsAPI.class) .build(); testConsumerCache(false, false, consumer); } private void testConsumerCache(boolean hasCache, boolean detachCache, TestHollowConsumer consumer) throws IOException { com.netflix.hollow.test.model.Movie m1 = new com.netflix.hollow.test.model.Movie(1, "test movie 1", 2023); com.netflix.hollow.test.model.Movie m2 = new com.netflix.hollow.test.model.Movie(2, "test movie 2", 2023); com.netflix.hollow.test.model.Award a1 = new com.netflix.hollow.test.model.Award(1, m1, new HashSet<com.netflix.hollow.test.model.Movie>() {{ add(m2); }}); com.netflix.hollow.test.model.Award a2 = new com.netflix.hollow.test.model.Award(2, m2, new HashSet<com.netflix.hollow.test.model.Movie>() {{ add(m1); }}); // v1 consumer.addSnapshot(1l, new HollowWriteStateEngineBuilder() .add(a1).build()); consumer.triggerRefreshTo(1l); AwardsAPI awardsAPI = (AwardsAPI) consumer.getAPI(); Movie movieFromV1 = awardsAPI.getMovie(0); // v2 consumer.addDelta(1l, 2l, new HollowWriteStateEngineBuilder() .add(a1, a2).build()); consumer.triggerRefreshTo(2l); assertTrue(consumer.getCurrentVersionId() == 2l); awardsAPI = (AwardsAPI) consumer.getAPI(); if (detachCache) { awardsAPI.detachCaches(); } Movie movie = awardsAPI.getMovie(0); // primary key index MoviePrimaryKeyIndex primaryKeyIndex = new MoviePrimaryKeyIndex(consumer, false); Movie movieFromPrimaryKeyIndex = primaryKeyIndex.findMatch(1l); // hash index HashIndex<Movie, Long> hashIndex = HashIndex.from(consumer, Movie.class) .usingPath("id", Long.class); // note ".value" suffix Movie movieFromHashIndex = hashIndex.findMatches(1l).findFirst().get(); // getAll Movie movieFromGetAllMovie = awardsAPI.getAllMovie().stream().findFirst().get(); // movie from award.getWinner() Award award1 = awardsAPI.getAward(0); Movie movieFromAward = award1.getWinner(); // movie from award.getNominees() Award award2 = awardsAPI.getAward(1); Movie movieFromAwardNominees = award2.getNominees().stream().findFirst().get(); if (hasCache) { assertTrue(movie == movieFromV1); assertTrue(movie == movieFromPrimaryKeyIndex); assertTrue(movie == movieFromHashIndex); assertTrue(movie == movieFromGetAllMovie); assertTrue(movie == movieFromAward); assertTrue(movie == movieFromAwardNominees); } else { assertFalse(movie == movieFromV1); assertFalse(movie == movieFromPrimaryKeyIndex); assertFalse(movie == movieFromHashIndex); assertFalse(movie == movieFromGetAllMovie); assertFalse(movie == movieFromAward); assertFalse(movie == movieFromAwardNominees); } } }
8,862
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/metrics/AbstractRefreshMetricsListenerTest.java
package com.netflix.hollow.api.consumer.metrics; import static com.netflix.hollow.core.HollowConstants.VERSION_NONE; import static com.netflix.hollow.core.HollowStateEngine.HEADER_TAG_METRIC_ANNOUNCEMENT; import static com.netflix.hollow.core.HollowStateEngine.HEADER_TAG_METRIC_CYCLE_START; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.when; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class AbstractRefreshMetricsListenerTest { private final long TEST_VERSION_LOW = 123l; private final long TEST_VERSION_HIGH = 456l; private final long TEST_CYCLE_START_TIMESTAMP = System.currentTimeMillis(); private final long TEST_ANNOUNCEMENT_TIMESTAMP = System.currentTimeMillis() + 5000l; private Map<String, String> testHeaderTags = new HashMap<>(); protected TestRefreshMetricsListener concreteRefreshMetricsListener; @Mock HollowReadStateEngine mockStateEngine; class TestRefreshMetricsListener extends AbstractRefreshMetricsListener { @Override public void refreshEndMetricsReporting(ConsumerRefreshMetrics refreshMetrics) { assertNotNull(refreshMetrics); } } @Before public void setup() { concreteRefreshMetricsListener = new TestRefreshMetricsListener(); MockitoAnnotations.initMocks(this); when(mockStateEngine.getHeaderTags()).thenReturn(testHeaderTags); } @Test public void testRefreshStartedWithInitialLoad() { concreteRefreshMetricsListener.refreshStarted(VERSION_NONE, TEST_VERSION_HIGH); ConsumerRefreshMetrics refreshMetrics = concreteRefreshMetricsListener.refreshMetricsBuilder.build(); assertEquals(true, refreshMetrics.getIsInitialLoad()); assertNotNull(refreshMetrics.getUpdatePlanDetails()); } @Test public void testRefreshStartedWithSubsequentLoad() { concreteRefreshMetricsListener.refreshStarted(TEST_VERSION_LOW, TEST_VERSION_HIGH); ConsumerRefreshMetrics refreshMetrics = concreteRefreshMetricsListener.refreshMetricsBuilder.build(); Assert.assertFalse(refreshMetrics.getIsInitialLoad()); assertNotNull(refreshMetrics.getUpdatePlanDetails()); } @Test public void testTransitionsPlannedWithSnapshotUpdatePlan() { List<HollowConsumer.Blob.BlobType> testTransitionSequence = new ArrayList<HollowConsumer.Blob.BlobType>() {{ add(HollowConsumer.Blob.BlobType.SNAPSHOT); add(HollowConsumer.Blob.BlobType.DELTA); add(HollowConsumer.Blob.BlobType.DELTA); }}; concreteRefreshMetricsListener.refreshStarted(TEST_VERSION_LOW, TEST_VERSION_HIGH); concreteRefreshMetricsListener.transitionsPlanned(TEST_VERSION_LOW, TEST_VERSION_HIGH, true, testTransitionSequence); ConsumerRefreshMetrics refreshMetrics = concreteRefreshMetricsListener.refreshMetricsBuilder.build(); assertEquals(HollowConsumer.Blob.BlobType.SNAPSHOT, refreshMetrics.getOverallRefreshType()); assertEquals(TEST_VERSION_HIGH, refreshMetrics.getUpdatePlanDetails().getDesiredVersion()); assertEquals(TEST_VERSION_LOW, refreshMetrics.getUpdatePlanDetails().getBeforeVersion()); assertEquals(testTransitionSequence, refreshMetrics.getUpdatePlanDetails().getTransitionSequence()); } @Test public void testTransitionsPlannedWithDeltaUpdatePlan() { List<HollowConsumer.Blob.BlobType> testTransitionSequence = new ArrayList<HollowConsumer.Blob.BlobType>() {{ add(HollowConsumer.Blob.BlobType.DELTA); add(HollowConsumer.Blob.BlobType.DELTA); add(HollowConsumer.Blob.BlobType.DELTA); }}; concreteRefreshMetricsListener.refreshStarted(TEST_VERSION_LOW, TEST_VERSION_HIGH); concreteRefreshMetricsListener.transitionsPlanned(TEST_VERSION_LOW, TEST_VERSION_HIGH, false, testTransitionSequence); ConsumerRefreshMetrics refreshMetrics = concreteRefreshMetricsListener.refreshMetricsBuilder.build(); assertEquals(HollowConsumer.Blob.BlobType.DELTA, refreshMetrics.getOverallRefreshType()); assertEquals(TEST_VERSION_HIGH, refreshMetrics.getUpdatePlanDetails().getDesiredVersion()); assertEquals(TEST_VERSION_LOW, refreshMetrics.getUpdatePlanDetails().getBeforeVersion()); assertEquals(testTransitionSequence, refreshMetrics.getUpdatePlanDetails().getTransitionSequence()); } @Test public void testTransitionsPlannedWithReverseDeltaUpdatePlan() { List<HollowConsumer.Blob.BlobType> testTransitionSequence = new ArrayList<HollowConsumer.Blob.BlobType>() {{ add(HollowConsumer.Blob.BlobType.REVERSE_DELTA); add(HollowConsumer.Blob.BlobType.REVERSE_DELTA); add(HollowConsumer.Blob.BlobType.REVERSE_DELTA); }}; concreteRefreshMetricsListener.refreshStarted(TEST_VERSION_HIGH, TEST_VERSION_LOW); concreteRefreshMetricsListener.transitionsPlanned(TEST_VERSION_HIGH, TEST_VERSION_LOW, false, testTransitionSequence); ConsumerRefreshMetrics refreshMetrics = concreteRefreshMetricsListener.refreshMetricsBuilder.build(); assertEquals(HollowConsumer.Blob.BlobType.REVERSE_DELTA, refreshMetrics.getOverallRefreshType()); assertEquals(TEST_VERSION_LOW, refreshMetrics.getUpdatePlanDetails().getDesiredVersion()); assertEquals(TEST_VERSION_HIGH, refreshMetrics.getUpdatePlanDetails().getBeforeVersion()); assertEquals(testTransitionSequence, refreshMetrics.getUpdatePlanDetails().getTransitionSequence()); } @Test public void testRefreshSuccess() { class SuccessTestRefreshMetricsListener extends AbstractRefreshMetricsListener { @Override public void refreshEndMetricsReporting(ConsumerRefreshMetrics refreshMetrics) { assertEquals(0l, refreshMetrics.getConsecutiveFailures()); assertEquals(true, refreshMetrics.getIsRefreshSuccess()); assertEquals(0l, refreshMetrics.getRefreshSuccessAgeMillisOptional().getAsLong()); Assert.assertNotEquals(0l, refreshMetrics.getRefreshEndTimeNano()); assertEquals(TEST_CYCLE_START_TIMESTAMP, refreshMetrics.getCycleStartTimestamp().getAsLong()); assertEquals(TEST_ANNOUNCEMENT_TIMESTAMP, refreshMetrics.getAnnouncementTimestamp().getAsLong()); } } SuccessTestRefreshMetricsListener successTestRefreshMetricsListener = new SuccessTestRefreshMetricsListener(); successTestRefreshMetricsListener.refreshStarted(TEST_VERSION_LOW, TEST_VERSION_HIGH); testHeaderTags.put(HEADER_TAG_METRIC_CYCLE_START, String.valueOf(TEST_CYCLE_START_TIMESTAMP)); testHeaderTags.put(HEADER_TAG_METRIC_ANNOUNCEMENT, String.valueOf(TEST_ANNOUNCEMENT_TIMESTAMP)); successTestRefreshMetricsListener.snapshotUpdateOccurred(null, mockStateEngine, TEST_VERSION_HIGH); successTestRefreshMetricsListener.refreshSuccessful(TEST_VERSION_LOW, TEST_VERSION_HIGH, TEST_VERSION_HIGH); } @Test public void testRefreshFailure() { class FailureTestRefreshMetricsListener extends AbstractRefreshMetricsListener { @Override public void refreshEndMetricsReporting(ConsumerRefreshMetrics refreshMetrics) { Assert.assertNotEquals(0l, refreshMetrics.getConsecutiveFailures()); Assert.assertFalse(refreshMetrics.getIsRefreshSuccess()); Assert.assertNotEquals(Optional.empty(), refreshMetrics.getRefreshSuccessAgeMillisOptional()); Assert.assertNotEquals(0l, refreshMetrics.getRefreshEndTimeNano()); Assert.assertFalse(refreshMetrics.getCycleStartTimestamp().isPresent()); Assert.assertFalse(refreshMetrics.getAnnouncementTimestamp().isPresent()); } } FailureTestRefreshMetricsListener failTestRefreshMetricsListener = new FailureTestRefreshMetricsListener(); failTestRefreshMetricsListener.refreshStarted(TEST_VERSION_LOW, TEST_VERSION_HIGH); failTestRefreshMetricsListener.refreshFailed(TEST_VERSION_LOW, TEST_VERSION_HIGH, TEST_VERSION_HIGH, null); } @Test public void testMetricsWhenMultiTransitionRefreshSucceeds() { class SuccessTestRefreshMetricsListener extends AbstractRefreshMetricsListener { @Override public void refreshEndMetricsReporting(ConsumerRefreshMetrics refreshMetrics) { assertEquals(3, refreshMetrics.getUpdatePlanDetails().getNumSuccessfulTransitions()); assertEquals(TEST_CYCLE_START_TIMESTAMP, refreshMetrics.getCycleStartTimestamp().getAsLong()); assertEquals(TEST_ANNOUNCEMENT_TIMESTAMP, refreshMetrics.getAnnouncementTimestamp().getAsLong()); } } List<HollowConsumer.Blob.BlobType> testTransitionSequence = new ArrayList<HollowConsumer.Blob.BlobType>() {{ add(HollowConsumer.Blob.BlobType.SNAPSHOT); add(HollowConsumer.Blob.BlobType.DELTA); add(HollowConsumer.Blob.BlobType.DELTA); }}; SuccessTestRefreshMetricsListener successTestRefreshMetricsListener = new SuccessTestRefreshMetricsListener(); successTestRefreshMetricsListener.refreshStarted(TEST_VERSION_LOW, TEST_VERSION_HIGH); successTestRefreshMetricsListener.transitionsPlanned(TEST_VERSION_LOW, TEST_VERSION_HIGH, true, testTransitionSequence); successTestRefreshMetricsListener.blobLoaded(null); testHeaderTags.put(HEADER_TAG_METRIC_CYCLE_START, String.valueOf(TEST_CYCLE_START_TIMESTAMP-2)); testHeaderTags.put(HEADER_TAG_METRIC_ANNOUNCEMENT, String.valueOf(TEST_ANNOUNCEMENT_TIMESTAMP-2)); successTestRefreshMetricsListener.deltaUpdateOccurred(null, mockStateEngine, TEST_VERSION_HIGH-2); successTestRefreshMetricsListener.blobLoaded(null); testHeaderTags.put(HEADER_TAG_METRIC_CYCLE_START, String.valueOf(TEST_CYCLE_START_TIMESTAMP-1)); testHeaderTags.put(HEADER_TAG_METRIC_ANNOUNCEMENT, String.valueOf(TEST_ANNOUNCEMENT_TIMESTAMP-1)); successTestRefreshMetricsListener.deltaUpdateOccurred(null, mockStateEngine, TEST_VERSION_HIGH-1); successTestRefreshMetricsListener.blobLoaded(null); testHeaderTags.put(HEADER_TAG_METRIC_CYCLE_START, String.valueOf(TEST_CYCLE_START_TIMESTAMP)); testHeaderTags.put(HEADER_TAG_METRIC_ANNOUNCEMENT, String.valueOf(TEST_ANNOUNCEMENT_TIMESTAMP)); successTestRefreshMetricsListener.deltaUpdateOccurred(null, mockStateEngine, TEST_VERSION_HIGH); successTestRefreshMetricsListener.refreshSuccessful(TEST_VERSION_LOW, TEST_VERSION_HIGH, TEST_VERSION_HIGH); } @Test public void testMetricsWhenMultiTransitionRefreshFails() { class FailureTestRefreshMetricsListener extends AbstractRefreshMetricsListener { @Override public void refreshEndMetricsReporting(ConsumerRefreshMetrics refreshMetrics) { assertEquals(1, refreshMetrics.getUpdatePlanDetails().getNumSuccessfulTransitions()); assertEquals(TEST_CYCLE_START_TIMESTAMP, refreshMetrics.getCycleStartTimestamp().getAsLong()); } } List<HollowConsumer.Blob.BlobType> testTransitionSequence = new ArrayList<HollowConsumer.Blob.BlobType>() {{ add(HollowConsumer.Blob.BlobType.SNAPSHOT); add(HollowConsumer.Blob.BlobType.DELTA); add(HollowConsumer.Blob.BlobType.DELTA); }}; FailureTestRefreshMetricsListener failureTestRefreshMetricsListener = new FailureTestRefreshMetricsListener(); failureTestRefreshMetricsListener.refreshStarted(TEST_VERSION_LOW, TEST_VERSION_HIGH); failureTestRefreshMetricsListener.transitionsPlanned(TEST_VERSION_LOW, TEST_VERSION_HIGH, true, testTransitionSequence); failureTestRefreshMetricsListener.blobLoaded(null); testHeaderTags.put(HEADER_TAG_METRIC_CYCLE_START, String.valueOf(TEST_CYCLE_START_TIMESTAMP)); failureTestRefreshMetricsListener.snapshotUpdateOccurred(null, mockStateEngine, TEST_VERSION_LOW); failureTestRefreshMetricsListener.refreshFailed(TEST_VERSION_LOW-1, TEST_VERSION_LOW, TEST_VERSION_HIGH, null); } @Test public void testCycleStart() { // also exercises reverse delta transition InMemoryBlobStore blobStore = new InMemoryBlobStore(); HollowInMemoryBlobStager blobStager = new HollowInMemoryBlobStager(); HollowProducer p = HollowProducer .withPublisher(blobStore) .withBlobStager(blobStager) .build(); p.initializeDataModel(String.class); long version1 = p.runCycle(ws -> { // override cycle start time with a strictly incrementing count to prevent potential // clock skew issue from use of System.currentTimeMillis() that would make test brittle ws.getStateEngine().addHeaderTag(HEADER_TAG_METRIC_CYCLE_START, "1"); ws.add("A"); }); class TestRefreshMetricsListener extends AbstractRefreshMetricsListener { int run = 0; @Override public void refreshEndMetricsReporting(ConsumerRefreshMetrics refreshMetrics) { run ++; assertNotNull(refreshMetrics.getCycleStartTimestamp()); switch (run) { case 1: assertEquals(1L, refreshMetrics.getCycleStartTimestamp().getAsLong()); break; case 2: case 5: assertEquals(2L, refreshMetrics.getCycleStartTimestamp().getAsLong()); break; case 3: assertEquals(1L, refreshMetrics.getCycleStartTimestamp().getAsLong()); break; case 4: assertEquals(3L, refreshMetrics.getCycleStartTimestamp().getAsLong()); break; } } } TestRefreshMetricsListener testMetricsListener = new TestRefreshMetricsListener(); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore) .withRefreshListener(testMetricsListener) .build(); consumer.triggerRefreshTo(version1); // snapshot load long version2 = p.runCycle(ws -> { ws.getStateEngine().addHeaderTag(HEADER_TAG_METRIC_CYCLE_START, "2"); ws.add("B"); }); consumer.triggerRefreshTo(version2); // delta transition consumer.triggerRefreshTo(version1); // reverse delta transition // now restore from v2 and continue delta chain HollowProducer p2 = HollowProducer .withPublisher(blobStore) .withBlobStager(blobStager) .build(); p2.initializeDataModel(String.class); p2.restore(version2, blobStore); long version3 = p2.runCycle(ws -> { ws.getStateEngine().addHeaderTag(HEADER_TAG_METRIC_CYCLE_START, "3"); ws.add("C"); }); consumer.triggerRefreshTo(version3); // delta transition consumer.triggerRefreshTo(version2); // reverse delta transition } }
8,863
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/index/HashIndexUpdatesTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.consumer.index; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HashIndexUpdatesTest { InMemoryBlobStore blobStore; @Before public void setUp() { blobStore = new InMemoryBlobStore(); } void updates(boolean doubleSnapshot) { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); long v1 = producer.runCycle(ws -> { ws.add(new DataModel.Producer.TypeA(1, "1")); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore) .withGeneratedAPIClass(DataModel.Consumer.Api.class) .build(); consumer.triggerRefreshTo(v1); HashIndex<DataModel.Consumer.TypeA, Integer> hi = HashIndex.from(consumer, DataModel.Consumer.TypeA.class) .usingPath("i", int.class); consumer.addRefreshListener(hi); Assert.assertEquals(1L, hi.findMatches(1).count()); long v2 = producer.runCycle(ws -> { ws.add(new DataModel.Producer.TypeA(1, "1")); ws.add(new DataModel.Producer.TypeA(1, "2")); }); if (doubleSnapshot) { consumer.forceDoubleSnapshotNextUpdate(); } consumer.triggerRefreshTo(v2); Assert.assertEquals(2L, hi.findMatches(1).count()); consumer.removeRefreshListener(hi); long v3 = producer.runCycle(ws -> { ws.add(new DataModel.Producer.TypeA(1, "1")); ws.add(new DataModel.Producer.TypeA(1, "2")); ws.add(new DataModel.Producer.TypeA(1, "3")); }); if (doubleSnapshot) { consumer.forceDoubleSnapshotNextUpdate(); } consumer.triggerRefreshTo(v3); Assert.assertEquals(2L, hi.findMatches(1).count()); } @Test public void deltaUpdates() { updates(false); } @Test public void snapshotUpdates() { updates(true); } }
8,864
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/index/UniqueKeyIndexTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.consumer.index; import static java.util.stream.Collectors.toList; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.objects.HollowObject; import com.netflix.hollow.api.objects.HollowRecord; import com.netflix.hollow.api.objects.delegate.HollowObjectDelegate; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Supplier; import java.util.stream.Stream; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; public class UniqueKeyIndexTest { // Map of primitive class to box class static final Map<Class<?>, Class<?>> primitiveClasses; static { primitiveClasses = new HashMap<>(); primitiveClasses.put(boolean.class, Boolean.class); primitiveClasses.put(byte.class, Byte.class); primitiveClasses.put(short.class, Short.class); primitiveClasses.put(char.class, Character.class); primitiveClasses.put(int.class, Integer.class); primitiveClasses.put(long.class, Long.class); primitiveClasses.put(float.class, Float.class); primitiveClasses.put(double.class, Double.class); } static HollowConsumer consumer; static DataModel.Consumer.Api api; @BeforeClass public static void setup() { InMemoryBlobStore blobStore = new InMemoryBlobStore(); HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); long v1 = producer.runCycle(ws -> { ws.add(new DataModel.Producer.References()); for (int i = 0; i < 100; i++) { ws.add(new DataModel.Producer.TypeA(1, "TypeA" + i)); } ws.add(new DataModel.Producer.TypeWithPrimaryKey2(1)); }); consumer = HollowConsumer.withBlobRetriever(blobStore) .withGeneratedAPIClass(DataModel.Consumer.Api.class) .build(); consumer.triggerRefreshTo(v1); api = consumer.getAPI(DataModel.Consumer.Api.class); } public static abstract class MatchTestParameterized<T extends HollowObject, Q> extends UniqueKeyIndexTest { final String path; final Class<Q> type; final Q value; final Class<T> uniqueType; public MatchTestParameterized(String path, Class<Q> type, Q value, Class<T> uniqueType) { this.path = path; this.type = type; this.value = value; this.uniqueType = uniqueType; } @Test public void test() { UniqueKeyIndex<T, Q> pki = UniqueKeyIndex .from(consumer, uniqueType) .usingPath(path, type); T r = pki.findMatch(value); Assert.assertNotNull(r); Assert.assertEquals(0, r.getOrdinal()); } } // path, type, value static List<Object[]> valuesDataProvider() { DataModel.Producer.Values values = new DataModel.Producer.Values(); return Stream.of(DataModel.Producer.Values.class.getDeclaredFields()) .flatMap(f -> { String path = f.getName(); Class<?> type = f.getType(); Object value; try { value = f.get(values); } catch (IllegalAccessException e) { throw new InternalError(); } Object[] args = new Object[] {path, type, value}; if (type.isPrimitive()) { return Stream.of(args, new Object[] {path, primitiveClasses.get(type), value} ); } else { return Stream.<Object[]>of(args); } }) .collect(toList()); } @RunWith(Parameterized.class) public static class MatchOnValuesTest<Q> extends MatchTestParameterized<DataModel.Consumer.Values, Q> { // path[type] = value @Parameterized.Parameters(name = "{index}: {0}[{1}] = {2}") public static Collection<Object[]> data() { return valuesDataProvider(); } public MatchOnValuesTest(String path, Class<Q> type, Q value) { super(path, type, value, DataModel.Consumer.Values.class); } } @RunWith(Parameterized.class) public static class MatchOnValuesIllegalTypeTest extends UniqueKeyIndexTest { // path[type] = value @Parameterized.Parameters(name = "{index}: {0}[{1}] = {2}") public static Collection<Object[]> data() { return valuesDataProvider(); } final String path; final Class<?> type; final Object value; public MatchOnValuesIllegalTypeTest(String path, Class<?> type, Object value) { this.path = path; this.type = type; this.value = value; } @Test(expected = IllegalArgumentException.class) public void test() { UniqueKeyIndex .from(consumer, DataModel.Consumer.Values.class) .usingPath(path, Object.class); } } public static class MatchOnValuesBeanTest extends UniqueKeyIndexTest { static class ValueFieldsQuery { @FieldPath boolean _boolean; @FieldPath byte _byte; @FieldPath short _short; @FieldPath char _char; @FieldPath int _int; @FieldPath long _long; @FieldPath float _float; @FieldPath double _double; @FieldPath byte[] _bytes; @FieldPath char[] _chars; ValueFieldsQuery(DataModel.Producer.Values v) { this._boolean = v._boolean; this._byte = v._byte; this._short = v._short; this._char = v._char; this._int = v._int; this._long = v._long; this._float = v._float; this._double = v._double; this._bytes = v._bytes.clone(); this._chars = v._chars.clone(); } static MatchOnValuesBeanTest.ValueFieldsQuery create() { return new MatchOnValuesBeanTest.ValueFieldsQuery(new DataModel.Producer.Values()); } } @Test public void testFields() { UniqueKeyIndex<DataModel.Consumer.Values, ValueFieldsQuery> hi = UniqueKeyIndex .from(consumer, DataModel.Consumer.Values.class) .usingBean(MatchOnValuesBeanTest.ValueFieldsQuery.class); DataModel.Consumer.Values r = hi.findMatch(MatchOnValuesBeanTest.ValueFieldsQuery.create()); Assert.assertNotNull(r); Assert.assertEquals(0, r.getOrdinal()); } static class ValueMethodsQuery { boolean _boolean; byte _byte; short _short; char _char; int _int; long _long; float _float; double _double; byte[] _bytes; char[] _chars; @FieldPath("_boolean") boolean is_boolean() { return _boolean; } @FieldPath("_byte") byte get_byte() { return _byte; } @FieldPath("_short") short get_short() { return _short; } @FieldPath("_char") char get_char() { return _char; } @FieldPath("_int") int get_int() { return _int; } @FieldPath("_long") long get_long() { return _long; } @FieldPath("_float") float get_float() { return _float; } @FieldPath("_double") double get_double() { return _double; } @FieldPath("_bytes") byte[] get_bytes() { return _bytes; } @FieldPath("_chars") char[] get_chars() { return _chars; } ValueMethodsQuery(DataModel.Producer.Values v) { this._boolean = v._boolean; this._byte = v._byte; this._short = v._short; this._char = v._char; this._int = v._int; this._long = v._long; this._float = v._float; this._double = v._double; this._bytes = v._bytes.clone(); this._chars = v._chars.clone(); } static MatchOnValuesBeanTest.ValueMethodsQuery create() { return new MatchOnValuesBeanTest.ValueMethodsQuery(new DataModel.Producer.Values()); } } @Test public void testMethods() { UniqueKeyIndex<DataModel.Consumer.Values, ValueMethodsQuery> hi = UniqueKeyIndex .from(consumer, DataModel.Consumer.Values.class) .usingBean(MatchOnValuesBeanTest.ValueMethodsQuery.class); DataModel.Consumer.Values r = hi.findMatch(MatchOnValuesBeanTest.ValueMethodsQuery.create()); Assert.assertNotNull(r); Assert.assertEquals(0, r.getOrdinal()); } } // path, type, value static List<Object[]> boxesDataProvider() { DataModel.Producer.Boxes values = new DataModel.Producer.Boxes(); return Stream.of(DataModel.Producer.Boxes.class.getDeclaredFields()) .map(f -> { // Path will be auto-expanded to append ".value" String path = f.getName(); Class<?> type = f.getType(); Object value; try { value = f.get(values); } catch (IllegalAccessException e) { throw new InternalError(); } return new Object[] {path, type, value}; }) .collect(toList()); } @RunWith(Parameterized.class) public static class MatchOnBoxesValuesTest<Q> extends MatchTestParameterized<DataModel.Consumer.Boxes, Q> { // path[type] = value @Parameterized.Parameters(name = "{index}: {0}[{1}] = {2}") public static Collection<Object[]> data() { return boxesDataProvider(); } public MatchOnBoxesValuesTest(String path, Class<Q> type, Q value) { super(path, type, value, DataModel.Consumer.Boxes.class); } } static List<Object[]> inlineBoxesDataProvider() { DataModel.Producer.InlineBoxes values = new DataModel.Producer.InlineBoxes(); return Stream.of(DataModel.Producer.InlineBoxes.class.getDeclaredFields()) .map(f -> { String path = f.getName(); Class<?> type = f.getType(); Object value; try { value = f.get(values); } catch (IllegalAccessException e) { throw new InternalError(); } return new Object[] {path, type, value}; }) .collect(toList()); } @RunWith(Parameterized.class) public static class MatchOnInlineBoxesTest<Q> extends MatchTestParameterized<DataModel.Consumer.InlineBoxes, Q> { // path[type] = value @Parameterized.Parameters(name = "{index}: {0}[{1}] = {2}") public static Collection<Object[]> data() { return inlineBoxesDataProvider(); } public MatchOnInlineBoxesTest(String path, Class<Q> type, Q value) { super(path, type, value, DataModel.Consumer.InlineBoxes.class); } } @RunWith(Parameterized.class) public static class MatchOnMappedReferencesTest<Q> extends MatchTestParameterized<DataModel.Consumer.MappedReferencesToValues, Q> { // path[type] = value @Parameterized.Parameters(name = "{index}: {0}[{1}] = {2}") public static Collection<Object[]> data() { return Arrays.<Object[]>asList( new Object[] {"date.value", long.class, 0L}, new Object[] {"number._name", String.class, "ONE"} ); } public MatchOnMappedReferencesTest(String path, Class<Q> type, Q value) { super(path, type, value, DataModel.Consumer.MappedReferencesToValues.class); } } @RunWith(Parameterized.class) public static class MatchOnMappedReferencesNoAutoExpansionTest<Q extends HollowRecord> extends UniqueKeyIndexTest { @Parameterized.Parameters(name = "{index}: {0}[{1} = {2}]") public static Collection<Object[]> data() { return Arrays.asList( args("values!", DataModel.Consumer.Values.class, () -> api.getValues(0)), args("boxes._string!", DataModel.Consumer.HString.class, () -> api.getHString(0)), args("referenceWithStrings!", DataModel.Consumer.ReferenceWithStringsRenamed.class, () -> api.getReferenceWithStringsRenamed(0)), args("referenceWithStrings._string1!", DataModel.Consumer.HString.class, () -> api.getHString(0)), args("referenceWithStrings._string2!", DataModel.Consumer.FieldOfStringRenamed.class, () -> api.getFieldOfStringRenamed(0)) ); } static <Q extends HollowRecord> Object[] args(String path, Class<Q> type, Supplier<Q> s) { return new Object[] {path, type, s}; } final String path; final Class<Q> type; final Q value; public MatchOnMappedReferencesNoAutoExpansionTest(String path, Class<Q> type, Supplier<Q> value) { this.path = path; this.type = type; this.value = value.get(); } @Test public void test() { UniqueKeyIndex<DataModel.Consumer.References, Q> uki = UniqueKeyIndex .from(consumer, DataModel.Consumer.References.class) .usingPath(path, type); DataModel.Consumer.References r = uki.findMatch(value); Assert.assertNotNull(r); Assert.assertEquals(0, r.getOrdinal()); } } public static class ErrorsTest extends UniqueKeyIndexTest { static class Unknown extends HollowObject { Unknown(HollowObjectDelegate delegate, int ordinal) { super(delegate, ordinal); } } @Test(expected = IllegalArgumentException.class) public void testUnknownRootSelectType() { UniqueKeyIndex .from(consumer, ErrorsTest.Unknown.class) .usingPath("values", DataModel.Consumer.Values.class); } @Test(expected = IllegalArgumentException.class) public void testEmptyMatchPath() { UniqueKeyIndex .from(consumer, DataModel.Consumer.References.class) .usingPath("", DataModel.Consumer.References.class); } @Test(expected = IllegalArgumentException.class) public void testNoPrimaryKey() { UniqueKeyIndex .from(consumer, DataModel.Consumer.References.class) .bindToPrimaryKey() .usingPath("values._int", int.class); } } public static class PrimaryKeyDeclarationTest extends UniqueKeyIndexTest { // This class declares fields in the same order as those declared in // the @HollowPrimaryKey on TypeWithPrimaryKey static class KeyTypeSameOrder { @FieldPath("i") int i; @FieldPath("sub1.s") String sub1_s; @FieldPath("sub2.i") int sub2_i; KeyTypeSameOrder(int i, String sub1_s, int sub2_i) { this.i = i; this.sub1_s = sub1_s; this.sub2_i = sub2_i; } } // This class declares fields in the reverse order as those declared in // the @HollowPrimaryKey on TypeWithPrimaryKey static class KeyTypeReverseOrder { @FieldPath("sub2.i") int sub2_i; @FieldPath("sub1.s") String sub1_s; @FieldPath("i") int i; KeyTypeReverseOrder(int i, String sub1_s, int sub2_i) { this.i = i; this.sub1_s = sub1_s; this.sub2_i = sub2_i; } } static class KeyWithMissingPath { @FieldPath("i") int i; @FieldPath("sub1.s") String sub1_s; int sub2_i; KeyWithMissingPath(int i, String sub1_s, int sub2_i) { this.i = i; this.sub1_s = sub1_s; this.sub2_i = sub2_i; } } static class KeyWithWrongPath { @FieldPath("i") int i; @FieldPath("sub1.s") String sub1_s; @FieldPath("sub2.s") String sub2_s; KeyWithWrongPath(int i, String sub1_s, String sub2_s) { this.i = i; this.sub1_s = sub1_s; this.sub2_s = sub2_s; } } static class KeyWithSinglePath { @FieldPath("i") int i; KeyWithSinglePath(int i) { this.i = i; } } public <T> void test(Class<T> keyType, T key) { UniqueKeyIndex<DataModel.Consumer.TypeWithPrimaryKey, T> pki = UniqueKeyIndex .from(consumer, DataModel.Consumer.TypeWithPrimaryKey.class) .bindToPrimaryKey() .usingBean(keyType); DataModel.Consumer.TypeWithPrimaryKey match = pki.findMatch(key); Assert.assertNotNull(match); Assert.assertEquals(0, match.getOrdinal()); } @Test public void testSameOrder() { test(KeyTypeSameOrder.class, new KeyTypeSameOrder(1, "1", 2)); } @Test public void testWithHollowTypeName() { UniqueKeyIndex<DataModel.Consumer.TypeWithPrimaryKeySuffixed, Integer> pki = UniqueKeyIndex.from(consumer, DataModel.Consumer.TypeWithPrimaryKeySuffixed.class) .bindToPrimaryKey() .usingPath("i", Integer.class); DataModel.Consumer.TypeWithPrimaryKeySuffixed match = pki.findMatch(1); Assert.assertNotNull(match); Assert.assertEquals(0, match.getOrdinal()); UniqueKeyIndex<DataModel.Consumer.TypeWithPrimaryKeySuffixed, KeyWithSinglePath> pki2 = UniqueKeyIndex.from(consumer, DataModel.Consumer.TypeWithPrimaryKeySuffixed.class) .bindToPrimaryKey() .usingBean(KeyWithSinglePath.class); match = pki2.findMatch(new KeyWithSinglePath(1)); Assert.assertNotNull(match); Assert.assertEquals(0, match.getOrdinal()); } @Test public void testReverseOrder() { test(KeyTypeReverseOrder.class, new KeyTypeReverseOrder(1, "1", 2)); } @Test(expected = IllegalArgumentException.class) public void testMissingPath() { test(KeyWithMissingPath.class, new KeyWithMissingPath(1, "1", 2)); } @Test(expected = IllegalArgumentException.class) public void testWrongPath() { test(KeyWithWrongPath.class, new KeyWithWrongPath(1, "1", "2")); } } }
8,865
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/index/HashIndexTest.java
package com.netflix.hollow.api.consumer.index; import static java.util.stream.Collectors.toList; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.objects.HollowObject; import com.netflix.hollow.api.objects.HollowRecord; import com.netflix.hollow.api.objects.delegate.HollowObjectDelegate; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; public class HashIndexTest { // Map of primitive class to box class private static final Map<Class<?>, Class<?>> primitiveClasses; static { primitiveClasses = new HashMap<>(); primitiveClasses.put(boolean.class, Boolean.class); primitiveClasses.put(byte.class, Byte.class); primitiveClasses.put(short.class, Short.class); primitiveClasses.put(char.class, Character.class); primitiveClasses.put(int.class, Integer.class); primitiveClasses.put(long.class, Long.class); primitiveClasses.put(float.class, Float.class); primitiveClasses.put(double.class, Double.class); } static HollowConsumer consumer; private static DataModel.Consumer.Api api; @BeforeClass public static void setup() { InMemoryBlobStore blobStore = new InMemoryBlobStore(); HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); long v1 = producer.runCycle(ws -> { ws.add(new DataModel.Producer.References()); for (int i = 0; i < 100; i++) { ws.add(new DataModel.Producer.TypeA(1, "TypeA" + i)); ws.add(new DataModel.Producer.TypeB(1, "TypeB" + i)); } ws.add(new DataModel.Producer.TypeWithTypeB("bar", new DataModel.Producer.TypeB(7, "c"))); ws.add(new DataModel.Producer.TypeWithTypeB("foo", new DataModel.Producer.TypeB(8, "a"))); ws.add(new DataModel.Producer.TypeWithTypeB("foo", new DataModel.Producer.TypeB(7, "b"))); }); consumer = HollowConsumer.withBlobRetriever(blobStore) .withGeneratedAPIClass(DataModel.Consumer.Api.class) .build(); consumer.triggerRefreshTo(v1); api = consumer.getAPI(DataModel.Consumer.Api.class); } public static abstract class MatchTestParameterized<T extends HollowObject, Q> extends HashIndexTest { final String path; final Class<Q> type; final Q value; final Class<T> selectType; MatchTestParameterized(String path, Class<Q> type, Q value, Class<T> selectType) { this.path = path; this.type = type; this.value = value; this.selectType = selectType; } @Test public void test() { HashIndex<T, Q> hi = HashIndex .from(consumer, selectType) .usingPath(path, type); List<T> r = hi .findMatches(value) .collect(toList()); Assert.assertEquals(1, r.size()); Assert.assertTrue(selectType.isInstance(r.get(0))); Assert.assertEquals(0, r.get(0).getOrdinal()); } } // path, type, value private static List<Object[]> valuesDataProvider() { DataModel.Producer.Values values = new DataModel.Producer.Values(); return Stream.of(DataModel.Producer.Values.class.getDeclaredFields()) .flatMap(f -> { String path = f.getName(); Class<?> type = f.getType(); Object value; try { value = f.get(values); } catch (IllegalAccessException e) { throw new InternalError(); } Object[] args = new Object[] {path, type, value}; if (type.isPrimitive()) { return Stream.of(args, new Object[] {path, primitiveClasses.get(type), value} ); } else { return Stream.<Object[]>of(args); } }) .collect(toList()); } @RunWith(Parameterized.class) public static class MatchOnValuesTest<Q> extends MatchTestParameterized<DataModel.Consumer.Values, Q> { // path[type] = value @Parameters(name = "{index}: {0}[{1}] = {2}") public static Collection<Object[]> data() { return valuesDataProvider(); } public MatchOnValuesTest(String path, Class<Q> type, Q value) { super(path, type, value, DataModel.Consumer.Values.class); } } @RunWith(Parameterized.class) public static class MatchOnValuesIllegalTypeTest extends HashIndexTest { // path[type] = value @Parameters(name = "{index}: {0}[{1}] = {2}") public static Collection<Object[]> data() { return valuesDataProvider(); } final String path; final Class<?> type; final Object value; public MatchOnValuesIllegalTypeTest(String path, Class<?> type, Object value) { this.path = path; this.type = type; this.value = value; } @Test(expected = IllegalArgumentException.class) public void test() { HashIndex .from(consumer, DataModel.Consumer.Values.class) .usingPath(path, Object.class); } } public static class MatchOnValuesBeanTest extends HashIndexTest { static class ValueFieldsQuery { @FieldPath boolean _boolean; @FieldPath byte _byte; @FieldPath short _short; @FieldPath char _char; @FieldPath int _int; @FieldPath long _long; @FieldPath float _float; @FieldPath double _double; @FieldPath byte[] _bytes; @FieldPath char[] _chars; ValueFieldsQuery(DataModel.Producer.Values v) { this._boolean = v._boolean; this._byte = v._byte; this._short = v._short; this._char = v._char; this._int = v._int; this._long = v._long; this._float = v._float; this._double = v._double; this._bytes = v._bytes.clone(); this._chars = v._chars.clone(); } static ValueFieldsQuery create() { return new ValueFieldsQuery(new DataModel.Producer.Values()); } } @Test public void testFields() { HashIndex<DataModel.Consumer.Values, ValueFieldsQuery> hi = HashIndex .from(consumer, DataModel.Consumer.Values.class) .usingBean(ValueFieldsQuery.class); List<DataModel.Consumer.Values> r = hi.findMatches(ValueFieldsQuery.create()) .collect(toList()); Assert.assertEquals(1, r.size()); Assert.assertEquals(0, r.get(0).getOrdinal()); } @SuppressWarnings("unused") static class ValueMethodsQuery { boolean _boolean; byte _byte; short _short; char _char; int _int; long _long; float _float; double _double; byte[] _bytes; char[] _chars; @FieldPath("_boolean") boolean is_boolean() { return _boolean; } @FieldPath("_byte") byte get_byte() { return _byte; } @FieldPath("_short") short get_short() { return _short; } @FieldPath("_char") char get_char() { return _char; } @FieldPath("_int") int get_int() { return _int; } @FieldPath("_long") long get_long() { return _long; } @FieldPath("_float") float get_float() { return _float; } @FieldPath("_double") double get_double() { return _double; } @FieldPath("_bytes") byte[] get_bytes() { return _bytes; } @FieldPath("_chars") char[] get_chars() { return _chars; } ValueMethodsQuery(DataModel.Producer.Values v) { this._boolean = v._boolean; this._byte = v._byte; this._short = v._short; this._char = v._char; this._int = v._int; this._long = v._long; this._float = v._float; this._double = v._double; this._bytes = v._bytes.clone(); this._chars = v._chars.clone(); } static ValueMethodsQuery create() { return new ValueMethodsQuery(new DataModel.Producer.Values()); } } @Test public void testMethods() { HashIndex<DataModel.Consumer.Values, ValueMethodsQuery> hi = HashIndex .from(consumer, DataModel.Consumer.Values.class) .usingBean(ValueMethodsQuery.class); List<DataModel.Consumer.Values> r = hi.findMatches(ValueMethodsQuery.create()) .collect(toList()); Assert.assertEquals(1, r.size()); Assert.assertEquals(0, r.get(0).getOrdinal()); } } // path, type, value private static List<Object[]> boxesDataProvider() { DataModel.Producer.Boxes values = new DataModel.Producer.Boxes(); return Stream.of(DataModel.Producer.Boxes.class.getDeclaredFields()) .map(f -> { String path = f.getName() + ".value"; Class<?> type = f.getType(); Object value; try { value = f.get(values); } catch (IllegalAccessException e) { throw new InternalError(); } return new Object[] {path, type, value}; }) .collect(toList()); } @RunWith(Parameterized.class) public static class MatchOnBoxesValuesTest<Q> extends MatchTestParameterized<DataModel.Consumer.Boxes, Q> { // path[type] = value @Parameters(name = "{index}: {0}[{1}] = {2}") public static Collection<Object[]> data() { return boxesDataProvider(); } public MatchOnBoxesValuesTest(String path, Class<Q> type, Q value) { super(path, type, value, DataModel.Consumer.Boxes.class); } } private static List<Object[]> inlineBoxesDataProvider() { DataModel.Producer.InlineBoxes values = new DataModel.Producer.InlineBoxes(); return Stream.of(DataModel.Producer.InlineBoxes.class.getDeclaredFields()) .map(f -> { String path = f.getName(); Class<?> type = f.getType(); Object value; try { value = f.get(values); } catch (IllegalAccessException e) { throw new InternalError(); } return new Object[] {path, type, value}; }) .collect(toList()); } @RunWith(Parameterized.class) public static class MatchOnInlineBoxesTest<Q> extends MatchTestParameterized<DataModel.Consumer.InlineBoxes, Q> { // path[type] = value @Parameters(name = "{index}: {0}[{1}] = {2}") public static Collection<Object[]> data() { return inlineBoxesDataProvider(); } public MatchOnInlineBoxesTest(String path, Class<Q> type, Q value) { super(path, type, value, DataModel.Consumer.InlineBoxes.class); } } @RunWith(Parameterized.class) public static class MatchOnMappedReferencesTest<Q> extends MatchTestParameterized<DataModel.Consumer.MappedReferencesToValues, Q> { // path[type] = value @Parameters(name = "{index}: {0}[{1}] = {2}") public static Collection<Object[]> data() { return Arrays.asList( new Object[] {"date.value", long.class, 0L}, new Object[] {"number._name", String.class, "ONE"} ); } public MatchOnMappedReferencesTest(String path, Class<Q> type, Q value) { super(path, type, value, DataModel.Consumer.MappedReferencesToValues.class); } } @RunWith(Parameterized.class) public static class MatchOnReferencesTest<Q extends HollowRecord> extends HashIndexTest { @Parameters(name = "{index}: {0}[{1} = {2}]") public static Collection<Object[]> data() { return Arrays.asList( args("values", DataModel.Consumer.Values.class, () -> api.getValues(0)), args("boxes._string", DataModel.Consumer.HString.class, () -> api.getHString(0)), args("sequences.list", DataModel.Consumer.ListOfBoxes.class, () -> api.getListOfBoxes(0)), args("sequences.map.key._string", DataModel.Consumer.HString.class, () -> api.getHString(0)), args("referenceWithStrings", DataModel.Consumer.ReferenceWithStringsRenamed.class, () -> api.getReferenceWithStringsRenamed(0)), args("referenceWithStrings._string1", DataModel.Consumer.HString.class, () -> api.getHString(0)), args("referenceWithStrings._string2", DataModel.Consumer.FieldOfStringRenamed.class, () -> api.getFieldOfStringRenamed(0)) ); } static <Q extends HollowRecord> Object[] args(String path, Class<Q> type, Supplier<Q> s) { return new Object[] {path, type, s}; } final String path; final Class<Q> type; final Q value; public MatchOnReferencesTest(String path, Class<Q> type, Supplier<Q> value) { this.path = path; this.type = type; this.value = value.get(); } @Test public void test() { HashIndex<DataModel.Consumer.References, Q> hi = HashIndex .from(consumer, DataModel.Consumer.References.class) .usingPath(path, type); List<DataModel.Consumer.References> r = hi.findMatches(value) .collect(toList()); Assert.assertEquals(1, r.size()); Assert.assertEquals(0, r.get(0).getOrdinal()); } } @RunWith(Parameterized.class) public static class SelectOnValuesTest extends HashIndexTest { // path[type] = value @Parameters(name = "{index}: {0}[{1}] = {2}") public static Collection<Object[]> data() { return valuesDataProvider(); } final String path; final Class<?> type; final Object value; public SelectOnValuesTest(String path, Class<?> type, Object value) { this.path = path; this.type = type; this.value = value; } @Test(expected = IllegalArgumentException.class) public void test() { HashIndex .from(consumer, DataModel.Consumer.Values.class) .selectField(path, GenericHollowObject.class) .usingPath("values._int", int.class); } } @RunWith(Parameterized.class) public static class SelectTest<S extends HollowRecord> extends HashIndexTest { @Parameters(name = "{index}: {0}[{1}]") public static Collection<Object[]> data() { return Arrays.asList( args("boxes._string", DataModel.Consumer.HString.class), args("boxes._string", GenericHollowObject.class), args("sequences.list", DataModel.Consumer.ListOfBoxes.class), args("sequences.list.element", DataModel.Consumer.Boxes.class), args("sequences.list.element._string", DataModel.Consumer.HString.class), args("sequences.set", DataModel.Consumer.SetOfBoxes.class), args("sequences.set.element", DataModel.Consumer.Boxes.class), args("sequences.set.element._string", DataModel.Consumer.HString.class), args("sequences.map", DataModel.Consumer.MapOfBoxesToBoxes.class), args("sequences.map.key", DataModel.Consumer.Boxes.class), args("sequences.map.key._string", DataModel.Consumer.HString.class), args("sequences.map.value", DataModel.Consumer.Boxes.class), args("sequences.map.value._string", DataModel.Consumer.HString.class), args("referenceWithStrings", DataModel.Consumer.ReferenceWithStringsRenamed.class), args("referenceWithStrings._string1", DataModel.Consumer.HString.class), args("referenceWithStrings._string2", DataModel.Consumer.FieldOfStringRenamed.class) ); } static <S extends HollowRecord> Object[] args(String path, Class<S> type) { return new Object[] {path, type}; } final String path; final Class<S> type; public SelectTest(String path, Class<S> type) { this.path = path; this.type = type; } @Test public void test() { HashIndexSelect<DataModel.Consumer.References, S, Integer> hi = HashIndex .from(consumer, DataModel.Consumer.References.class) .selectField(path, type) .usingPath("values._int", int.class); List<S> r = hi.findMatches(1) .collect(toList()); Assert.assertEquals(1, r.size()); Assert.assertTrue(type.isInstance(r.get(0))); Assert.assertEquals(0, r.get(0).getOrdinal()); } } public static class TestManyMatches extends HashIndexTest { @Test public void test() { HashIndex<DataModel.Consumer.TypeA, Integer> hi = HashIndex .from(consumer, DataModel.Consumer.TypeA.class) .usingPath("i", int.class); List<DataModel.Consumer.TypeA> r = hi.findMatches(1) .sorted(Comparator.comparingInt(HollowObject::getOrdinal)).collect(toList()); Assert.assertEquals(100, r.size()); for (int i = 0; i < r.size(); i++) { Assert.assertEquals(i, r.get(i).getOrdinal()); } } @Test public void testTypeAWithSelect() { HashIndexSelect<DataModel.Consumer.TypeA, DataModel.Consumer.HString, Integer> hi = HashIndex .from(consumer, DataModel.Consumer.TypeA.class) .selectField("s", DataModel.Consumer.HString.class) .usingPath("i", int.class); List<String> r = hi.findMatches(1) .sorted(Comparator.comparingInt(HollowObject::getOrdinal)) .map(DataModel.Consumer.HString::getValue) .collect(toList()); Assert.assertEquals(100, r.size()); for (int i = 0; i < r.size(); i++) { Assert.assertEquals("TypeA" + i, r.get(i)); } } @Test public void testTypeBWithSelect() { HashIndexSelect<DataModel.Consumer.TypeBSuffixed, DataModel.Consumer.HString, Integer> hi = HashIndex .from(consumer, DataModel.Consumer.TypeBSuffixed.class) .selectField("s", DataModel.Consumer.HString.class) .usingPath("i", int.class); List<String> r = hi.findMatches(1) .sorted(Comparator.comparingInt(HollowObject::getOrdinal)) .map(DataModel.Consumer.HString::getValue) .collect(toList()); Assert.assertEquals(100, r.size()); for (int i = 0; i < r.size(); i++) { Assert.assertEquals("TypeB" + i, r.get(i)); } } @Test public void testWithSelectRootTypeGenericHollowObject() { HashIndexSelect<DataModel.Consumer.TypeA, GenericHollowObject, Integer> hi = HashIndex .from(consumer, DataModel.Consumer.TypeA.class) .selectField("", GenericHollowObject.class) .usingPath("i", int.class); boolean r = hi.findMatches(1) .sorted(Comparator.comparingInt(HollowObject::getOrdinal)) .mapToInt(gho -> gho.getInt("i")) .allMatch(i -> i == 1); Assert.assertTrue(r); } @Test public void testWithSelectGenericHollowObject() { HashIndexSelect<DataModel.Consumer.TypeA, GenericHollowObject, Integer> hi = HashIndex .from(consumer, DataModel.Consumer.TypeA.class) .selectField("s", GenericHollowObject.class) .usingPath("i", int.class); List<String> r = hi.findMatches(1) .sorted(Comparator.comparingInt(HollowObject::getOrdinal)) .map(gho -> gho.getString("value")) .collect(toList()); Assert.assertEquals(100, r.size()); for (int i = 0; i < r.size(); i++) { Assert.assertEquals("TypeA" + i, r.get(i)); } } } public static class ErrorsTest extends HashIndexTest { static class Unknown extends HollowObject { Unknown(HollowObjectDelegate delegate, int ordinal) { super(delegate, ordinal); } } @Test(expected = IllegalArgumentException.class) public void testUnknownRootSelectType() { HashIndex .from(consumer, Unknown.class) .usingPath("values", DataModel.Consumer.Values.class); } @Test(expected = IllegalArgumentException.class) public void testUnknownSelectType() { HashIndex .from(consumer, DataModel.Consumer.References.class) .selectField("values", Unknown.class) .usingPath("values", DataModel.Consumer.Values.class); } @Test(expected = IllegalArgumentException.class) public void testEmptyMatchPath() { HashIndex .from(consumer, DataModel.Consumer.References.class) .usingPath("", DataModel.Consumer.References.class); } } public static class GeneratedSuffixTest extends HashIndexTest { @Test public void testMatch() { HashIndex<DataModel.Consumer.TypeBSuffixed, Integer> hi = HashIndex .from(consumer, DataModel.Consumer.TypeBSuffixed.class) .usingPath("i", int.class); List<DataModel.Consumer.TypeBSuffixed> r = hi.findMatches(1) .sorted(Comparator.comparingInt(HollowObject::getOrdinal)).collect(toList()); Assert.assertEquals(100, r.size()); for (int i = 0; i < r.size(); i++) { Assert.assertEquals(i, r.get(i).getOrdinal()); } } @Test public void testSelect() { HashIndexSelect<DataModel.Consumer.TypeWithTypeB, DataModel.Consumer.TypeBSuffixed, String> his = HashIndex.from(consumer, DataModel.Consumer.TypeWithTypeB.class) .selectField("typeB", DataModel.Consumer.TypeBSuffixed.class) .usingPath("foo.value", String.class); List<Integer> r = his.findMatches("foo") .map(HollowObject::getOrdinal).sorted().collect(Collectors.toList()); Assert.assertEquals(Arrays.asList(101, 102), r); } @Test public void testSelectRootTypeSuffixed() { HashIndexSelect<DataModel.Consumer.TypeBSuffixed, DataModel.Consumer.HString, Integer> his = HashIndex.from(consumer, DataModel.Consumer.TypeBSuffixed.class) .selectField("s", DataModel.Consumer.HString.class) .usingPath("i", int.class); List<Integer> r = his.findMatches(7) .map(HollowObject::getOrdinal).sorted().collect(Collectors.toList()); Assert.assertEquals(Arrays.asList(203, 206), r); } } }
8,866
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/index/UniqueKeyUpdatesTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.consumer.index; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowInMemoryBlobStager; import com.netflix.hollow.test.InMemoryBlobStore; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class UniqueKeyUpdatesTest { InMemoryBlobStore blobStore; @Before public void setUp() { blobStore = new InMemoryBlobStore(); } static class Key { @FieldPath("i") int i; @FieldPath("sub1.s") String sub1_s; @FieldPath("sub2.i") int sub2_i; Key(int i, String sub1_s, int sub2_i) { this.i = i; this.sub1_s = sub1_s; this.sub2_i = sub2_i; } } void updates(boolean doubleSnapshot) { HollowProducer producer = HollowProducer.withPublisher(blobStore) .withBlobStager(new HollowInMemoryBlobStager()) .build(); long v1 = producer.runCycle(ws -> { ws.add(new DataModel.Producer.TypeWithPrimaryKey( 1, new DataModel.Producer.SubTypeOfTypeWithPrimaryKey("1", 1), new DataModel.Producer.SubTypeOfTypeWithPrimaryKey("2", 2))); }); HollowConsumer consumer = HollowConsumer.withBlobRetriever(blobStore) .withGeneratedAPIClass(DataModel.Consumer.Api.class) .build(); consumer.triggerRefreshTo(v1); UniqueKeyIndex<DataModel.Consumer.TypeWithPrimaryKey, Key> uki = UniqueKeyIndex.from(consumer, DataModel.Consumer.TypeWithPrimaryKey.class) .bindToPrimaryKey() .usingBean(Key.class); consumer.addRefreshListener(uki); Assert.assertNotNull(uki.findMatch(new Key(1, "1", 2))); long v2 = producer.runCycle(ws -> { ws.add(new DataModel.Producer.TypeWithPrimaryKey( 1, new DataModel.Producer.SubTypeOfTypeWithPrimaryKey("1", 1), new DataModel.Producer.SubTypeOfTypeWithPrimaryKey("2", 2))); ws.add(new DataModel.Producer.TypeWithPrimaryKey( 2, new DataModel.Producer.SubTypeOfTypeWithPrimaryKey("1", 1), new DataModel.Producer.SubTypeOfTypeWithPrimaryKey("2", 2))); }); if (doubleSnapshot) { consumer.forceDoubleSnapshotNextUpdate(); } consumer.triggerRefreshTo(v2); Assert.assertNotNull(uki.findMatch(new Key(1, "1", 2))); Assert.assertNotNull(uki.findMatch(new Key(2, "1", 2))); consumer.removeRefreshListener(uki); long v3 = producer.runCycle(ws -> { ws.add(new DataModel.Producer.TypeWithPrimaryKey( 1, new DataModel.Producer.SubTypeOfTypeWithPrimaryKey("1", 1), new DataModel.Producer.SubTypeOfTypeWithPrimaryKey("2", 2))); ws.add(new DataModel.Producer.TypeWithPrimaryKey( 2, new DataModel.Producer.SubTypeOfTypeWithPrimaryKey("1", 1), new DataModel.Producer.SubTypeOfTypeWithPrimaryKey("2", 2))); ws.add(new DataModel.Producer.TypeWithPrimaryKey( 3, new DataModel.Producer.SubTypeOfTypeWithPrimaryKey("1", 1), new DataModel.Producer.SubTypeOfTypeWithPrimaryKey("2", 2))); }); if (doubleSnapshot) { consumer.forceDoubleSnapshotNextUpdate(); } consumer.triggerRefreshTo(v3); Assert.assertNotNull(uki.findMatch(new Key(1, "1", 2))); Assert.assertNotNull(uki.findMatch(new Key(2, "1", 2))); Assert.assertNull(uki.findMatch(new Key(3, "1", 2))); } @Test public void deltaUpdates() { updates(false); } @Test public void snapshotUpdates() { updates(true); } }
8,867
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/index/DataModel.java
package com.netflix.hollow.api.consumer.index; import com.netflix.hollow.api.custom.HollowAPI; import com.netflix.hollow.api.objects.HollowList; import com.netflix.hollow.api.objects.HollowMap; import com.netflix.hollow.api.objects.HollowObject; import com.netflix.hollow.api.objects.HollowSet; import com.netflix.hollow.api.objects.delegate.HollowListDelegate; import com.netflix.hollow.api.objects.delegate.HollowMapDelegate; import com.netflix.hollow.api.objects.delegate.HollowObjectDelegate; import com.netflix.hollow.api.objects.delegate.HollowObjectGenericDelegate; import com.netflix.hollow.api.objects.delegate.HollowSetDelegate; import com.netflix.hollow.api.objects.provider.HollowFactory; import com.netflix.hollow.core.read.dataaccess.HollowDataAccess; import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess; import com.netflix.hollow.core.write.objectmapper.HollowInline; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import com.netflix.hollow.core.write.objectmapper.HollowTypeName; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class DataModel { static class Producer { public static class Values { final boolean _boolean; final byte _byte; final short _short; final char _char; final int _int; final long _long; final float _float; final double _double; final byte[] _bytes; final char[] _chars; public Values() { this._boolean = true; this._byte = 1; this._short = 1; this._char = 1; this._int = 1; this._long = 1L; this._float = 1.0f; this._double = 1.0d; this._bytes = new byte[] {1}; this._chars = "1".toCharArray(); } } public static class Boxes { final Boolean _boolean; final Byte _byte; final Short _short; final Character _char; final Integer _int; final Long _long; final Float _float; final Double _double; final String _string; public Boxes() { this._boolean = true; this._byte = 1; this._short = 1; this._char = 1; this._int = 1; this._long = 1L; this._float = 1.0f; this._double = 1.0d; this._string = "1"; } } public static class InlineBoxes { @HollowInline final Boolean _boolean; @HollowInline final Byte _byte; @HollowInline final Short _short; @HollowInline final Character _char; @HollowInline final Integer _int; @HollowInline final Long _long; @HollowInline final Float _float; @HollowInline final Double _double; @HollowInline final String _string; public InlineBoxes() { this._boolean = true; this._byte = 1; this._short = 1; this._char = 1; this._int = 1; this._long = 1L; this._float = 1.0f; this._double = 1.0d; this._string = "1"; } } public static class MappedReferencesToValues { enum Number { ONE, TWO } final Date date; final Number number; public MappedReferencesToValues() { this.date = new Date(0); this.number = Number.ONE; } } @HollowTypeName(name = "ReferenceWithStringsRenamed") public static class ReferenceWithStrings { final String _string1; @HollowTypeName(name = "FieldOfStringRenamed") final String _string2; public ReferenceWithStrings() { this._string1 = "1"; this._string2 = "1"; } } public static class TypeA { final int i; final String s; public TypeA(int i, String s) { this.i = i; this.s = s; } } public static class TypeB { final int i; final String s; public TypeB(int i, String s) { this.i = i; this.s = s; } } @HollowPrimaryKey(fields = {"i", "sub1.s", "sub2.i"}) public static class TypeWithPrimaryKey { final int i; final SubTypeOfTypeWithPrimaryKey sub1; final SubTypeOfTypeWithPrimaryKey sub2; public TypeWithPrimaryKey( int i, SubTypeOfTypeWithPrimaryKey sub1, SubTypeOfTypeWithPrimaryKey sub2) { this.i = i; this.sub1 = sub1; this.sub2 = sub2; } } public static class TypeWithTypeB { final String foo; final TypeB typeB; public TypeWithTypeB(String foo, TypeB typeB) { this.foo = foo; this.typeB = typeB; } } public static class SubTypeOfTypeWithPrimaryKey { final String s; final int i; public SubTypeOfTypeWithPrimaryKey(String s, int i) { this.s = s; this.i = i; } } @HollowPrimaryKey(fields = {"i"}) public static class TypeWithPrimaryKey2 { final int i; public TypeWithPrimaryKey2(int i) { this.i = i; } } public static class Sequences { final List<Boxes> list; final Set<Boxes> set; final Map<Boxes, Boxes> map; public Sequences() { this.list = new ArrayList<>(Arrays.asList(new Boxes())); this.set = new HashSet<>(list); this.map = new HashMap<>(); map.put(new Boxes(), new Boxes()); } } public static class References { final Values values; final Boxes boxes; final InlineBoxes inlineBoxes; final MappedReferencesToValues mapped; final Sequences sequences; final ReferenceWithStrings referenceWithStrings; final TypeWithPrimaryKey typeWithPrimaryKey; public References() { this.values = new Values(); this.boxes = new Boxes(); this.inlineBoxes = new InlineBoxes(); this.mapped = new MappedReferencesToValues(); this.sequences = new Sequences(); this.referenceWithStrings = new ReferenceWithStrings(); this.typeWithPrimaryKey = new TypeWithPrimaryKey(1, new SubTypeOfTypeWithPrimaryKey("1", 1), new SubTypeOfTypeWithPrimaryKey("2", 2)); } } } public static class Consumer { public static class Api extends HollowAPI { private final HollowObjectTypeDataAccess stringTypeDataAccess; private final HollowObjectGenericDelegate stringDelegate; private final HollowObjectTypeDataAccess fieldOfStringRenamedTypeDataAccess; private final HollowObjectGenericDelegate fieldOfStringRenamedDelegate; public Api(HollowDataAccess dataAccess) { this(dataAccess, Collections.<String>emptySet()); } public Api(HollowDataAccess dataAccess, Set<String> cachedTypes) { this(dataAccess, cachedTypes, Collections.<String, HollowFactory<?>>emptyMap()); } public Api( HollowDataAccess dataAccess, Set<String> cachedTypes, Map<String, HollowFactory<?>> factoryOverrides) { this(dataAccess, cachedTypes, factoryOverrides, null); } public Api( HollowDataAccess dataAccess, Set<String> cachedTypes, Map<String, HollowFactory<?>> factoryOverrides, Api previousCycleAPI) { super(dataAccess); this.stringTypeDataAccess = (HollowObjectTypeDataAccess) dataAccess.getTypeDataAccess("String"); this.stringDelegate = new HollowObjectGenericDelegate(stringTypeDataAccess); this.fieldOfStringRenamedTypeDataAccess = (HollowObjectTypeDataAccess) dataAccess.getTypeDataAccess( "FieldOfStringRenamed"); this.fieldOfStringRenamedDelegate = new HollowObjectGenericDelegate(fieldOfStringRenamedTypeDataAccess); } public HString getHString(int ordinal) { return new HString(stringDelegate, ordinal); } public Values getValues(int ordinal) { return new Values(null, ordinal); } public Boxes getBoxes(int ordinal) { return new Boxes(null, ordinal); } public InlineBoxes getInlineBoxes(int ordinal) { return new InlineBoxes(null, ordinal); } public MappedReferencesToValues getMappedReferencesToValues(int ordinal) { return new MappedReferencesToValues(null, ordinal); } public ReferenceWithStringsRenamed getReferenceWithStringsRenamed(int ordinal) { return new ReferenceWithStringsRenamed(null, ordinal); } public FieldOfStringRenamed getFieldOfStringRenamed(int ordinal) { return new FieldOfStringRenamed(fieldOfStringRenamedDelegate, ordinal); } public TypeA getTypeA(int ordinal) { return new TypeA(null, ordinal); } public TypeBSuffixed getTypeBSuffixed(int ordinal) { return new TypeBSuffixed(null, ordinal); } public TypeWithPrimaryKey getTypeWithPrimaryKey(int ordinal) { return new TypeWithPrimaryKey(null, ordinal); } public SubTypeOfTypeWithPrimaryKey getSubTypeOfTypeWithPrimaryKey(int ordinal) { return new SubTypeOfTypeWithPrimaryKey(null, ordinal); } public TypeWithPrimaryKeySuffixed getTypeWithPrimaryKeySuffixed(int ordinal) { return new TypeWithPrimaryKeySuffixed(null, ordinal); } public ListOfBoxes getListOfBoxes(int ordinal) { return new ListOfBoxes(null, ordinal); } public SetOfBoxes getSetOfBoxes(int ordinal) { return new SetOfBoxes(null, ordinal); } public MapOfBoxesToBoxes getMapOfBoxesToBoxes(int ordinal) { return new MapOfBoxesToBoxes(null, ordinal); } public References getReferences(int ordinal) { return new References(null, ordinal); } } public static class HString extends HollowObject { public HString(HollowObjectDelegate delegate, int ordinal) { super(delegate, ordinal); } public String getValue() { return ((HollowObjectGenericDelegate) getDelegate()).getString(getOrdinal(), "value"); } } public static class Values extends HollowObject { public Values(HollowObjectDelegate delegate, int ordinal) { super(delegate, ordinal); } } public static class Boxes extends HollowObject { public Boxes(HollowObjectDelegate delegate, int ordinal) { super(delegate, ordinal); } } public static class InlineBoxes extends HollowObject { public InlineBoxes(HollowObjectDelegate delegate, int ordinal) { super(delegate, ordinal); } } public static class MappedReferencesToValues extends HollowObject { public MappedReferencesToValues(HollowObjectDelegate delegate, int ordinal) { super(delegate, ordinal); } } public static class ReferenceWithStringsRenamed extends HollowObject { public ReferenceWithStringsRenamed(HollowObjectDelegate delegate, int ordinal) { super(delegate, ordinal); } } public static class FieldOfStringRenamed extends HollowObject { public FieldOfStringRenamed(HollowObjectDelegate delegate, int ordinal) { super(delegate, ordinal); } public String getValue() { return ((HollowObjectGenericDelegate) getDelegate()).getString(0, "value"); } } public static class TypeA extends HollowObject { public TypeA(HollowObjectDelegate delegate, int ordinal) { super(delegate, ordinal); } } @HollowTypeName(name = "TypeB") public static class TypeBSuffixed extends HollowObject { public TypeBSuffixed(HollowObjectDelegate delegate, int ordinal) { super(delegate, ordinal); } } public static class TypeWithPrimaryKey extends HollowObject { public TypeWithPrimaryKey(HollowObjectDelegate delegate, int ordinal) { super(delegate, ordinal); } } public static class TypeWithTypeB extends HollowObject { public TypeWithTypeB(HollowObjectDelegate delegate, int ordinal) { super(delegate, ordinal); } } public static class SubTypeOfTypeWithPrimaryKey extends HollowObject { public SubTypeOfTypeWithPrimaryKey(HollowObjectDelegate delegate, int ordinal) { super(delegate, ordinal); } } @HollowTypeName(name = "TypeWithPrimaryKey2") public static class TypeWithPrimaryKeySuffixed extends HollowObject { public TypeWithPrimaryKeySuffixed(HollowObjectDelegate delegate, int ordinal) { super(delegate, ordinal); } } public static class ListOfBoxes extends HollowList<Boxes> { public ListOfBoxes(HollowListDelegate<Boxes> delegate, int ordinal) { super(delegate, ordinal); } @Override public Boxes instantiateElement(int ordinal) { throw new UnsupportedOperationException(); } @Override public boolean equalsElement(int elementOrdinal, Object testObject) { throw new UnsupportedOperationException(); } } public static class SetOfBoxes extends HollowSet<Boxes> { public SetOfBoxes(HollowSetDelegate<Boxes> delegate, int ordinal) { super(delegate, ordinal); } @Override public Boxes instantiateElement(int ordinal) { throw new UnsupportedOperationException(); } @Override public boolean equalsElement(int elementOrdinal, Object testObject) { throw new UnsupportedOperationException(); } } public static class MapOfBoxesToBoxes extends HollowMap<Boxes, Boxes> { public MapOfBoxesToBoxes(HollowMapDelegate<Boxes, Boxes> delegate, int ordinal) { super(delegate, ordinal); } @Override public Boxes instantiateKey(int ordinal) { throw new UnsupportedOperationException(); } @Override public Boxes instantiateValue(int ordinal) { throw new UnsupportedOperationException(); } @Override public boolean equalsKey(int keyOrdinal, Object testObject) { throw new UnsupportedOperationException(); } @Override public boolean equalsValue(int valueOrdinal, Object testObject) { throw new UnsupportedOperationException(); } } public static class References extends HollowObject { public References(HollowObjectDelegate delegate, int ordinal) { super(delegate, ordinal); } } } }
8,868
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/fs/HollowFilesystemConsumerTest.java
package com.netflix.hollow.api.consumer.fs; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.api.producer.HollowProducer; import com.netflix.hollow.api.producer.fs.HollowFilesystemPublisher; import com.netflix.hollow.core.write.objectmapper.HollowPrimaryKey; import java.io.File; import java.io.IOException; import java.nio.file.Files; import org.junit.Assert; import org.junit.Test; public class HollowFilesystemConsumerTest { @Test public void testHollowFilesystemConsumer() throws IOException { File localDir = createLocalDir(); HollowFilesystemPublisher pub = new HollowFilesystemPublisher(localDir.toPath()); HollowProducer producer = HollowProducer.withPublisher(pub) .withNumStatesBetweenSnapshots(2) .build(); producer.runCycle(state -> { state.add(new Entity(1)); state.add(new Entity(2)); state.add(new Entity(3)); }); long deltaVersion = producer.runCycle(state -> { state.add(new Entity(1)); state.add(new Entity(2)); state.add(new Entity(3)); state.add(new Entity(4)); }); HollowFilesystemBlobRetriever retriever = new HollowFilesystemBlobRetriever(localDir.toPath()); HollowConsumer consumer = HollowConsumer.newHollowConsumer().withBlobRetriever(retriever).build(); consumer.triggerRefreshTo(deltaVersion); GenericHollowObject obj1 = new GenericHollowObject(consumer.getStateEngine(), "Entity", 0); GenericHollowObject obj4 = new GenericHollowObject(consumer.getStateEngine(), "Entity", 3); Assert.assertEquals(1, obj1.getInt("id")); Assert.assertEquals(4, obj4.getInt("id")); } static File createLocalDir() throws IOException { File localDir = Files.createTempDirectory("hollow_fs").toFile(); localDir.deleteOnExit(); return localDir; } @HollowPrimaryKey(fields="id") public static class Entity { @SuppressWarnings("unused") private final int id; public Entity(int id) { this.id = id; } } }
8,869
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/data/LongDataAccessorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.api.consumer.data; import com.netflix.hollow.api.objects.delegate.HollowObjectGenericDelegate; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.type.accessor.LongDataAccessor; import java.io.IOException; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; public class LongDataAccessorTest extends AbstractPrimitiveTypeDataAccessorTest<Long> { @Override protected Class<Long> getDataModelTestClass() { return Long.class; } @Override protected Long getData(HollowObjectTypeReadState readState, int ordinal) { GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(readState), ordinal); return obj.getLong("value"); } @Test public void test() throws IOException { addRecord(new Long(1)); addRecord(new Long(2)); addRecord(new Long(3)); roundTripSnapshot(); { LongDataAccessor dAccessor = new LongDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(3, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.<Long>asList(new Long(1), new Long(2), new Long(3))); Assert.assertTrue(dAccessor.getRemovedRecords().isEmpty()); Assert.assertTrue(dAccessor.getUpdatedRecords().isEmpty()); } writeStateEngine.prepareForNextCycle(); /// not necessary to call, but needs to be a no-op. addRecord(new Long(1)); // addRecord(new Long(2)); // removed addRecord(new Long(3)); addRecord(new Long(1000)); // added addRecord(new Long(0)); // added roundTripDelta(); { LongDataAccessor dAccessor = new LongDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(2, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.asList(new Long(1000), new Long(0))); Assert.assertEquals(1, dAccessor.getRemovedRecords().size()); assertList(dAccessor.getRemovedRecords(), Arrays.asList(new Long(2))); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("Long"); Assert.assertEquals(4, typeState.maxOrdinal()); assertObject(typeState, 0, new Long(1)); assertObject(typeState, 1, new Long(2)); /// this was "removed", but the data hangs around as a "ghost" until the following cycle. assertObject(typeState, 2, new Long(3)); assertObject(typeState, 3, new Long(1000)); assertObject(typeState, 4, new Long(0)); roundTripDelta(); // remove everything { LongDataAccessor dAccessor = new LongDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(0, dAccessor.getAddedRecords().size()); Assert.assertEquals(4, dAccessor.getRemovedRecords().size()); assertList(dAccessor.getRemovedRecords(), Arrays.asList(new Long(1), new Long(3), new Long(1000), new Long(0))); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } assertObject(typeState, 0, new Long(1)); /// all records were "removed", but again hang around until the following cycle. // assertObject(typeState, 1, new Long(2)); /// this record should now be disappeared. assertObject(typeState, 2, new Long(3)); /// "ghost" assertObject(typeState, 3, new Long(1000)); /// "ghost" assertObject(typeState, 4, new Long(0)); /// "ghost" Assert.assertEquals(4, typeState.maxOrdinal()); addRecord(new Long(634)); addRecord(new Long(0)); roundTripDelta(); { LongDataAccessor dAccessor = new LongDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(2, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.asList(new Long(634), new Long(0))); Assert.assertEquals(0, dAccessor.getRemovedRecords().size()); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } Assert.assertEquals(1, typeState.maxOrdinal()); assertObject(typeState, 0, new Long(634)); /// now, since all records were removed, we can recycle the ordinal "0", even though it was a "ghost" in the last cycle. assertObject(typeState, 1, new Long(0)); /// even though new Long(0) had an equivalent record in the previous cycle at ordinal "4", it is now assigned to recycled ordinal "1". } }
8,870
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/data/StringDataAccessorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.api.consumer.data; import com.netflix.hollow.api.objects.delegate.HollowObjectGenericDelegate; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.type.accessor.StringDataAccessor; import java.io.IOException; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; public class StringDataAccessorTest extends AbstractPrimitiveTypeDataAccessorTest<String> { @Override protected Class<String> getDataModelTestClass() { return String.class; } @Override protected String getData(HollowObjectTypeReadState readState, int ordinal) { GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(readState), ordinal); return obj.getString("value"); } @Test public void test() throws IOException { addRecord("one"); addRecord("two"); addRecord("three"); roundTripSnapshot(); { StringDataAccessor dAccessor = new StringDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(3, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.<String>asList("one", "two", "three")); Assert.assertTrue(dAccessor.getRemovedRecords().isEmpty()); Assert.assertTrue(dAccessor.getUpdatedRecords().isEmpty()); } writeStateEngine.prepareForNextCycle(); /// not necessary to call, but needs to be a no-op. addRecord("one"); // addRecord("two"); // removed addRecord("three"); addRecord("one thousand"); // added addRecord("zero"); // added roundTripDelta(); { StringDataAccessor dAccessor = new StringDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(2, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.asList("one thousand", "zero")); Assert.assertEquals(1, dAccessor.getRemovedRecords().size()); assertList(dAccessor.getRemovedRecords(), Arrays.asList("two")); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("String"); Assert.assertEquals(4, typeState.maxOrdinal()); assertObject(typeState, 0, "one"); assertObject(typeState, 1, "two"); /// this was "removed", but the data hangs around as a "ghost" until the following cycle. assertObject(typeState, 2, "three"); assertObject(typeState, 3, "one thousand"); assertObject(typeState, 4, "zero"); roundTripDelta(); // remove everything { StringDataAccessor dAccessor = new StringDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(0, dAccessor.getAddedRecords().size()); Assert.assertEquals(4, dAccessor.getRemovedRecords().size()); assertList(dAccessor.getRemovedRecords(), Arrays.asList("one", "three", "one thousand", "zero")); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } assertObject(typeState, 0, "one"); /// all records were "removed", but again hang around until the following cycle. // assertObject(typeState, 1, "two"); /// this record should now be disappeared. assertObject(typeState, 2, "three"); /// "ghost" assertObject(typeState, 3, "one thousand"); /// "ghost" assertObject(typeState, 4, "zero"); /// "ghost" Assert.assertEquals(4, typeState.maxOrdinal()); addRecord("six hundred thirty four"); addRecord("zero"); roundTripDelta(); { StringDataAccessor dAccessor = new StringDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(2, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.asList("six hundred thirty four", "zero")); Assert.assertEquals(0, dAccessor.getRemovedRecords().size()); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } Assert.assertEquals(1, typeState.maxOrdinal()); assertObject(typeState, 0, "six hundred thirty four"); /// now, since all records were removed, we can recycle the ordinal "0", even though it was a "ghost" in the last cycle. assertObject(typeState, 1, "zero"); /// even though "zero" had an equivalent record in the previous cycle at ordinal "4", it is now assigned to recycled ordinal "1". } }
8,871
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/data/FloatDataAccessorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.api.consumer.data; import com.netflix.hollow.api.objects.delegate.HollowObjectGenericDelegate; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.type.accessor.FloatDataAccessor; import java.io.IOException; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; public class FloatDataAccessorTest extends AbstractPrimitiveTypeDataAccessorTest<Float> { @Override protected Class<Float> getDataModelTestClass() { return Float.class; } @Override protected Float getData(HollowObjectTypeReadState readState, int ordinal) { GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(readState), ordinal); return obj.getFloat("value"); } @Test public void test() throws IOException { addRecord(new Float(1)); addRecord(new Float(2)); addRecord(new Float(3)); roundTripSnapshot(); { FloatDataAccessor dAccessor = new FloatDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(3, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.<Float>asList(new Float(1), new Float(2), new Float(3))); Assert.assertTrue(dAccessor.getRemovedRecords().isEmpty()); Assert.assertTrue(dAccessor.getUpdatedRecords().isEmpty()); } writeStateEngine.prepareForNextCycle(); /// not necessary to call, but needs to be a no-op. addRecord(new Float(1)); // addRecord(new Float(2)); // removed addRecord(new Float(3)); addRecord(new Float(1000)); // added addRecord(new Float(0)); // added roundTripDelta(); { FloatDataAccessor dAccessor = new FloatDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(2, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.asList(new Float(1000), new Float(0))); Assert.assertEquals(1, dAccessor.getRemovedRecords().size()); assertList(dAccessor.getRemovedRecords(), Arrays.asList(new Float(2))); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("Float"); Assert.assertEquals(4, typeState.maxOrdinal()); assertObject(typeState, 0, new Float(1)); assertObject(typeState, 1, new Float(2)); /// this was "removed", but the data hangs around as a "ghost" until the following cycle. assertObject(typeState, 2, new Float(3)); assertObject(typeState, 3, new Float(1000)); assertObject(typeState, 4, new Float(0)); roundTripDelta(); // remove everything { FloatDataAccessor dAccessor = new FloatDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(0, dAccessor.getAddedRecords().size()); Assert.assertEquals(4, dAccessor.getRemovedRecords().size()); assertList(dAccessor.getRemovedRecords(), Arrays.asList(new Float(1), new Float(3), new Float(1000), new Float(0))); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } assertObject(typeState, 0, new Float(1)); /// all records were "removed", but again hang around until the following cycle. // assertObject(typeState, 1, new Float(2)); /// this record should now be disappeared. assertObject(typeState, 2, new Float(3)); /// "ghost" assertObject(typeState, 3, new Float(1000)); /// "ghost" assertObject(typeState, 4, new Float(0)); /// "ghost" Assert.assertEquals(4, typeState.maxOrdinal()); addRecord(new Float(634)); addRecord(new Float(0)); roundTripDelta(); { FloatDataAccessor dAccessor = new FloatDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(2, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.asList(new Float(634), new Float(0))); Assert.assertEquals(0, dAccessor.getRemovedRecords().size()); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } Assert.assertEquals(1, typeState.maxOrdinal()); assertObject(typeState, 0, new Float(634)); /// now, since all records were removed, we can recycle the ordinal "0", even though it was a "ghost" in the last cycle. assertObject(typeState, 1, new Float(0)); /// even though new Float(0) had an equivalent record in the previous cycle at ordinal "4", it is now assigned to recycled ordinal "1". } }
8,872
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/data/AbstractPrimitiveTypeDataAccessorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.api.consumer.data; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.write.objectmapper.HollowObjectMapper; import java.util.Collection; import java.util.List; import org.junit.Assert; public abstract class AbstractPrimitiveTypeDataAccessorTest<T> extends AbstractStateEngineTest { HollowObjectMapper objectMapper; protected abstract Class<T> getDataModelTestClass(); protected abstract T getData(HollowObjectTypeReadState readState, int ordinal); @Override protected void initializeTypeStates() { objectMapper = new HollowObjectMapper(writeStateEngine); objectMapper.initializeTypeState(getDataModelTestClass()); } protected void addRecord(Object obj) { objectMapper.add(obj); } protected void assertObject(HollowObjectTypeReadState readState, int ordinal, T expectedValue) { Object obj = getData(readState, ordinal); Assert.assertEquals(expectedValue, obj); } protected void assertList(Collection<T> listOfObj, List<T> expectedObjs) { int i = 0; for (T obj : listOfObj) { Object expectedObj = expectedObjs.get(i++); Assert.assertEquals(expectedObj, obj); } } // protected void assertUpdatedList(Collection<UpdatedRecord<T>> listOfObj, List<T> beforeValues, List<T> afterValues) { // int i = 0; // for (UpdatedRecord<T> obj : listOfObj) { // T before = obj.getBefore(); // T after = obj.getAfter(); // Assert.assertNotEquals(before, after); // // T expBefore= beforeValues.get(i); // T expAfter = afterValues.get(i++); // Assert.assertNotEquals(expBefore, expAfter); // Assert.assertEquals(expBefore, before); // Assert.assertEquals(expAfter, after); // } // } }
8,873
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/data/HollowDataAccessorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.api.consumer.data; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.netflix.hollow.api.consumer.data.AbstractHollowDataAccessor.UpdatedRecord; import com.netflix.hollow.api.objects.delegate.HollowObjectGenericDelegate; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.AbstractStateEngineTest; import com.netflix.hollow.core.index.key.PrimaryKey; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class HollowDataAccessorTest extends AbstractStateEngineTest { private static final String TEST_TYPE = "TestObject"; HollowObjectSchema schema; @Override @Before public void setUp() { schema = new HollowObjectSchema(TEST_TYPE, 2, new PrimaryKey(TEST_TYPE, "f1")); schema.addField("f1", FieldType.INT); schema.addField("f2", FieldType.STRING); super.setUp(); } @Test public void test() throws IOException { addRecord(1, "one"); addRecord(2, "two"); addRecord(3, "three"); roundTripSnapshot(); { GenericHollowRecordDataAccessor dAccessor = new GenericHollowRecordDataAccessor(readStateEngine, TEST_TYPE); dAccessor.computeDataChange(); Assert.assertTrue(dAccessor.isDataChangeComputed()); Assert.assertEquals(3, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.asList(1, 2, 3)); Assert.assertTrue(dAccessor.getRemovedRecords().isEmpty()); Assert.assertTrue(dAccessor.getUpdatedRecords().isEmpty()); } writeStateEngine.prepareForNextCycle(); /// not necessary to call, but needs to be a no-op. addRecord(1, "one"); // addRecord(2, "two"); // removed addRecord(3, "three_updated"); // updated addRecord(1000, "one thousand"); // added addRecord(0, "zero"); // added roundTripDelta(); { GenericHollowRecordDataAccessor dAccessor = new GenericHollowRecordDataAccessor(readStateEngine, TEST_TYPE); Assert.assertFalse(dAccessor.isDataChangeComputed()); // Make sure it does not pre compute Assert.assertEquals(2, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.asList(1000, 0)); Assert.assertEquals(1, dAccessor.getRemovedRecords().size()); assertList(dAccessor.getRemovedRecords(), Arrays.asList(2)); Assert.assertEquals(1, dAccessor.getUpdatedRecords().size()); assertUpdatedList(dAccessor.getUpdatedRecords(), Arrays.asList("three"), Arrays.asList("three_updated")); Assert.assertTrue(dAccessor.isDataChangeComputed()); // Make sure data change is computed once data change API are invoked } HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState(TEST_TYPE); Assert.assertEquals(5, typeState.maxOrdinal()); assertObject(typeState, 0, 1, "one"); assertObject(typeState, 1, 2, "two"); /// this was "removed", but the data hangs around as a "ghost" until the following cycle. assertObject(typeState, 2, 3, "three"); /// this was "removed", but the data hangs around as a "ghost" until the following cycle. assertObject(typeState, 3, 3, "three_updated"); assertObject(typeState, 4, 1000, "one thousand"); assertObject(typeState, 5, 0, "zero"); roundTripDelta(); // remove everything { GenericHollowRecordDataAccessor dAccessor = new GenericHollowRecordDataAccessor(readStateEngine, TEST_TYPE); Assert.assertEquals(0, dAccessor.getAddedRecords().size()); Assert.assertEquals(4, dAccessor.getRemovedRecords().size()); assertList(dAccessor.getRemovedRecords(), Arrays.asList(1, 3, 1000, 0)); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } assertObject(typeState, 0, 1, "one"); /// all records were "removed", but again hang around until the following cycle. // assertObject(typeState, 1, 2, ""); /// this record should now be disappeared. // assertObject(typeState, 2, 3, "three"); /// this record should now be disappeared. assertObject(typeState, 3, 3, "three_updated"); /// "ghost" assertObject(typeState, 4, 1000, "one thousand"); /// "ghost" assertObject(typeState, 5, 0, "zero"); /// "ghost" Assert.assertEquals(5, typeState.maxOrdinal()); addRecord(634, "six hundred thirty four"); addRecord(0, "zero"); roundTripDelta(); { GenericHollowRecordDataAccessor dAccessor = new GenericHollowRecordDataAccessor(readStateEngine, TEST_TYPE); Assert.assertEquals(2, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.asList(634, 0)); Assert.assertEquals(0, dAccessor.getRemovedRecords().size()); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } Assert.assertEquals(1, typeState.maxOrdinal()); assertObject(typeState, 0, 634, "six hundred thirty four"); /// now, since all records were removed, we can recycle the ordinal "0", even /// though it was a "ghost" in the last cycle. assertObject(typeState, 1, 0, "zero"); /// even though "zero" had an equivalent record in the previous cycle at ordinal "4", it is now /// assigned to recycled ordinal "1". } @Test public void testDoubleSnapshotChanges() throws IOException { addRecord(1, "one"); addRecord(2, "two"); addRecord(3, "three"); roundTripSnapshot(); { GenericHollowRecordDataAccessor dAccessor = new GenericHollowRecordDataAccessor(readStateEngine, TEST_TYPE); dAccessor.computeDataChange(); Assert.assertTrue(dAccessor.isDataChangeComputed()); Assert.assertEquals(3, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.asList(1, 2, 3)); Assert.assertTrue(dAccessor.getRemovedRecords().isEmpty()); Assert.assertTrue(dAccessor.getUpdatedRecords().isEmpty()); } writeStateEngine.prepareForNextCycle(); /// not necessary to call, but needs to be a no-op. addRecord(4, "four"); // added // addRecord(2, "two"); // removed addRecord(3, "three_updated"); // updated roundTripSnapshot(); { GenericHollowRecordDataAccessor dAccessor = new GenericHollowRecordDataAccessor(readStateEngine, TEST_TYPE); Assert.assertEquals(2, dAccessor.getAddedRecords().size()); // double snapshot; all records in new state are additions Assert.assertEquals(0, dAccessor.getRemovedRecords().size()); // double snapshot; no removals Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); // double snapshot; no modifications } } @Test public void typeMissing() throws IOException { roundTripSnapshot(); String typeName = "ThisTypeDoesNotExist"; assertThatThrownBy(() -> { new AbstractHollowDataAccessor<Object>(readStateEngine, typeName) { @Override public Object getRecord(int ordinal) { return null; } }; }).isInstanceOf(NullPointerException.class) .hasMessageContaining(typeName) .hasMessageContaining("not loaded"); } private void addRecord(int intVal, String strVal) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); rec.setInt("f1", intVal); rec.setString("f2", strVal); writeStateEngine.add(TEST_TYPE, rec); } private void assertObject(HollowObjectTypeReadState readState, int ordinal, int intVal, String strVal) { GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(readState), ordinal); Assert.assertEquals(intVal, obj.getInt("f1")); Assert.assertEquals(strVal, obj.getString("f2")); } private void assertList(Collection<GenericHollowObject> listOfObj, List<Integer> listOfIds) { int i = 0; for (GenericHollowObject obj : listOfObj) { int id = listOfIds.get(i++); Assert.assertEquals(id, obj.getInt("f1")); } } private void assertUpdatedList(Collection<UpdatedRecord<GenericHollowObject>> listOfObj, List<String> beforeValues, List<String> afterValues) { int i = 0; for (UpdatedRecord<GenericHollowObject> obj : listOfObj) { int beforeId = obj.getBefore().getInt("f1"); int afterId = obj.getAfter().getInt("f1"); Assert.assertEquals(beforeId, afterId); String beforeVal = beforeValues.get(i); String afterVal = afterValues.get(i++); Assert.assertNotEquals(beforeVal, afterVal); Assert.assertEquals(beforeVal, obj.getBefore().getString("f2")); Assert.assertEquals(afterVal, obj.getAfter().getString("f2")); } } @Override protected void initializeTypeStates() { HollowObjectTypeWriteState writeState = new HollowObjectTypeWriteState(schema); writeStateEngine.addTypeState(writeState); } }
8,874
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/data/IntegerDataAccessorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.api.consumer.data; import com.netflix.hollow.api.objects.delegate.HollowObjectGenericDelegate; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.type.accessor.IntegerDataAccessor; import java.io.IOException; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; public class IntegerDataAccessorTest extends AbstractPrimitiveTypeDataAccessorTest<Integer> { @Override protected Class<Integer> getDataModelTestClass() { return Integer.class; } @Override protected Integer getData(HollowObjectTypeReadState readState, int ordinal) { GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(readState), ordinal); return obj.getInt("value"); } @Test public void test() throws IOException { addRecord(new Integer(1)); addRecord(new Integer(2)); addRecord(new Integer(3)); roundTripSnapshot(); { IntegerDataAccessor dAccessor = new IntegerDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(3, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.<Integer>asList(new Integer(1), new Integer(2), new Integer(3))); Assert.assertTrue(dAccessor.getRemovedRecords().isEmpty()); Assert.assertTrue(dAccessor.getUpdatedRecords().isEmpty()); } writeStateEngine.prepareForNextCycle(); /// not necessary to call, but needs to be a no-op. addRecord(new Integer(1)); // addRecord(new Integer(2)); // removed addRecord(new Integer(3)); addRecord(new Integer(1000)); // added addRecord(new Integer(0)); // added roundTripDelta(); { IntegerDataAccessor dAccessor = new IntegerDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(2, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.asList(new Integer(1000), new Integer(0))); Assert.assertEquals(1, dAccessor.getRemovedRecords().size()); assertList(dAccessor.getRemovedRecords(), Arrays.asList(new Integer(2))); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("Integer"); Assert.assertEquals(4, typeState.maxOrdinal()); assertObject(typeState, 0, new Integer(1)); assertObject(typeState, 1, new Integer(2)); /// this was "removed", but the data hangs around as a "ghost" until the following cycle. assertObject(typeState, 2, new Integer(3)); assertObject(typeState, 3, new Integer(1000)); assertObject(typeState, 4, new Integer(0)); roundTripDelta(); // remove everything { IntegerDataAccessor dAccessor = new IntegerDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(0, dAccessor.getAddedRecords().size()); Assert.assertEquals(4, dAccessor.getRemovedRecords().size()); assertList(dAccessor.getRemovedRecords(), Arrays.asList(new Integer(1), new Integer(3), new Integer(1000), new Integer(0))); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } assertObject(typeState, 0, new Integer(1)); /// all records were "removed", but again hang around until the following cycle. // assertObject(typeState, 1, new Integer(2)); /// this record should now be disappeared. assertObject(typeState, 2, new Integer(3)); /// "ghost" assertObject(typeState, 3, new Integer(1000)); /// "ghost" assertObject(typeState, 4, new Integer(0)); /// "ghost" Assert.assertEquals(4, typeState.maxOrdinal()); addRecord(new Integer(634)); addRecord(new Integer(0)); roundTripDelta(); { IntegerDataAccessor dAccessor = new IntegerDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(2, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.asList(new Integer(634), new Integer(0))); Assert.assertEquals(0, dAccessor.getRemovedRecords().size()); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } Assert.assertEquals(1, typeState.maxOrdinal()); assertObject(typeState, 0, new Integer(634)); /// now, since all records were removed, we can recycle the ordinal "0", even though it was a "ghost" in the last cycle. assertObject(typeState, 1, new Integer(0)); /// even though new Integer(0) had an equivalent record in the previous cycle at ordinal "4", it is now assigned to recycled ordinal "1". } }
8,875
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/data/BooleanDataAccessorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.api.consumer.data; import com.netflix.hollow.api.objects.delegate.HollowObjectGenericDelegate; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.type.accessor.BooleanDataAccessor; import java.io.IOException; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; public class BooleanDataAccessorTest extends AbstractPrimitiveTypeDataAccessorTest<Boolean> { @Override protected Class<Boolean> getDataModelTestClass() { return Boolean.class; } @Override protected Boolean getData(HollowObjectTypeReadState readState, int ordinal) { GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(readState), ordinal); return obj.getBoolean("value"); } @Test public void test() throws IOException { addRecord(new Boolean(true)); addRecord(new Boolean(false)); roundTripSnapshot(); { BooleanDataAccessor dAccessor = new BooleanDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(2, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.<Boolean>asList(true, false)); Assert.assertTrue(dAccessor.getRemovedRecords().isEmpty()); Assert.assertTrue(dAccessor.getUpdatedRecords().isEmpty()); } writeStateEngine.prepareForNextCycle(); /// not necessary to call, but needs to be a no-op. addRecord(new Boolean(true)); // addRecord(new Boolean(false)); // removed roundTripDelta(); { BooleanDataAccessor dAccessor = new BooleanDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(0, dAccessor.getAddedRecords().size()); Assert.assertEquals(1, dAccessor.getRemovedRecords().size()); assertList(dAccessor.getRemovedRecords(), Arrays.asList(false)); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("Boolean"); Assert.assertEquals(1, typeState.maxOrdinal()); assertObject(typeState, 0, true); assertObject(typeState, 1, false); /// this was "removed", but the data hangs around as a "ghost" until the following cycle. roundTripDelta(); // remove everything { BooleanDataAccessor dAccessor = new BooleanDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(0, dAccessor.getAddedRecords().size()); Assert.assertEquals(1, dAccessor.getRemovedRecords().size()); assertList(dAccessor.getRemovedRecords(), Arrays.asList(true)); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } assertObject(typeState, 0, true); /// all records were "removed", but again hang around until the following cycle. // assertObject(typeState, 1, false); /// this record should now be disappeared. Assert.assertEquals(0, typeState.maxOrdinal()); addRecord(new Boolean(false)); addRecord(new Boolean(true)); roundTripDelta(); { BooleanDataAccessor dAccessor = new BooleanDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(2, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.asList(false, true)); Assert.assertEquals(0, dAccessor.getRemovedRecords().size()); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } Assert.assertEquals(1, typeState.maxOrdinal()); assertObject(typeState, 0, false); /// now, since all records were removed, we can recycle the ordinal "0", even though it was a "ghost" in the last cycle. assertObject(typeState, 1, true); /// even though "zero" had an equivalent record in the previous cycle at ordinal "4", it is now assigned to recycled ordinal "1". } }
8,876
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/data/DoubleDataAccessorTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hollow.api.consumer.data; import com.netflix.hollow.api.objects.delegate.HollowObjectGenericDelegate; import com.netflix.hollow.api.objects.generic.GenericHollowObject; import com.netflix.hollow.core.read.engine.object.HollowObjectTypeReadState; import com.netflix.hollow.core.type.accessor.DoubleDataAccessor; import java.io.IOException; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; public class DoubleDataAccessorTest extends AbstractPrimitiveTypeDataAccessorTest<Double> { @Override protected Class<Double> getDataModelTestClass() { return Double.class; } @Override protected Double getData(HollowObjectTypeReadState readState, int ordinal) { GenericHollowObject obj = new GenericHollowObject(new HollowObjectGenericDelegate(readState), ordinal); return obj.getDouble("value"); } @Test public void test() throws IOException { addRecord(new Double(1)); addRecord(new Double(2)); addRecord(new Double(3)); roundTripSnapshot(); { DoubleDataAccessor dAccessor = new DoubleDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(3, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.<Double>asList(new Double(1), new Double(2), new Double(3))); Assert.assertTrue(dAccessor.getRemovedRecords().isEmpty()); Assert.assertTrue(dAccessor.getUpdatedRecords().isEmpty()); } writeStateEngine.prepareForNextCycle(); /// not necessary to call, but needs to be a no-op. addRecord(new Double(1)); // addRecord(new Double(2)); // removed addRecord(new Double(3)); addRecord(new Double(1000)); // added addRecord(new Double(0)); // added roundTripDelta(); { DoubleDataAccessor dAccessor = new DoubleDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(2, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.asList(new Double(1000), new Double(0))); Assert.assertEquals(1, dAccessor.getRemovedRecords().size()); assertList(dAccessor.getRemovedRecords(), Arrays.asList(new Double(2))); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } HollowObjectTypeReadState typeState = (HollowObjectTypeReadState) readStateEngine.getTypeState("Double"); Assert.assertEquals(4, typeState.maxOrdinal()); assertObject(typeState, 0, new Double(1)); assertObject(typeState, 1, new Double(2)); /// this was "removed", but the data hangs around as a "ghost" until the following cycle. assertObject(typeState, 2, new Double(3)); assertObject(typeState, 3, new Double(1000)); assertObject(typeState, 4, new Double(0)); roundTripDelta(); // remove everything { DoubleDataAccessor dAccessor = new DoubleDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(0, dAccessor.getAddedRecords().size()); Assert.assertEquals(4, dAccessor.getRemovedRecords().size()); assertList(dAccessor.getRemovedRecords(), Arrays.asList(new Double(1), new Double(3), new Double(1000), new Double(0))); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } assertObject(typeState, 0, new Double(1)); /// all records were "removed", but again hang around until the following cycle. // assertObject(typeState, 1, new Double(2)); /// this record should now be disappeared. assertObject(typeState, 2, new Double(3)); /// "ghost" assertObject(typeState, 3, new Double(1000)); /// "ghost" assertObject(typeState, 4, new Double(0)); /// "ghost" Assert.assertEquals(4, typeState.maxOrdinal()); addRecord(new Double(634)); addRecord(new Double(0)); roundTripDelta(); { DoubleDataAccessor dAccessor = new DoubleDataAccessor(readStateEngine, new PrimitiveTypeTestAPI(readStateEngine)); Assert.assertEquals(2, dAccessor.getAddedRecords().size()); assertList(dAccessor.getAddedRecords(), Arrays.asList(new Double(634), new Double(0))); Assert.assertEquals(0, dAccessor.getRemovedRecords().size()); Assert.assertEquals(0, dAccessor.getUpdatedRecords().size()); } Assert.assertEquals(1, typeState.maxOrdinal()); assertObject(typeState, 0, new Double(634)); /// now, since all records were removed, we can recycle the ordinal "0", even though it was a "ghost" in the last cycle. assertObject(typeState, 1, new Double(0)); /// even though new Double(0) had an equivalent record in the previous cycle at ordinal "4", it is now assigned to recycled ordinal "1". } }
8,877
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/consumer/data/PrimitiveTypeTestAPI.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.consumer.data; import com.netflix.hollow.api.consumer.HollowConsumerAPI; import com.netflix.hollow.api.custom.HollowAPI; import com.netflix.hollow.api.objects.provider.HollowFactory; import com.netflix.hollow.api.objects.provider.HollowObjectCacheProvider; import com.netflix.hollow.api.objects.provider.HollowObjectFactoryProvider; import com.netflix.hollow.api.objects.provider.HollowObjectProvider; import com.netflix.hollow.core.read.dataaccess.HollowDataAccess; import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess; import com.netflix.hollow.core.read.dataaccess.HollowTypeDataAccess; import com.netflix.hollow.core.read.dataaccess.missing.HollowObjectMissingDataAccess; import com.netflix.hollow.core.type.BooleanHollowFactory; import com.netflix.hollow.core.type.BooleanTypeAPI; import com.netflix.hollow.core.type.DoubleHollowFactory; import com.netflix.hollow.core.type.DoubleTypeAPI; import com.netflix.hollow.core.type.FloatHollowFactory; import com.netflix.hollow.core.type.FloatTypeAPI; import com.netflix.hollow.core.type.HBoolean; import com.netflix.hollow.core.type.HDouble; import com.netflix.hollow.core.type.HFloat; import com.netflix.hollow.core.type.HInteger; import com.netflix.hollow.core.type.HLong; import com.netflix.hollow.core.type.HString; import com.netflix.hollow.core.type.IntegerHollowFactory; import com.netflix.hollow.core.type.IntegerTypeAPI; import com.netflix.hollow.core.type.LongHollowFactory; import com.netflix.hollow.core.type.LongTypeAPI; import com.netflix.hollow.core.type.StringHollowFactory; import com.netflix.hollow.core.type.StringTypeAPI; import com.netflix.hollow.core.util.AllHollowRecordCollection; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Set; @SuppressWarnings("all") public class PrimitiveTypeTestAPI extends HollowAPI implements HollowConsumerAPI.FloatRetriever, HollowConsumerAPI.DoubleRetriever, HollowConsumerAPI.LongRetriever, HollowConsumerAPI.StringRetriever, HollowConsumerAPI.IntegerRetriever, HollowConsumerAPI.BooleanRetriever { private final BooleanTypeAPI booleanTypeAPI; private final DoubleTypeAPI doubleTypeAPI; private final FloatTypeAPI floatTypeAPI; private final IntegerTypeAPI integerTypeAPI; private final LongTypeAPI longTypeAPI; private final StringTypeAPI stringTypeAPI; private final HollowObjectProvider booleanProvider; private final HollowObjectProvider doubleProvider; private final HollowObjectProvider floatProvider; private final HollowObjectProvider integerProvider; private final HollowObjectProvider longProvider; private final HollowObjectProvider stringProvider; public PrimitiveTypeTestAPI(HollowDataAccess dataAccess) { this(dataAccess, Collections.<String>emptySet()); } public PrimitiveTypeTestAPI(HollowDataAccess dataAccess, Set<String> cachedTypes) { this(dataAccess, cachedTypes, Collections.<String, HollowFactory<?>>emptyMap()); } public PrimitiveTypeTestAPI(HollowDataAccess dataAccess, Set<String> cachedTypes, Map<String, HollowFactory<?>> factoryOverrides) { this(dataAccess, cachedTypes, factoryOverrides, null); } public PrimitiveTypeTestAPI(HollowDataAccess dataAccess, Set<String> cachedTypes, Map<String, HollowFactory<?>> factoryOverrides, PrimitiveTypeTestAPI previousCycleAPI) { super(dataAccess); HollowTypeDataAccess typeDataAccess; HollowFactory factory; typeDataAccess = dataAccess.getTypeDataAccess("Boolean"); if(typeDataAccess != null) { booleanTypeAPI = new BooleanTypeAPI(this, (HollowObjectTypeDataAccess)typeDataAccess); } else { booleanTypeAPI = new BooleanTypeAPI(this, new HollowObjectMissingDataAccess(dataAccess, "Boolean")); } addTypeAPI(booleanTypeAPI); factory = factoryOverrides.get("Boolean"); if(factory == null) factory = new BooleanHollowFactory(); if(cachedTypes.contains("Boolean")) { HollowObjectCacheProvider previousCacheProvider = null; if(previousCycleAPI != null && (previousCycleAPI.booleanProvider instanceof HollowObjectCacheProvider)) previousCacheProvider = (HollowObjectCacheProvider) previousCycleAPI.booleanProvider; booleanProvider = new HollowObjectCacheProvider(typeDataAccess, booleanTypeAPI, factory, previousCacheProvider); } else { booleanProvider = new HollowObjectFactoryProvider(typeDataAccess, booleanTypeAPI, factory); } typeDataAccess = dataAccess.getTypeDataAccess("Double"); if(typeDataAccess != null) { doubleTypeAPI = new DoubleTypeAPI(this, (HollowObjectTypeDataAccess)typeDataAccess); } else { doubleTypeAPI = new DoubleTypeAPI(this, new HollowObjectMissingDataAccess(dataAccess, "Double")); } addTypeAPI(doubleTypeAPI); factory = factoryOverrides.get("Double"); if(factory == null) factory = new DoubleHollowFactory(); if(cachedTypes.contains("Double")) { HollowObjectCacheProvider previousCacheProvider = null; if(previousCycleAPI != null && (previousCycleAPI.doubleProvider instanceof HollowObjectCacheProvider)) previousCacheProvider = (HollowObjectCacheProvider) previousCycleAPI.doubleProvider; doubleProvider = new HollowObjectCacheProvider(typeDataAccess, doubleTypeAPI, factory, previousCacheProvider); } else { doubleProvider = new HollowObjectFactoryProvider(typeDataAccess, doubleTypeAPI, factory); } typeDataAccess = dataAccess.getTypeDataAccess("Float"); if(typeDataAccess != null) { floatTypeAPI = new FloatTypeAPI(this, (HollowObjectTypeDataAccess)typeDataAccess); } else { floatTypeAPI = new FloatTypeAPI(this, new HollowObjectMissingDataAccess(dataAccess, "Float")); } addTypeAPI(floatTypeAPI); factory = factoryOverrides.get("Float"); if(factory == null) factory = new FloatHollowFactory(); if(cachedTypes.contains("Float")) { HollowObjectCacheProvider previousCacheProvider = null; if(previousCycleAPI != null && (previousCycleAPI.floatProvider instanceof HollowObjectCacheProvider)) previousCacheProvider = (HollowObjectCacheProvider) previousCycleAPI.floatProvider; floatProvider = new HollowObjectCacheProvider(typeDataAccess, floatTypeAPI, factory, previousCacheProvider); } else { floatProvider = new HollowObjectFactoryProvider(typeDataAccess, floatTypeAPI, factory); } typeDataAccess = dataAccess.getTypeDataAccess("Integer"); if(typeDataAccess != null) { integerTypeAPI = new IntegerTypeAPI(this, (HollowObjectTypeDataAccess)typeDataAccess); } else { integerTypeAPI = new IntegerTypeAPI(this, new HollowObjectMissingDataAccess(dataAccess, "Integer")); } addTypeAPI(integerTypeAPI); factory = factoryOverrides.get("Integer"); if(factory == null) factory = new IntegerHollowFactory(); if(cachedTypes.contains("Integer")) { HollowObjectCacheProvider previousCacheProvider = null; if(previousCycleAPI != null && (previousCycleAPI.integerProvider instanceof HollowObjectCacheProvider)) previousCacheProvider = (HollowObjectCacheProvider) previousCycleAPI.integerProvider; integerProvider = new HollowObjectCacheProvider(typeDataAccess, integerTypeAPI, factory, previousCacheProvider); } else { integerProvider = new HollowObjectFactoryProvider(typeDataAccess, integerTypeAPI, factory); } typeDataAccess = dataAccess.getTypeDataAccess("Long"); if(typeDataAccess != null) { longTypeAPI = new LongTypeAPI(this, (HollowObjectTypeDataAccess)typeDataAccess); } else { longTypeAPI = new LongTypeAPI(this, new HollowObjectMissingDataAccess(dataAccess, "Long")); } addTypeAPI(longTypeAPI); factory = factoryOverrides.get("Long"); if(factory == null) factory = new LongHollowFactory(); if(cachedTypes.contains("Long")) { HollowObjectCacheProvider previousCacheProvider = null; if(previousCycleAPI != null && (previousCycleAPI.longProvider instanceof HollowObjectCacheProvider)) previousCacheProvider = (HollowObjectCacheProvider) previousCycleAPI.longProvider; longProvider = new HollowObjectCacheProvider(typeDataAccess, longTypeAPI, factory, previousCacheProvider); } else { longProvider = new HollowObjectFactoryProvider(typeDataAccess, longTypeAPI, factory); } typeDataAccess = dataAccess.getTypeDataAccess("String"); if(typeDataAccess != null) { stringTypeAPI = new StringTypeAPI(this, (HollowObjectTypeDataAccess)typeDataAccess); } else { stringTypeAPI = new StringTypeAPI(this, new HollowObjectMissingDataAccess(dataAccess, "String")); } addTypeAPI(stringTypeAPI); factory = factoryOverrides.get("String"); if(factory == null) factory = new StringHollowFactory(); if(cachedTypes.contains("String")) { HollowObjectCacheProvider previousCacheProvider = null; if(previousCycleAPI != null && (previousCycleAPI.stringProvider instanceof HollowObjectCacheProvider)) previousCacheProvider = (HollowObjectCacheProvider) previousCycleAPI.stringProvider; stringProvider = new HollowObjectCacheProvider(typeDataAccess, stringTypeAPI, factory, previousCacheProvider); } else { stringProvider = new HollowObjectFactoryProvider(typeDataAccess, stringTypeAPI, factory); } } @Override public void detachCaches() { if(booleanProvider instanceof HollowObjectCacheProvider) ((HollowObjectCacheProvider)booleanProvider).detach(); if(doubleProvider instanceof HollowObjectCacheProvider) ((HollowObjectCacheProvider)doubleProvider).detach(); if(floatProvider instanceof HollowObjectCacheProvider) ((HollowObjectCacheProvider)floatProvider).detach(); if(integerProvider instanceof HollowObjectCacheProvider) ((HollowObjectCacheProvider)integerProvider).detach(); if(longProvider instanceof HollowObjectCacheProvider) ((HollowObjectCacheProvider)longProvider).detach(); if(stringProvider instanceof HollowObjectCacheProvider) ((HollowObjectCacheProvider)stringProvider).detach(); } public BooleanTypeAPI getBooleanTypeAPI() { return booleanTypeAPI; } public DoubleTypeAPI getDoubleTypeAPI() { return doubleTypeAPI; } public FloatTypeAPI getFloatTypeAPI() { return floatTypeAPI; } public IntegerTypeAPI getIntegerTypeAPI() { return integerTypeAPI; } public LongTypeAPI getLongTypeAPI() { return longTypeAPI; } public StringTypeAPI getStringTypeAPI() { return stringTypeAPI; } @Override public Collection<HBoolean> getAllHBoolean() { return new AllHollowRecordCollection<HBoolean>(getDataAccess().getTypeDataAccess("Boolean").getTypeState()) { @Override protected HBoolean getForOrdinal(int ordinal) { return getHBoolean(ordinal); } }; } @Override public HBoolean getHBoolean(int ordinal) { return (HBoolean)booleanProvider.getHollowObject(ordinal); } @Override public Collection<HDouble> getAllHDouble() { return new AllHollowRecordCollection<HDouble>(getDataAccess().getTypeDataAccess("Double").getTypeState()) { @Override protected HDouble getForOrdinal(int ordinal) { return getHDouble(ordinal); } }; } @Override public HDouble getHDouble(int ordinal) { return (HDouble)doubleProvider.getHollowObject(ordinal); } @Override public Collection<HFloat> getAllHFloat() { return new AllHollowRecordCollection<HFloat>(getDataAccess().getTypeDataAccess("Float").getTypeState()) { @Override protected HFloat getForOrdinal(int ordinal) { return getHFloat(ordinal); } }; } @Override public HFloat getHFloat(int ordinal) { return (HFloat)floatProvider.getHollowObject(ordinal); } @Override public Collection<HInteger> getAllHInteger() { return new AllHollowRecordCollection<HInteger>(getDataAccess().getTypeDataAccess("Integer").getTypeState()) { @Override protected HInteger getForOrdinal(int ordinal) { return getHInteger(ordinal); } }; } @Override public HInteger getHInteger(int ordinal) { return (HInteger)integerProvider.getHollowObject(ordinal); } @Override public Collection<HLong> getAllHLong() { return new AllHollowRecordCollection<HLong>(getDataAccess().getTypeDataAccess("Long").getTypeState()) { @Override protected HLong getForOrdinal(int ordinal) { return getHLong(ordinal); } }; } @Override public HLong getHLong(int ordinal) { return (HLong)longProvider.getHollowObject(ordinal); } @Override public Collection<HString> getAllHString() { return new AllHollowRecordCollection<HString>(getDataAccess().getTypeDataAccess("String").getTypeState()) { @Override protected HString getForOrdinal(int ordinal) { return getHString(ordinal); } }; } @Override public HString getHString(int ordinal) { return (HString)stringProvider.getHollowObject(ordinal); } }
8,878
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/client/HollowClientTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.client; import com.netflix.hollow.api.custom.HollowAPI; import com.netflix.hollow.core.HollowBlobHeader; import com.netflix.hollow.core.read.dataaccess.HollowObjectTypeDataAccess; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowObjectSchema.FieldType; import com.netflix.hollow.core.write.HollowBlobWriter; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import com.netflix.hollow.core.write.HollowWriteStateEngine; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @SuppressWarnings("deprecation") public class HollowClientTest { private HollowWriteStateEngine writeEngine; private HollowObjectTypeWriteState typeWriteState; private HollowObjectSchema schema; private HollowBlobWriter writer; private HollowClient client; private final ByteArrayOutputStream snapshot1 = new ByteArrayOutputStream(); private final ByteArrayOutputStream delta1 = new ByteArrayOutputStream(); private final ByteArrayOutputStream delta2 = new ByteArrayOutputStream(); private final ByteArrayOutputStream delta3 = new ByteArrayOutputStream(); @Before public void setUp() throws IOException { this.writeEngine = new HollowWriteStateEngine(); this.schema = new HollowObjectSchema("TestObject", 2); schema.addField("f1", FieldType.INT); schema.addField("f2", FieldType.STRING); this.typeWriteState = new HollowObjectTypeWriteState(schema); writeEngine.addTypeState(typeWriteState); writer = new HollowBlobWriter(writeEngine); snapshot1.reset(); delta1.reset(); delta2.reset(); delta3.reset(); client = new HollowClient.Builder() .withBlobRetriever(new FakeHollowBlobRetriever()) .withMemoryConfig(new HollowClientMemoryConfig.SpecifiedConfig(true, false, 10000L, 10000L)) .build(); createChain(); } @Test public void testClientAPIHoldsLongLivedReferences() throws IOException { client.triggerRefreshTo(1); HollowAPI api = client.getAPI(); HollowObjectTypeDataAccess dataAccess = (HollowObjectTypeDataAccess) api.getDataAccess().getTypeDataAccess("TestObject"); client.triggerRefreshTo(2); client.triggerRefreshTo(3); client.triggerRefreshTo(4); Assert.assertEquals(1, dataAccess.readInt(1, 0)); Assert.assertEquals("one", dataAccess.readString(1, 1)); Assert.assertEquals(3, dataAccess.readInt(3, 0)); Assert.assertEquals("three", dataAccess.readString(3, 1)); } private void createChain() throws IOException { addRecord(0, "zero"); addRecord(1, "one"); addRecord(2, "two"); addRecord(3, "three"); addRecord(4, "four"); addRecord(5, "five"); writer.writeSnapshot(snapshot1); writeEngine.prepareForNextCycle(); addRecord(0, "zero"); // addRecord(1, "one"); addRecord(2, "two"); addRecord(3, "three"); // addRecord(4, "four"); addRecord(5, "five"); addRecord(6, "six"); writer.writeDelta(delta1); writeEngine.prepareForNextCycle(); addRecord(0, "zero"); addRecord(7, "seven"); // addRecord(1, "one"); // addRecord(2, "two"); addRecord(3, "three"); addRecord(8, "eight"); // addRecord(4, "four"); // addRecord(5, "five"); // addRecord(6, "six"); writer.writeDelta(delta2); writeEngine.prepareForNextCycle(); addRecord(0, "zero"); addRecord(7, "seven"); // addRecord(1, "one"); addRecord(9, "nine"); // addRecord(2, "two"); addRecord(3, "three"); addRecord(8, "eight"); // addRecord(4, "four"); // addRecord(5, "five"); // addRecord(6, "six"); writer.writeDelta(delta3); writeEngine.prepareForNextCycle(); } private final void addRecord(int f1, String f2) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord(schema); rec.setInt("f1", f1); rec.setString("f2", f2); writeEngine.add("TestObject", rec); } private class FakeHollowBlobRetriever implements HollowBlobRetriever { @Override public HollowBlob retrieveSnapshotBlob(long desiredVersion) { return new HollowBlob(1) { public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(snapshot1.toByteArray()); } }; } @Override public HollowBlobHeader retrieveHeaderBlob(long currentVersion) { return new HollowBlobHeader(); } @Override public HollowBlob retrieveDeltaBlob(long currentVersion) { byte[] data = null; if(currentVersion == 1) data = delta1.toByteArray(); if(currentVersion == 2) data = delta2.toByteArray(); if(currentVersion == 3) data = delta3.toByteArray(); final byte b[] = data; return new HollowBlob(currentVersion, currentVersion + 1) { public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(b); } }; } @Override public HollowBlob retrieveReverseDeltaBlob(long currentVersion) { throw new UnsupportedOperationException(); } } }
8,879
0
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api
Create_ds/hollow/hollow/src/test/java/com/netflix/hollow/api/client/HollowClientUpdaterTest.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.api.client; import static com.netflix.hollow.core.HollowConstants.VERSION_LATEST; import static com.netflix.hollow.core.HollowConstants.VERSION_NONE; import static com.netflix.hollow.core.HollowStateEngine.HEADER_TAG_SCHEMA_HASH; import static java.util.Collections.emptyList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.netflix.hollow.api.consumer.HollowConsumer; import com.netflix.hollow.api.custom.HollowAPI; import com.netflix.hollow.api.metrics.HollowConsumerMetrics; import com.netflix.hollow.core.HollowStateEngine; import com.netflix.hollow.core.memory.MemoryMode; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowSchemaHash; import com.netflix.hollow.core.write.HollowBlobWriter; import com.netflix.hollow.core.write.HollowObjectTypeWriteState; import com.netflix.hollow.core.write.HollowObjectWriteRecord; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.test.HollowWriteStateEngineBuilder; import com.netflix.hollow.test.consumer.TestBlob; import com.netflix.hollow.test.consumer.TestBlobRetriever; import com.netflix.hollow.test.consumer.TestHollowConsumer; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.LogRecord; import java.util.logging.Logger; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class HollowClientUpdaterTest { private HollowConsumer.BlobRetriever retriever; private HollowConsumer.DoubleSnapshotConfig snapshotConfig; private HollowConsumerMetrics metrics; private HollowClientUpdater subject; private HollowConsumer.ObjectLongevityConfig objectLongevityConfig; private HollowConsumer.ObjectLongevityDetector objectLongevityDetector; private HollowAPIFactory apiFactory; @Before public void setUp() { retriever = mock(HollowConsumer.BlobRetriever.class); apiFactory = mock(HollowAPIFactory.class); snapshotConfig = mock(HollowConsumer.DoubleSnapshotConfig.class); objectLongevityConfig = mock(HollowConsumer.ObjectLongevityConfig.class); objectLongevityDetector = mock(HollowConsumer.ObjectLongevityDetector.class); metrics = mock(HollowConsumerMetrics.class); MemoryMode memoryMode = MemoryMode.ON_HEAP; subject = new HollowClientUpdater(retriever, emptyList(), apiFactory, snapshotConfig, null, memoryMode, objectLongevityConfig, objectLongevityDetector, metrics, null); } @Test public void testUpdateTo_noVersions() throws Throwable { when(snapshotConfig.allowDoubleSnapshot()).thenReturn(false); when(snapshotConfig.doubleSnapshotOnSchemaChange()).thenReturn(false); assertTrue(subject.updateTo(VERSION_NONE)); HollowReadStateEngine readStateEngine = subject.getStateEngine(); assertTrue("Should have no types", readStateEngine.getAllTypes().isEmpty()); assertTrue("Should create snapshot plan next, even if double snapshot config disallows it", subject.shouldCreateSnapshotPlan(new HollowConsumer.VersionInfo(VERSION_NONE))); assertTrue(subject.updateTo(VERSION_NONE)); assertTrue("Should still have no types", readStateEngine.getAllTypes().isEmpty()); } @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testUpdateTo_updateToLatestButNoVersionsRetrieved_throwsException() throws Throwable { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Could not create an update plan, because no existing versions could be retrieved."); subject.updateTo(VERSION_LATEST); } @Test public void testUpdateTo_updateToArbitraryVersionButNoVersionsRetrieved_throwsException() throws Throwable { long v = Long.MAX_VALUE - 1; expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(String.format("Could not create an update plan for version %s, because that " + "version or any qualifying previous versions could not be retrieved.", v)); subject.updateTo(v); } @Test public void initialLoad_beforeFirst() { CompletableFuture<Long> initialLoad = subject.getInitialLoad(); assertFalse(initialLoad.isDone()); assertFalse(initialLoad.isCancelled()); assertFalse(initialLoad.isCompletedExceptionally()); } @Test public void initialLoad_firstFailed() { when(retriever.retrieveSnapshotBlob(anyLong())) .thenThrow(new RuntimeException("boom")); try { subject.updateTo(VERSION_LATEST); fail("should throw"); } catch (Throwable th) { assertEquals("boom", th.getMessage()); } assertFalse(subject.getInitialLoad().isCompletedExceptionally()); } @Test public void testInitialLoadSucceedsThenBadUpdatePlan_throwsException() throws Throwable { // much setup // 1. construct a real-ish snapshot blob HollowWriteStateEngine stateEngine = new HollowWriteStateEngineBuilder() .add("hello") .build(); // TODO(timt): DRY with TestHollowConsumer::addSnapshot ByteArrayOutputStream os = new ByteArrayOutputStream(); new HollowBlobWriter(stateEngine).writeSnapshot(os); ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); // 2. fake a snapshot blob HollowConsumer.Blob blob = mock(HollowConsumer.Blob.class); when(blob.isSnapshot()) .thenReturn(true); when(blob.getInputStream()) .thenReturn(is); // 3. return fake snapshot when asked when(retriever.retrieveSnapshotBlob(anyLong())) .thenReturn(blob); // such act subject.updateTo(VERSION_LATEST); // amaze! assertTrue(subject.getInitialLoad().isDone()); // test exception msg when subsequent update fails to fetch qualifying versions long v = Long.MAX_VALUE - 1; expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(String.format("Could not create an update plan for version %s, because that " + "version or any qualifying previous versions could not be retrieved. Consumer will remain at current " + "version %s until next update attempt.", v, subject.getCurrentVersionId())); subject.updateTo(v); } @Test public void testUpdateTo_pinnedVersion() { long pinnedVersion = 1000L; HashMap<String, String> annData = new HashMap<>(); try { subject.updateTo(new HollowConsumer.VersionInfo(pinnedVersion, Optional.of(annData), Optional.of(Boolean.TRUE))); } catch(Throwable ex) { // do nothing } } @Test public void testDoubleSnapshotOnSchemaChange() throws Exception { HollowWriteStateEngine stateEngine = new HollowWriteStateEngine(); TestHollowConsumer testHollowConsumer = schemaChangeSubject(stateEngine, true, false, true, true); Map<String, String> v2Metadata = new HashMap<String, String>() {{ put(HollowStateEngine.HEADER_TAG_SCHEMA_HASH, (new HollowSchemaHash(stateEngine)).getHash()); }}; testHollowConsumer.triggerRefreshTo(new HollowConsumer.VersionInfo(2, Optional.of(v2Metadata), Optional.empty())); } @Test public void testDoubleSnapshotOnSchemaChange_flagDisabled() throws Exception { HollowWriteStateEngine stateEngine = new HollowWriteStateEngine(); TestHollowConsumer testHollowConsumer = schemaChangeSubject(stateEngine, false, true, false, true); Map<String, String> v2Metadata = new HashMap<String, String>() {{ put(HollowStateEngine.HEADER_TAG_SCHEMA_HASH, (new HollowSchemaHash(stateEngine)).getHash()); }}; testHollowConsumer.triggerRefreshTo(new HollowConsumer.VersionInfo(2, Optional.of(v2Metadata), Optional.empty())); } @Test public void testDoubleSnapshotOnSchemaChange_noVersionMetadata_logsWarning() throws Exception { WarnLogHandler logHandler = (WarnLogHandler) configureLogger(HollowClientUpdater.class.getName(), Level.WARNING, "Double snapshots on schema change are enabled and its functioning depends on " + "visibility into incoming version's schema through metadata but NO metadata was available " + "for version 2. Check that the mechanism that triggered " + "the refresh (usually announcementWatcher) supports passing version metadata. This refresh will " + "not be able to reflect any schema changes."); HollowWriteStateEngine stateEngine = new HollowWriteStateEngine(); TestHollowConsumer testHollowConsumer = schemaChangeSubject(stateEngine, true, true, false, true); testHollowConsumer.triggerRefreshTo(2); assertTrue("Warning should be logged", logHandler.isContains()); } @Test public void testDoubleSnapshotOnSchemaChange_noSchemaHashInMetadata_logsWarning() throws Exception { WarnLogHandler logHandler = (WarnLogHandler) configureLogger(HollowClientUpdater.class.getName(), Level.WARNING, "Double snapshots on schema change are enabled but version metadata for incoming " + "version 2 did not contain the required attribute (" + HEADER_TAG_SCHEMA_HASH + "). Check that the producer supports setting this attribute. This " + "refresh will not be able to reflect any schema changes."); HollowWriteStateEngine stateEngine = new HollowWriteStateEngine(); TestHollowConsumer testHollowConsumer = schemaChangeSubject(stateEngine, true, true, false, true); testHollowConsumer.triggerRefreshTo(new HollowConsumer.VersionInfo(2, Optional.of(new HashMap<>()), Optional.empty())); assertTrue("Warning should be logged", logHandler.isContains()); } @Test public void testDoubleSnapshotOnSchemaChange_prohibitDoubleSnapshot_logsWarning() throws Exception { WarnLogHandler logHandler = (WarnLogHandler) configureLogger(HollowClientUpdater.class.getName(), Level.WARNING, "Auto double snapshots on schema changes are enabled but double snapshots on consumer " + "are prohibited by doubleSnapshotConfig. This refresh will not be able to reflect any schema changes."); HollowWriteStateEngine stateEngine = new HollowWriteStateEngine(); TestHollowConsumer testHollowConsumer = schemaChangeSubject(stateEngine, true, true, false, false); Map<String, String> v2Metadata = new HashMap<String, String>() {{ put(HollowStateEngine.HEADER_TAG_SCHEMA_HASH, (new HollowSchemaHash(stateEngine)).getHash()); }}; testHollowConsumer.triggerRefreshTo(new HollowConsumer.VersionInfo(2, Optional.of(v2Metadata), Optional.empty())); assertTrue("Warning should be logged", logHandler.isContains()); } private static void addMovie(HollowWriteStateEngine stateEngine, int id) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord((HollowObjectSchema) stateEngine.getSchema("Movie")); rec.setInt("id", id); stateEngine.add("Movie", rec); } private static void addActor(HollowWriteStateEngine stateEngine, int id) { HollowObjectWriteRecord rec = new HollowObjectWriteRecord((HollowObjectSchema) stateEngine.getSchema("Actor")); rec.setInt("id", id); stateEngine.add("Actor", rec); } private TestHollowConsumer schemaChangeSubject(HollowWriteStateEngine stateEngine, boolean doubleSnapshotOnSchemaChange, boolean failIfDoubleSnapshot, boolean failIfDelta, boolean allowDoubleSnapshots) throws Exception { HollowConsumer.DoubleSnapshotConfig supportsSchemaChange = new HollowConsumer.DoubleSnapshotConfig() { @Override public boolean allowDoubleSnapshot() { return allowDoubleSnapshots; } @Override public int maxDeltasBeforeDoubleSnapshot() { return 32; } @Override public boolean doubleSnapshotOnSchemaChange() { return doubleSnapshotOnSchemaChange; } }; TestBlobRetriever testBlobRetriever = new TestBlobRetriever(); HollowObjectSchema movieSchema = new HollowObjectSchema("Movie", 1, "id"); movieSchema.addField("id", HollowObjectSchema.FieldType.INT); stateEngine.addTypeState(new HollowObjectTypeWriteState(movieSchema)); class AssertNoDeltas extends HollowConsumer.AbstractRefreshListener { private boolean initialLoad = true; @Override public void snapshotUpdateOccurred(HollowAPI api, HollowReadStateEngine stateEngine, long version) throws Exception { if (!initialLoad && failIfDoubleSnapshot) { fail(); } initialLoad = false; } @Override public void deltaUpdateOccurred(HollowAPI api, HollowReadStateEngine stateEngine, long version) throws Exception { if (failIfDelta) { fail(); } } } // v1 addMovie(stateEngine, 1); stateEngine.prepareForWrite(); ByteArrayOutputStream baos_v1 = new ByteArrayOutputStream(); HollowBlobWriter writer = new HollowBlobWriter(stateEngine); writer.writeSnapshot(baos_v1); testBlobRetriever.addSnapshot(1, new TestBlob(1,new ByteArrayInputStream(baos_v1.toByteArray()))); TestHollowConsumer testHollowConsumer = (new TestHollowConsumer.Builder()) .withBlobRetriever(testBlobRetriever) .withDoubleSnapshotConfig(supportsSchemaChange) .withRefreshListener(new AssertNoDeltas()) .build(); testHollowConsumer.triggerRefreshTo(1); // v2 stateEngine.prepareForNextCycle(); HollowObjectSchema actorSchema = new HollowObjectSchema("Actor", 1, "id"); actorSchema.addField("id", HollowObjectSchema.FieldType.INT); stateEngine.addTypeState(new HollowObjectTypeWriteState(actorSchema)); addActor(stateEngine, 1); stateEngine.prepareForWrite(); ByteArrayOutputStream baos_v1_to_v2 = new ByteArrayOutputStream(); ByteArrayOutputStream baos_v2_to_v1 = new ByteArrayOutputStream(); ByteArrayOutputStream baos_v2 = new ByteArrayOutputStream(); writer.writeSnapshot(baos_v2); writer.writeDelta(baos_v1_to_v2); writer.writeReverseDelta(baos_v2_to_v1); testBlobRetriever.addSnapshot(2, new TestBlob(2,new ByteArrayInputStream(baos_v2.toByteArray()))); testBlobRetriever.addDelta(1, new TestBlob(1, 2, new ByteArrayInputStream(baos_v1_to_v2.toByteArray()))); testBlobRetriever.addReverseDelta(2, new TestBlob(2, 1, new ByteArrayInputStream(baos_v2_to_v1.toByteArray()))); return testHollowConsumer; } private Handler configureLogger(String classLogger, Level level, String msg) { Logger logger = LogManager.getLogManager().getLogger(classLogger); Handler logHandler = new WarnLogHandler(msg); logHandler.setLevel(Level.ALL); logger.setUseParentHandlers(false); logger.addHandler(logHandler); return logHandler; } private class WarnLogHandler extends Handler { private final String msg; private boolean contains = false; WarnLogHandler(String msg) { this.msg = msg; } @Override public void publish(LogRecord record) { if (record.getLevel().equals(Level.WARNING)) { if (record.getMessage().equals(msg)) { contains = true; } } } @Override public void flush() { } @Override public void close() throws SecurityException { } public boolean isContains() { return contains; } } }
8,880
0
Create_ds/hollow/hollow/src/main/java/com/netflix
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/Internal.java
/* * Copyright 2016-2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PACKAGE; import static java.lang.annotation.ElementType.TYPE; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This represents code that the hollow project considers internal code that MAY not be stable within * major releases. * * In general unnecessary changes will be avoided but you should not depend on internal classes being stable */ @Retention(RetentionPolicy.RUNTIME) @Target(value={CONSTRUCTOR, METHOD, PACKAGE, TYPE}) public @interface Internal {}
8,881
0
Create_ds/hollow/hollow/src/main/java/com/netflix
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/Hollow.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow; // Note: this class should always remain in `hollow` module (i.e. `hollow.jar` as it's used to determine JAR version at runtime public final class Hollow { private Hollow() {} }
8,882
0
Create_ds/hollow/hollow/src/main/java/com/netflix
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/PublicSpi.java
/* * Copyright 2016-2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This represents code that the hollow project considers public SPI and has an imperative to be stable within * major releases. * * The guarantee is for callers of code with this annotation as well as derivations that inherit / implement this code. * * New methods will not be added (without using default methods say) that would nominally breaks SPI implementations * within a major release. */ @Retention(RetentionPolicy.RUNTIME) @Target(value = {CONSTRUCTOR, METHOD, TYPE}) @Documented public @interface PublicSpi {}
8,883
0
Create_ds/hollow/hollow/src/main/java/com/netflix
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/PublicApi.java
/* * Copyright 2016-2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This represents code that the hollow project considers public API and has an imperative to be stable within * major releases. * * The guarantee is for code calling classes and interfaces with this annotation, not derived from them. New methods * maybe be added which would break derivations but not callers. */ @Retention(RetentionPolicy.RUNTIME) @Target(value = {CONSTRUCTOR, METHOD, TYPE}) @Documented public @interface PublicApi {}
8,884
0
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools/split/HollowSplitterOrdinalRemapper.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.tools.split; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.read.engine.HollowTypeReadState; import com.netflix.hollow.tools.combine.OrdinalRemapper; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class HollowSplitterOrdinalRemapper implements OrdinalRemapper { private final HollowSplitterShardCopier shardCopier; private final Map<String, int[]> typeMappings = new HashMap<String, int[]>(); public HollowSplitterOrdinalRemapper(HollowReadStateEngine stateEngine, HollowSplitterShardCopier shardCopier) { this.shardCopier = shardCopier; for(HollowTypeReadState typeState : stateEngine.getTypeStates()) { String typeName = typeState.getSchema().getName(); int ordinalRemapping[] = new int[typeState.maxOrdinal() + 1]; Arrays.fill(ordinalRemapping, -1); typeMappings.put(typeName, ordinalRemapping); } } @Override public int getMappedOrdinal(String type, int originalOrdinal) { int[] ordinalRemapping = typeMappings.get(type); if(ordinalRemapping[originalOrdinal] == -1) { ordinalRemapping[originalOrdinal] = shardCopier.copyRecord(type, originalOrdinal); } return ordinalRemapping[originalOrdinal]; } @Override public void remapOrdinal(String type, int originalOrdinal, int mappedOrdinal) { typeMappings.get(type)[originalOrdinal] = mappedOrdinal; } @Override public boolean ordinalIsMapped(String type, int originalOrdinal) { return typeMappings.get(type)[originalOrdinal] != -1; } }
8,885
0
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools/split/HollowSplitterPrimaryKeyCopyDirector.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.tools.split; import com.netflix.hollow.core.index.key.HollowPrimaryKeyValueDeriver; import com.netflix.hollow.core.index.key.PrimaryKey; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.read.engine.HollowTypeReadState; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class HollowSplitterPrimaryKeyCopyDirector implements HollowSplitterCopyDirector { private final int numShards; private final List<String> topLevelTypes; private final Map<String, HollowPrimaryKeyValueDeriver> primaryKeyDeriverByType; public HollowSplitterPrimaryKeyCopyDirector(HollowReadStateEngine stateEngine, int numShards, PrimaryKey... keys) { this.numShards = numShards; this.topLevelTypes = new ArrayList<String>(keys.length); this.primaryKeyDeriverByType = new HashMap<String, HollowPrimaryKeyValueDeriver>(); for(int i=0;i<keys.length;i++) { topLevelTypes.add(keys[i].getType()); HollowPrimaryKeyValueDeriver deriver = new HollowPrimaryKeyValueDeriver(keys[i], stateEngine); primaryKeyDeriverByType.put(keys[i].getType(), deriver); } } public void addReplicatedTypes(String... replicatedTypes) { topLevelTypes.addAll(Arrays.asList(replicatedTypes)); } @Override public String[] getTopLevelTypes() { return topLevelTypes.toArray(new String[topLevelTypes.size()]); } @Override public int getNumShards() { return numShards; } @Override public int getShard(HollowTypeReadState topLevelType, int ordinal) { HollowPrimaryKeyValueDeriver deriver = primaryKeyDeriverByType.get(topLevelType.getSchema().getName()); if(deriver == null) return -1; Object[] key = deriver.getRecordKey(ordinal); return hashKey(topLevelType.getSchema().getName(), key) % numShards; } public int hashKey(String type, Object[] key) { return Arrays.hashCode(key); } }
8,886
0
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools/split/HollowSplitterCopyDirector.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.tools.split; import com.netflix.hollow.core.read.engine.HollowTypeReadState; public interface HollowSplitterCopyDirector { public String[] getTopLevelTypes(); public int getNumShards(); public int getShard(HollowTypeReadState topLevelType, int ordinal); }
8,887
0
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools/split/HollowSplitterOrdinalCopyDirector.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.tools.split; import com.netflix.hollow.core.read.engine.HollowTypeReadState; public class HollowSplitterOrdinalCopyDirector implements HollowSplitterCopyDirector { private final int numShards; private final String[] topLevelTypes; public HollowSplitterOrdinalCopyDirector(int numShards, String... topLevelTypes) { this.numShards = numShards; this.topLevelTypes = topLevelTypes; } @Override public String[] getTopLevelTypes() { return topLevelTypes; } @Override public int getNumShards() { return numShards; } @Override public int getShard(HollowTypeReadState topLevelType, int ordinal) { return ordinal % numShards; } }
8,888
0
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools/split/HollowSplitterShardCopier.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.tools.split; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.read.engine.HollowTypeReadState; import com.netflix.hollow.core.read.engine.PopulatedOrdinalListener; import com.netflix.hollow.core.read.engine.map.HollowMapTypeReadState; import com.netflix.hollow.core.read.engine.set.HollowSetTypeReadState; import com.netflix.hollow.core.schema.HollowMapSchema; import com.netflix.hollow.core.schema.HollowSetSchema; import com.netflix.hollow.core.write.HollowWriteRecord; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.copy.HollowRecordCopier; import com.netflix.hollow.tools.combine.OrdinalRemapper; import java.util.BitSet; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; public class HollowSplitterShardCopier { private final Logger log = Logger.getLogger(HollowSplitterShardCopier.class.getName()); private final HollowReadStateEngine input; private final HollowWriteStateEngine output; private final OrdinalRemapper ordinalRemapper; private final HollowSplitterCopyDirector director; private final int shardNumber; private final Map<String, HollowRecordCopier> copiersPerType; public HollowSplitterShardCopier(HollowReadStateEngine input, HollowWriteStateEngine shardOutput, HollowSplitterCopyDirector director, int shardNumber) { this.input = input; this.output = shardOutput; this.director = director; this.shardNumber = shardNumber; this.ordinalRemapper = new HollowSplitterOrdinalRemapper(input, this); this.copiersPerType = new HashMap<String, HollowRecordCopier>(); } public void copy() { for(String topLevelType : director.getTopLevelTypes()) { HollowTypeReadState inputTypeState = input.getTypeState(topLevelType); if(inputTypeState == null) { log.warning("Could not find input type state for " + topLevelType); continue; } PopulatedOrdinalListener listener = inputTypeState.getListener(PopulatedOrdinalListener.class); BitSet ordinals = listener.getPopulatedOrdinals(); int ordinal = ordinals.nextSetBit(0); while(ordinal != -1) { int directedShard = director.getShard(inputTypeState, ordinal); if(directedShard == shardNumber || directedShard < 0) { copyRecord(topLevelType, ordinal); } ordinal = ordinals.nextSetBit(ordinal + 1); } } } int copyRecord(String typeName, int ordinal) { HollowTypeReadState typeState = input.getTypeState(typeName); HollowRecordCopier copier = copiersPerType.get(typeName); if(copier == null) { copier = HollowRecordCopier.createCopier(typeState, ordinalRemapper, isDefinedHashCode(typeState)); copiersPerType.put(typeName, copier); } HollowWriteRecord rec = copier.copy(ordinal); return output.add(typeName, rec); } private boolean isDefinedHashCode(HollowTypeReadState typeState) { if(typeState instanceof HollowSetTypeReadState) return input.getTypesWithDefinedHashCodes().contains(((HollowSetSchema)typeState.getSchema()).getElementType()); if(typeState instanceof HollowMapTypeReadState) return input.getTypesWithDefinedHashCodes().contains(((HollowMapSchema)typeState.getSchema()).getKeyType()); return false; } }
8,889
0
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools/split/HollowSplitter.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.tools.split; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.schema.HollowSchema; import com.netflix.hollow.core.util.HollowWriteStateCreator; import com.netflix.hollow.core.util.SimultaneousExecutor; import com.netflix.hollow.core.write.HollowWriteStateEngine; import java.util.List; /** * This tool can be used to shard a Hollow dataset into two or more smaller datasets. */ public class HollowSplitter { private final HollowReadStateEngine inputStateEngine; private final HollowWriteStateEngine outputStateEngines[]; private final HollowSplitterCopyDirector director; public HollowSplitter(HollowSplitterCopyDirector director, HollowReadStateEngine inputStateEngine) { this.inputStateEngine = inputStateEngine; this.outputStateEngines = new HollowWriteStateEngine[director.getNumShards()]; this.director = director; List<HollowSchema> schemas = inputStateEngine.getSchemas(); for(int i=0;i<director.getNumShards();i++) outputStateEngines[i] = HollowWriteStateCreator.createWithSchemas(schemas); } public void split() { prepareForNextCycle(); SimultaneousExecutor executor = new SimultaneousExecutor(getNumberOfShards(), getClass(), "split"); for(int i=0;i<getNumberOfShards();i++) { final int shardNumber = i; executor.execute(new Runnable() { public void run() { HollowSplitterShardCopier copier = new HollowSplitterShardCopier(inputStateEngine, outputStateEngines[shardNumber], director, shardNumber); copier.copy(); } }); } try { executor.awaitSuccessfulCompletion(); } catch(Throwable th) { throw new RuntimeException(th); } } public HollowReadStateEngine getInputStateEngine() { return inputStateEngine; } public HollowWriteStateEngine getOutputShardStateEngine(int shardNumber) { return outputStateEngines[shardNumber]; } public int getNumberOfShards() { return outputStateEngines.length; } private void prepareForNextCycle() { for(int i=0;i<outputStateEngines.length;i++) outputStateEngines[i].prepareForNextCycle(); } }
8,890
0
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools/compact/HollowCompactor.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.tools.compact; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.read.engine.HollowTypeReadState; import com.netflix.hollow.core.read.engine.PopulatedOrdinalListener; import com.netflix.hollow.core.schema.HollowMapSchema; import com.netflix.hollow.core.schema.HollowSchema; import com.netflix.hollow.core.schema.HollowSchemaSorter; import com.netflix.hollow.core.schema.HollowSetSchema; import com.netflix.hollow.core.util.IntMap; import com.netflix.hollow.core.write.HollowTypeWriteState; import com.netflix.hollow.core.write.HollowWriteRecord; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.copy.HollowRecordCopier; import com.netflix.hollow.tools.patch.delta.PartialOrdinalRemapper; import com.netflix.hollow.tools.traverse.TransitiveSetTraverser; import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * During a long delta chain, it's possible that a large number of holes in the ordinal space will exist in some types. * <p> * The HollowCompactor can reclaim space by moving records off of the high end of the ordinal space into these holes. * <p> * This is accomplished by producing deltas which <i>only</i> include removals and additions of identical records * allocated to more optimal ordinals. * <p> * This must sometimes be accomplished with a series of deltas, because the remapping of one state will cause some removals/additions * in referencing states (since they will point to new ordinals). In a single delta transition, the HollowCompactor will * only attempt to compact a set of types which are not referencing each other (either directly or transitively). * */ public class HollowCompactor { private final HollowWriteStateEngine writeEngine; private final HollowReadStateEngine readEngine; private long minCandidateHoleCostInBytes; private int minCandidateHolePercentage; /** * Provide the state engines on which to operate, and the criteria to identify when a compaction is necessary * * @param writeEngine the HollowWriteStateEngine to compact * @param readEngine a HollowReadStateEngine at the same data state as the writeEngine * @param config The criteria to identify when a compaction is necessary. */ public HollowCompactor(HollowWriteStateEngine writeEngine, HollowReadStateEngine readEngine, CompactionConfig config) { this(writeEngine, readEngine, config.getMinCandidateHoleCostInBytes(), config.getMinCandidateHolePercentage()); } /** * Provide the state engines on which to operate, and the criteria to identify when a compaction is necessary * * @param writeEngine the HollowWriteStateEngine to compact * @param readEngine a HollowReadStateEngine at the same data state as the writeEngine * @param minCandidateHoleCostInBytes identify a type as a candidate for compaction only when the bytes used by ordinal holes exceeds this value * @param minCandidateHolePercentage identify a type as a candidate for compaction only when the percentage of space used by ordinal holes exceeds this value */ public HollowCompactor(HollowWriteStateEngine writeEngine, HollowReadStateEngine readEngine, long minCandidateHoleCostInBytes, int minCandidateHolePercentage) { this.writeEngine = writeEngine; this.readEngine = readEngine; this.minCandidateHoleCostInBytes = minCandidateHoleCostInBytes; this.minCandidateHolePercentage = minCandidateHolePercentage; } /** * Determine whether a compaction is necessary, based on the criteria specified in the constructor. * @return {@code true} if compaction is necessary, otherwise {@code false} */ public boolean needsCompaction() { return !findCompactionTargets().isEmpty(); } /** * Perform a compaction. It is expected that: * * <ul> * <li>the {@link HollowWriteStateEngine} supplied in the constructor is unmodified since the * last call to {@link HollowWriteStateEngine#prepareForNextCycle()}</li> * <li>the {@link HollowReadStateEngine} supplied in the constructor reflects the same state as * the HollowWriteStateEngine.</li> * </ul> * */ public void compact() { Set<String> compactionTargets = findCompactionTargets(); Map<String, BitSet> relocatedOrdinals = new HashMap<String, BitSet>(); PartialOrdinalRemapper remapper = new PartialOrdinalRemapper(); for(String compactionTarget : compactionTargets) { HollowTypeReadState typeState = readEngine.getTypeState(compactionTarget); HollowTypeWriteState writeState = writeEngine.getTypeState(compactionTarget); BitSet populatedOrdinals = typeState.getListener(PopulatedOrdinalListener.class).getPopulatedOrdinals(); BitSet typeRelocatedOrdinals = new BitSet(populatedOrdinals.length()); int populatedCardinality = populatedOrdinals.cardinality(); writeState.addAllObjectsFromPreviousCycle(); int numRelocations = 0; int ordinalToRelocate = populatedOrdinals.nextSetBit(populatedCardinality); while(ordinalToRelocate != -1) { numRelocations++; ordinalToRelocate = populatedOrdinals.nextSetBit(ordinalToRelocate+1); } HollowRecordCopier copier = HollowRecordCopier.createCopier(typeState); IntMap remappedOrdinals = new IntMap(numRelocations); ordinalToRelocate = populatedOrdinals.length(); int relocatePosition = -1; try { for(int i=0;i<numRelocations;i++) { while(!populatedOrdinals.get(--ordinalToRelocate)); relocatePosition = populatedOrdinals.nextClearBit(relocatePosition + 1); typeRelocatedOrdinals.set(ordinalToRelocate); writeState.removeOrdinalFromThisCycle(ordinalToRelocate); HollowWriteRecord rec = copier.copy(ordinalToRelocate); writeState.mapOrdinal(rec, relocatePosition, false, true); remappedOrdinals.put(ordinalToRelocate, relocatePosition); } } finally { writeState.recalculateFreeOrdinals(); } remapper.addOrdinalRemapping(compactionTarget, remappedOrdinals); relocatedOrdinals.put(compactionTarget, typeRelocatedOrdinals); } /// find the referencing dependents TransitiveSetTraverser.addReferencingOutsideClosure(readEngine, relocatedOrdinals); /// copy all forward except remapped and transitive dependents of remapped for(HollowSchema schema : HollowSchemaSorter.dependencyOrderedSchemaList(writeEngine.getSchemas())) { if(!compactionTargets.contains(schema.getName())) { HollowTypeWriteState writeState = writeEngine.getTypeState(schema.getName()); writeState.addAllObjectsFromPreviousCycle(); BitSet typeRelocatedOrdinals = relocatedOrdinals.get(schema.getName()); if(typeRelocatedOrdinals != null) { HollowTypeReadState readState = readEngine.getTypeState(schema.getName()); IntMap remappedOrdinals = new IntMap(typeRelocatedOrdinals.cardinality()); boolean preserveHashPositions = shouldPreserveHashPositions(schema); HollowRecordCopier copier = HollowRecordCopier.createCopier(readState, remapper, preserveHashPositions); int remapOrdinal = typeRelocatedOrdinals.nextSetBit(0); while(remapOrdinal != -1) { HollowWriteRecord rec = copier.copy(remapOrdinal); int newOrdinal = writeState.add(rec); remappedOrdinals.put(remapOrdinal, newOrdinal); writeState.removeOrdinalFromThisCycle(remapOrdinal); remapOrdinal = typeRelocatedOrdinals.nextSetBit(remapOrdinal + 1); } remapper.addOrdinalRemapping(schema.getName(), remappedOrdinals); } } } } /** * Find candidate types for compaction. No two types in the returned set will have a dependency relationship, either * directly or transitively. */ private Set<String> findCompactionTargets() { List<HollowSchema> schemas = HollowSchemaSorter.dependencyOrderedSchemaList(readEngine.getSchemas()); Set<String> typesToCompact = new HashSet<String>(); for(HollowSchema schema : schemas) { if(isCompactionCandidate(schema.getName())) { if(!candidateIsDependentOnAnyTargetedType(schema.getName(), typesToCompact)) typesToCompact.add(schema.getName()); } } return typesToCompact; } private boolean isCompactionCandidate(String typeName) { HollowTypeReadState typeState = readEngine.getTypeState(typeName); BitSet populatedOrdinals = typeState.getListener(PopulatedOrdinalListener.class).getPopulatedOrdinals(); double numOrdinals = populatedOrdinals.length(); double numHoles = populatedOrdinals.length() - populatedOrdinals.cardinality(); double holePercentage = numHoles / numOrdinals * 100d; long approximateHoleCostInBytes = typeState.getApproximateHoleCostInBytes(); boolean isCompactionCandidate = holePercentage > (double)minCandidateHolePercentage && approximateHoleCostInBytes > minCandidateHoleCostInBytes; return isCompactionCandidate; } private boolean candidateIsDependentOnAnyTargetedType(String type, Set<String> targetedTypes) { for(String targetedType : targetedTypes) { if(HollowSchemaSorter.typeIsTransitivelyDependent(readEngine, type, targetedType)) return true; } return false; } private boolean shouldPreserveHashPositions(HollowSchema schema) { switch(schema.getSchemaType()) { case MAP: return readEngine.getTypesWithDefinedHashCodes().contains(((HollowMapSchema)schema).getKeyType()); case SET: return readEngine.getTypesWithDefinedHashCodes().contains(((HollowSetSchema)schema).getElementType()); default: return false; } } /** * A configuration that specifies when a type is a candidate for compaction. */ public static class CompactionConfig { private final long minCandidateHoleCostInBytes; private final int minCandidateHolePercentage; /** * Create a new compaction. Both of the criteria specified by the following parameters must be met in order for a type * to be considered a candidate for compaction. * * @param minCandidateHoleCostInBytes identify a type as a candidate for compaction only when the bytes used by ordinal holes exceeds this value * @param minCandidateHolePercentage identify a type as a candidate for compaction only when the percentage of space used by ordinal holes exceeds this value */ public CompactionConfig(long minCandidateHoleCostInBytes, int minCandidateHolePercentage) { this.minCandidateHoleCostInBytes = minCandidateHoleCostInBytes; this.minCandidateHolePercentage = minCandidateHolePercentage; } public long getMinCandidateHoleCostInBytes() { return minCandidateHoleCostInBytes; } public int getMinCandidateHolePercentage() { return minCandidateHolePercentage; } } }
8,891
0
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools/combine/HollowCombinerExcludeOrdinalsCopyDirector.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.tools.combine; import com.netflix.hollow.core.read.engine.HollowTypeReadState; import java.util.BitSet; import java.util.Map; /** * An implementation of {@link HollowCombinerCopyDirector} which specifies the ordinals to <i>include</i> in the * copy operation for a single state engine. * * @author dkoszewnik * */ public class HollowCombinerExcludeOrdinalsCopyDirector implements HollowCombinerCopyDirector { private final Map<String, BitSet> excludedOrdinals; public HollowCombinerExcludeOrdinalsCopyDirector(Map<String, BitSet> excludedOrdinals) { this.excludedOrdinals = excludedOrdinals; } @Override public boolean shouldCopy(HollowTypeReadState typeState, int ordinal) { BitSet typeExcludedOrdinals = excludedOrdinals.get(typeState.getSchema().getName()); if(typeExcludedOrdinals == null) return true; return !typeExcludedOrdinals.get(ordinal); } }
8,892
0
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools/combine/IdentityOrdinalRemapper.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.tools.combine; /** * An implementation of the OrdinalRemapper for when ordinals are not actually remapped. Not intended for external consumption. * * @author dkoszewnik * */ public class IdentityOrdinalRemapper implements OrdinalRemapper { public static IdentityOrdinalRemapper INSTANCE = new IdentityOrdinalRemapper(); private IdentityOrdinalRemapper() { } @Override public int getMappedOrdinal(String type, int originalOrdinal) { return originalOrdinal; } @Override public void remapOrdinal(String type, int originalOrdinal, int mappedOrdinal) { throw new UnsupportedOperationException("Cannot remap ordinals in an IdentityOrdinalRemapper"); } @Override public boolean ordinalIsMapped(String type, int originalOrdinal) { return true; } }
8,893
0
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools/combine/HollowCombiner.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.tools.combine; import com.netflix.hollow.core.index.HollowPrimaryKeyIndex; import com.netflix.hollow.core.index.key.PrimaryKey; import com.netflix.hollow.core.memory.ByteArrayOrdinalMap; import com.netflix.hollow.core.memory.ByteDataArray; import com.netflix.hollow.core.memory.pool.WastefulRecycler; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.read.engine.HollowTypeReadState; import com.netflix.hollow.core.read.engine.PopulatedOrdinalListener; import com.netflix.hollow.core.schema.HollowMapSchema; import com.netflix.hollow.core.schema.HollowObjectSchema; import com.netflix.hollow.core.schema.HollowSchema; import com.netflix.hollow.core.schema.HollowSchema.SchemaType; import com.netflix.hollow.core.schema.HollowSchemaSorter; import com.netflix.hollow.core.schema.HollowSetSchema; import com.netflix.hollow.core.util.HollowWriteStateCreator; import com.netflix.hollow.core.util.SimultaneousExecutor; import com.netflix.hollow.core.write.HollowHashableWriteRecord; import com.netflix.hollow.core.write.HollowHashableWriteRecord.HashBehavior; import com.netflix.hollow.core.write.HollowTypeWriteState; import com.netflix.hollow.core.write.HollowWriteRecord; import com.netflix.hollow.core.write.HollowWriteStateEngine; import com.netflix.hollow.core.write.copy.HollowRecordCopier; import java.util.ArrayList; import java.util.BitSet; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; /** * The HollowCombiner is used to copy data from one or more copies of hollow datasets (a {@link HollowReadStateEngine}) into a single hollow dataset (a {@link HollowWriteStateEngine}). * <p> * By default, a HollowCombiner will copy all records from each provided {@link HollowReadStateEngine} into the destination. * <p> * A {@link HollowCombinerCopyDirector} can be provided, which will specify which specific ordinals to include/exclude while copying. * <p> * A set of {@link PrimaryKey} can be provided, which will ensure that no duplicate records, as defined by any of the provided keys, will be added to the destination state. * * @author dkoszewnik * */ public class HollowCombiner { private final HollowReadStateEngine[] inputs; private final OrdinalRemapper[] ordinalRemappers; private final HollowWriteStateEngine output; private final Set<String> typeNamesWithDefinedHashCodes; private final Set<String> ignoredTypes; private final HollowCombinerCopyDirector copyDirector; private List<PrimaryKey> primaryKeys; private final ThreadLocal<Map<String, HollowCombinerCopier>> copiersPerType; private final Map<String, ByteArrayOrdinalMap> hashOrderIndependentOrdinalMaps; /** * @param inputs the set of {@link HollowReadStateEngine} to combine data from. */ public HollowCombiner(HollowReadStateEngine... inputs) { this(HollowWriteStateCreator.createWithSchemas(validateInputs(inputs)[0].getSchemas()), inputs); } static HollowReadStateEngine[] validateInputs(HollowReadStateEngine... inputs) { Objects.requireNonNull(inputs); if (inputs.length == 0) { throw new IllegalArgumentException("No input read state engines"); } return inputs; } /** * @param director a {@link HollowCombinerCopyDirector} which will specify which specific records to copy from the input(s). * @param inputs the set of {@link HollowReadStateEngine} to combine data from. */ public HollowCombiner(HollowCombinerCopyDirector director, HollowReadStateEngine... inputs) { this(director, HollowWriteStateCreator.createWithSchemas(inputs[0].getSchemas()), inputs); } /** * @param output the {@link HollowWriteStateEngine} to use as the destination. * @param inputs the set of {@link HollowReadStateEngine} to combine data from. */ public HollowCombiner(HollowWriteStateEngine output, HollowReadStateEngine... inputs) { this(HollowCombinerCopyDirector.DEFAULT_DIRECTOR, output, inputs); } /** * @param copyDirector a {@link HollowCombinerCopyDirector} which will specify which specific records to copy from the input(s). * @param output the {@link HollowWriteStateEngine} to use as the destination. * @param inputs the set of {@link HollowReadStateEngine} to combine data from. */ public HollowCombiner(HollowCombinerCopyDirector copyDirector, HollowWriteStateEngine output, HollowReadStateEngine... inputs) { Objects.requireNonNull(copyDirector); Objects.requireNonNull(output); this.inputs = validateInputs(inputs); this.output = output; this.typeNamesWithDefinedHashCodes = getAllTypesWithDefinedHashCodes(); this.ordinalRemappers = new OrdinalRemapper[inputs.length]; this.copiersPerType = new ThreadLocal<>(); this.hashOrderIndependentOrdinalMaps = new HashMap<>(); this.ignoredTypes = new HashSet<>(); this.copyDirector = copyDirector; initializePrimaryKeys(); } private Set<String> getAllTypesWithDefinedHashCodes() { Set<String> unionOfTypesWithDefinedHashCodes = new HashSet<>(); for(HollowReadStateEngine input : inputs) { unionOfTypesWithDefinedHashCodes.addAll(input.getTypesWithDefinedHashCodes()); } return unionOfTypesWithDefinedHashCodes; } /** * When provided, a set of {@link PrimaryKey} will ensure that no duplicate records are added to the destination state. * * If multiple records exist in the inputs matching a single value for any of the supplied primary keys, then only one such record * will be copied to the destination. The specific record which is copied will be the record from the input which was supplied first in the constructor * of this HollowCombiner. * * Further, if any record <i>references</i> another record which was omitted because it would have been duplicate based on this rule, then that reference is * remapped in the destination state to the matching record which was chosen to be included. * * @param newKeys the new primary keys */ public void setPrimaryKeys(PrimaryKey... newKeys) { Objects.requireNonNull(newKeys); if (newKeys.length == 0) { return; } if (inputs.length == 1) { return; } /// deduplicate new keys with existing keys //process existing ones first Map<String, PrimaryKey> keysByType = new HashMap<>(); for (PrimaryKey primaryKey : primaryKeys) { keysByType.put(primaryKey.getType(), primaryKey); } // allow override for (PrimaryKey primaryKey : newKeys) { keysByType.put(primaryKey.getType(), primaryKey); } this.primaryKeys = sortPrimaryKeys(new ArrayList<>(keysByType.values())); } public List<PrimaryKey> getPrimaryKeys() { return this.primaryKeys; } private void initializePrimaryKeys() { if (inputs.length == 1) { this.primaryKeys = new ArrayList<>(); return; } List<PrimaryKey> keys = new ArrayList<>(); for (HollowSchema schema : output.getSchemas()) { if (schema.getSchemaType() == SchemaType.OBJECT && !ignoredTypes.contains(schema.getName())) { PrimaryKey pk = ((HollowObjectSchema) schema).getPrimaryKey(); if (pk != null) keys.add(pk); } } this.primaryKeys = sortPrimaryKeys(keys); } private List<PrimaryKey> sortPrimaryKeys(List<PrimaryKey> primaryKeys) { final List<HollowSchema> dependencyOrderedSchemas = HollowSchemaSorter.dependencyOrderedSchemaList(output.getSchemas()); primaryKeys.sort(new Comparator<PrimaryKey>() { public int compare(PrimaryKey o1, PrimaryKey o2) { return schemaDependencyIdx(o1) - schemaDependencyIdx(o2); } private int schemaDependencyIdx(PrimaryKey key) { for (int i = 0; i < dependencyOrderedSchemas.size(); i++) { if (dependencyOrderedSchemas.get(i).getName().equals(key.getType())) return i; } throw new IllegalArgumentException("Primary key defined for non-existent type: " + key.getType()); } }); return primaryKeys; } /** * Specify a set of types not to copy. Be careful: if any included types reference any of the specified types, * behavior is undefined. * * @param typeNames the type names to be ignored */ public void addIgnoredTypes(String... typeNames) { for(String typeName : typeNames) ignoredTypes.add(typeName); } /** * Perform the combine operation. */ public void combine() { SimultaneousExecutor executor = new SimultaneousExecutor(getClass(), "combine"); final int numThreads = executor.getCorePoolSize(); createOrdinalRemappers(); createHashOrderIndependentOrdinalMaps(); final Set<String> processedTypes = new HashSet<>(); final Set<PrimaryKey> processedPrimaryKeys = new HashSet<>(); final Set<PrimaryKey> selectedPrimaryKeys = new HashSet<>(); while(processedTypes.size() < output.getOrderedTypeStates().size()){ /// find the next primary keys for(PrimaryKey key : primaryKeys) { if (!processedPrimaryKeys.contains(key) && !ignoredTypes.contains(key.getType())) { if(!isAnySelectedPrimaryKeyADependencyOf(key.getType(), selectedPrimaryKeys)) { selectedPrimaryKeys.add(key); } } } final Set<String> typesToProcessThisIteration = new HashSet<>(); final Map<String, HollowPrimaryKeyIndex[]> primaryKeyIndexes = new HashMap<>(); final HollowCombinerExcludePrimaryKeysCopyDirector primaryKeyCopyDirector = new HollowCombinerExcludePrimaryKeysCopyDirector(copyDirector); for(HollowSchema schema : output.getSchemas()) { if(!processedTypes.contains(schema.getName()) && !ignoredTypes.contains(schema.getName())) { if(selectedPrimaryKeys.isEmpty() || isAnySelectedPrimaryKeyDependentOn(schema.getName(), selectedPrimaryKeys)) { for(PrimaryKey pk : selectedPrimaryKeys) { if(pk.getType().equals(schema.getName())) { HollowPrimaryKeyIndex[] indexes = new HollowPrimaryKeyIndex[inputs.length]; for(int i=0;i<indexes.length;i++) { if(inputs[i].getTypeState(pk.getType()) != null) indexes[i] = new HollowPrimaryKeyIndex(inputs[i], pk); } for(int i=0;i<indexes.length;i++) { HollowTypeReadState typeState = inputs[i].getTypeState(pk.getType()); if(typeState != null) { BitSet populatedOrdinals = typeState.getListener(PopulatedOrdinalListener.class).getPopulatedOrdinals(); int ordinal = populatedOrdinals.nextSetBit(0); while(ordinal != -1) { if(primaryKeyCopyDirector.shouldCopy(typeState, ordinal)) { Object[] recordKey = indexes[i].getRecordKey(ordinal); for(int j=i+1;j<indexes.length;j++) { primaryKeyCopyDirector.excludeKey(indexes[j], recordKey); } } ordinal = populatedOrdinals.nextSetBit(ordinal + 1); } } } primaryKeyIndexes.put(pk.getType(), indexes); } } typesToProcessThisIteration.add(schema.getName()); } } } if(typesToProcessThisIteration.isEmpty()) break; for(int i=0;i<numThreads;i++) { final int threadNumber = i; executor.execute(() -> { for(int i1 =0; i1 <inputs.length; i1++) { HollowCombinerCopyDirector copyDirector = selectedPrimaryKeys.isEmpty() ? HollowCombiner.this.copyDirector : primaryKeyCopyDirector; HollowReadStateEngine inputEngine = inputs[i1]; OrdinalRemapper ordinalRemapper = selectedPrimaryKeys.isEmpty() ? ordinalRemappers[i1] : new HollowCombinerPrimaryKeyOrdinalRemapper(ordinalRemappers, primaryKeyIndexes, i1); Map<String, HollowCombinerCopier> copierMap = new HashMap<>(); List<HollowCombinerCopier> copierList = new ArrayList<>(); for(String typeName : typesToProcessThisIteration) { HollowTypeReadState readState = inputEngine.getTypeState(typeName); HollowTypeWriteState writeState = output.getTypeState(typeName); if (readState != null && writeState != null) { HollowCombinerCopier copier = new HollowCombinerCopier(readState, writeState, ordinalRemapper); copierList.add(copier); copierMap.put(typeName, copier); } } for(String typeName : processedTypes) { HollowTypeReadState readState = inputEngine.getTypeState(typeName); HollowTypeWriteState writeState = output.getTypeState(typeName); if (readState != null && writeState != null) { HollowCombinerCopier copier = new HollowCombinerCopier(readState, writeState, ordinalRemappers[i1]); copierMap.put(typeName, copier); } } copiersPerType.set(copierMap); int currentOrdinal = threadNumber; while(!copierList.isEmpty()) { copyOrdinalForAllStates(currentOrdinal, copierList, ordinalRemapper, copyDirector); currentOrdinal += numThreads; } } }); } try { executor.awaitSuccessfulCompletionOfCurrentTasks(); } catch(Throwable th) { throw new RuntimeException(th); } processedTypes.addAll(typesToProcessThisIteration); processedPrimaryKeys.addAll(selectedPrimaryKeys); selectedPrimaryKeys.clear(); } executor.shutdown(); } private boolean isAnySelectedPrimaryKeyADependencyOf(String type, Set<PrimaryKey> selectedPrimaryKeys) { for(PrimaryKey selectedKey : selectedPrimaryKeys) { if(HollowSchemaSorter.typeIsTransitivelyDependent(output, type, selectedKey.getType())) return true; } return false; } private boolean isAnySelectedPrimaryKeyDependentOn(String type, Set<PrimaryKey> selectedPrimaryKeys) { for(PrimaryKey selectedKey : selectedPrimaryKeys) { if(HollowSchemaSorter.typeIsTransitivelyDependent(output, selectedKey.getType(), type)) return true; } return false; } /** * @return the destination {@link HollowWriteStateEngine} */ public HollowWriteStateEngine getCombinedStateEngine() { return output; } void copyOrdinalForAllStates(int currentOrdinal, List<HollowCombinerCopier> copiers, OrdinalRemapper ordinalRemapper, HollowCombinerCopyDirector copyDirector) { Iterator<HollowCombinerCopier> iter = copiers.iterator(); while(iter.hasNext()) { HollowCombinerCopier copier = iter.next(); HollowTypeReadState readTypeState = copier.getReadTypeState(); if(currentOrdinal <= readTypeState.maxOrdinal()) { if(copyDirector.shouldCopy(readTypeState, currentOrdinal)) copier.copy(currentOrdinal); } else { iter.remove(); } } } int copyOrdinal(String typeName, int currentOrdinal) { HollowCombinerCopier hollowCombinerCopier = copiersPerType.get().get(typeName); return hollowCombinerCopier == null ? currentOrdinal : hollowCombinerCopier.copy(currentOrdinal); } private OrdinalRemapper[] createOrdinalRemappers() { for(int i=0;i<ordinalRemappers.length;i++) ordinalRemappers[i] = new HollowCombinerOrdinalRemapper(this, inputs[i]); return ordinalRemappers; } private void createHashOrderIndependentOrdinalMaps() { for(HollowSchema schema : output.getSchemas()) { if(isDefinedHashCode(schema)) { hashOrderIndependentOrdinalMaps.put(schema.getName(), new ByteArrayOrdinalMap()); } } } private boolean isDefinedHashCode(HollowSchema schema) { if(schema instanceof HollowSetSchema) return typeNamesWithDefinedHashCodes.contains(((HollowSetSchema)schema).getElementType()); if(schema instanceof HollowMapSchema) return typeNamesWithDefinedHashCodes.contains(((HollowMapSchema)schema).getKeyType()); return false; } private class HollowCombinerCopier { private final HollowRecordCopier copier; private final BitSet populatedOrdinals; private final HollowTypeWriteState writeState; private final OrdinalRemapper ordinalRemapper; private final ByteArrayOrdinalMap hashOrderIndependentOrdinalMap; private final ByteDataArray scratch; HollowCombinerCopier(HollowTypeReadState readState, HollowTypeWriteState writeState, OrdinalRemapper ordinalRemapper) { this.copier = HollowRecordCopier.createCopier(readState, writeState.getSchema(), ordinalRemapper, isDefinedHashCode(readState.getSchema())); this.populatedOrdinals = readState.getListener(PopulatedOrdinalListener.class).getPopulatedOrdinals(); this.writeState = writeState; this.ordinalRemapper = ordinalRemapper; this.hashOrderIndependentOrdinalMap = hashOrderIndependentOrdinalMaps.get(readState.getSchema().getName()); this.scratch = hashOrderIndependentOrdinalMap != null ? new ByteDataArray(WastefulRecycler.SMALL_ARRAY_RECYCLER) : null; } int copy(int ordinal) { if(isOrdinalPopulated(ordinal)) { if(!ordinalRemapper.ordinalIsMapped(getType(), ordinal)) { HollowWriteRecord rec = copier.copy(ordinal); if(hashOrderIndependentOrdinalMap == null) { int outputOrdinal = writeState.add(rec); ordinalRemapper.remapOrdinal(getType(), ordinal, outputOrdinal); return outputOrdinal; } else { scratch.reset(); ((HollowHashableWriteRecord)rec).writeDataTo(scratch, HashBehavior.IGNORED_HASHES); int outputOrdinal = hashOrderIndependentOrdinalMap.get(scratch); if(outputOrdinal != -1) return outputOrdinal; synchronized(hashOrderIndependentOrdinalMap) { outputOrdinal = hashOrderIndependentOrdinalMap.get(scratch); if(outputOrdinal != -1) return outputOrdinal; outputOrdinal = writeState.add(rec); ordinalRemapper.remapOrdinal(getType(), ordinal, outputOrdinal); hashOrderIndependentOrdinalMap.put(scratch, outputOrdinal); } } } return ordinalRemapper.getMappedOrdinal(getType(), ordinal); } return -1; } boolean isOrdinalPopulated(int ordinal) { return populatedOrdinals.get(ordinal); } String getType() { return copier.getReadTypeState().getSchema().getName(); } HollowTypeReadState getReadTypeState() { return copier.getReadTypeState(); } } }
8,894
0
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools/combine/HollowCombinerExcludePrimaryKeysCopyDirector.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.tools.combine; import com.netflix.hollow.core.index.HollowPrimaryKeyIndex; import com.netflix.hollow.core.read.engine.HollowReadStateEngine; import com.netflix.hollow.core.read.engine.HollowTypeReadState; import com.netflix.hollow.tools.traverse.TransitiveSetTraverser; import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Specifies a set of exclusions for a {@link HollowCombiner}'s operation over one or more inputs. * <p> * Exclusions are specified based on record primary keys. * <p> * This is likely the most useful implementation of a {@link HollowCombinerCopyDirector}. * * * @author dkoszewnik * */ public class HollowCombinerExcludePrimaryKeysCopyDirector implements HollowCombinerCopyDirector { private final HollowCombinerCopyDirector baseDirector; private final Map<HollowTypeReadState, BitSet> excludedOrdinals; public HollowCombinerExcludePrimaryKeysCopyDirector() { this(HollowCombinerCopyDirector.DEFAULT_DIRECTOR); } /** * @param baseDirector if primary keys are not matched, delegate to the provided director for the answer to {@link #shouldCopy(HollowTypeReadState, int) } */ public HollowCombinerExcludePrimaryKeysCopyDirector(HollowCombinerCopyDirector baseDirector) { this.excludedOrdinals = new HashMap<HollowTypeReadState, BitSet>(); this.baseDirector = baseDirector; } /** * Exclude the record which matches the specified key. * * @param idx the index in which to query for the key * @param key the key */ public void excludeKey(HollowPrimaryKeyIndex idx, Object... key) { int excludeOrdinal = idx.getMatchingOrdinal(key); if(excludeOrdinal >= 0) { BitSet excludedOrdinals = this.excludedOrdinals.get(idx.getTypeState()); if(excludedOrdinals == null) { excludedOrdinals = new BitSet(idx.getTypeState().maxOrdinal()+1); this.excludedOrdinals.put(idx.getTypeState(), excludedOrdinals); } excludedOrdinals.set(excludeOrdinal); } } /** * Exclude any objects which are referenced by excluded objects. */ public void excludeReferencedObjects() { Set<HollowReadStateEngine> stateEngines = new HashSet<HollowReadStateEngine>(); for(Map.Entry<HollowTypeReadState, BitSet> entry : excludedOrdinals.entrySet()) stateEngines.add(entry.getKey().getStateEngine()); for(HollowReadStateEngine stateEngine : stateEngines) { Map<String, BitSet> typeBitSetsForStateEngine = new HashMap<String, BitSet>(); for(Map.Entry<HollowTypeReadState, BitSet> entry : excludedOrdinals.entrySet()) { if(entry.getKey().getStateEngine() == stateEngine) { String type = entry.getKey().getSchema().getName(); typeBitSetsForStateEngine.put(type, BitSet.valueOf(entry.getValue().toLongArray())); } } TransitiveSetTraverser.addTransitiveMatches(stateEngine, typeBitSetsForStateEngine); for(Map.Entry<String, BitSet> entry : typeBitSetsForStateEngine.entrySet()) excludedOrdinals.put(stateEngine.getTypeState(entry.getKey()), entry.getValue()); } } @Override public boolean shouldCopy(HollowTypeReadState typeState, int ordinal) { BitSet bitSet = excludedOrdinals.get(typeState); if(bitSet != null && bitSet.get(ordinal)) return false; return baseDirector.shouldCopy(typeState, ordinal); } }
8,895
0
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools/combine/HollowCombinerCopyDirector.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.tools.combine; import com.netflix.hollow.core.read.engine.HollowTypeReadState; /** * Specifies specific records (via their ordinals) to include/exclude while copying. * <p> * * The most useful implementation of this is likely the {@link HollowCombinerExcludePrimaryKeysCopyDirector} * * @author dkoszewnik * */ public interface HollowCombinerCopyDirector { /** * @param typeState the read state * @param ordinal the ordinal to copy * @return whether or not to include the specified ordinal from the supplied {@link HollowTypeReadState} in the output. * If this method returns false, then the copier will not attempt to directly copy the matching record. However, if * the matching record is referenced via <i>another</i> record for which this method returns true, then it will still be copied. */ boolean shouldCopy(HollowTypeReadState typeState, int ordinal); HollowCombinerCopyDirector DEFAULT_DIRECTOR = new HollowCombinerCopyDirector() { public boolean shouldCopy(HollowTypeReadState typeName, int ordinal) { return true; } }; }
8,896
0
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools/combine/OrdinalRemapper.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.tools.combine; /** * Remaps ordinals various operations. Not intended for external consumption. * */ public interface OrdinalRemapper { /** * @param type the type name * @param originalOrdinal the original ordinal * @return the remapped ordinal */ public int getMappedOrdinal(String type, int originalOrdinal); /** * Remap an ordinal. * @param type the type name * @param originalOrdinal the original ordinal * @param mappedOrdinal the mapped ordinal */ public void remapOrdinal(String type, int originalOrdinal, int mappedOrdinal); /** * @return whether or not a mapping is already defined. * @param type the type name * @param originalOrdinal the original ordinal */ public boolean ordinalIsMapped(String type, int originalOrdinal); }
8,897
0
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools/combine/HollowCombinerIncludeOrdinalsCopyDirector.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.tools.combine; import com.netflix.hollow.core.read.engine.HollowTypeReadState; import java.util.BitSet; import java.util.Map; /** * An implementation of {@link HollowCombinerCopyDirector} which specifies the ordinals to <i>include</i> in the * copy operation for a single state engine. * * @author dkoszewnik * */ public class HollowCombinerIncludeOrdinalsCopyDirector implements HollowCombinerCopyDirector { private final Map<String, BitSet> includedOrdinals; public HollowCombinerIncludeOrdinalsCopyDirector(Map<String, BitSet> includedOrdinals) { this.includedOrdinals = includedOrdinals; } @Override public boolean shouldCopy(HollowTypeReadState typeState, int ordinal) { BitSet typeIncludedOrdinals = includedOrdinals.get(typeState.getSchema().getName()); if(typeIncludedOrdinals == null) return false; return typeIncludedOrdinals.get(ordinal); } }
8,898
0
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools
Create_ds/hollow/hollow/src/main/java/com/netflix/hollow/tools/combine/HollowCombinerIncludePrimaryKeysCopyDirector.java
/* * Copyright 2016-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.hollow.tools.combine; import com.netflix.hollow.core.index.HollowPrimaryKeyIndex; import com.netflix.hollow.core.read.engine.HollowTypeReadState; /** * Specifies a set of inclusions for a {@link HollowCombiner}'s operation over one or more inputs. * <p> * Inclusions are specified based on record primary keys. * <p> * This is one of the most useful implementations of a {@link HollowCombinerCopyDirector}. * */ public class HollowCombinerIncludePrimaryKeysCopyDirector implements HollowCombinerCopyDirector { private final HollowCombinerExcludePrimaryKeysCopyDirector inverseCopyDirector; public HollowCombinerIncludePrimaryKeysCopyDirector() { this.inverseCopyDirector = new HollowCombinerExcludePrimaryKeysCopyDirector(); } public HollowCombinerIncludePrimaryKeysCopyDirector(HollowCombinerCopyDirector baseDirector) { this.inverseCopyDirector = new HollowCombinerExcludePrimaryKeysCopyDirector(baseDirector); } /** * Include the record which matches the specified key. * * @param idx the index in which to query for the key * @param key the key */ public void includeKey(HollowPrimaryKeyIndex idx, Object... key) { inverseCopyDirector.excludeKey(idx, key); } @Override public boolean shouldCopy(HollowTypeReadState typeState, int ordinal) { return !inverseCopyDirector.shouldCopy(typeState, ordinal); } }
8,899