Search in sources :

Example 6 with CachedView

use of cz.o2.proxima.direct.view.CachedView in project proxima-platform by O2-Czech-Republic.

the class DirectAttributeFamilyProxyDescriptor method getPartitionedCachedView.

private static Optional<CachedView> getPartitionedCachedView(AttrLookup lookup, Context context, AttributeFamilyProxyDescriptor desc) {
    if (desc.getTargetFamilyRead().getAccess().canReadCommitLog() && !desc.getTargetFamilyWrite().getAccess().isReadonly() && desc.getTargetFamilyRead().getAccess().canCreateCachedView()) {
        Optional<CommitLogReader> maybeReader = getCommitLogReader(lookup, context, desc);
        Optional<OnlineAttributeWriter> maybeWriter = getWriter(lookup, context, desc).map(AttributeWriterBase::online);
        if (maybeReader.isPresent() && maybeWriter.isPresent()) {
            return Optional.of(new LocalCachedPartitionedView(desc.getTargetFamilyRead().getEntity(), maybeReader.get(), maybeWriter.get()));
        }
    }
    return Optional.empty();
}
Also used : LocalCachedPartitionedView(cz.o2.proxima.direct.view.LocalCachedPartitionedView) CommitLogReader(cz.o2.proxima.direct.commitlog.CommitLogReader)

Example 7 with CachedView

use of cz.o2.proxima.direct.view.CachedView in project proxima-platform by O2-Czech-Republic.

the class DirectDataOperator method getCachedView.

/**
 * Retrieve {@link CachedView} for given {@link AttributeDescriptor}s.
 *
 * @param attrs the attributes to find cached view for
 * @return optional cached view
 */
public Optional<CachedView> getCachedView(Collection<AttributeDescriptor<?>> attrs) {
    boolean hasTransactions = attrs.stream().anyMatch(a -> a.getTransactionMode() != TransactionMode.NONE);
    Optional<CachedView> view = getFamilyForAttributes(attrs, DirectAttributeFamilyDescriptor::hasCachedView).flatMap(DirectAttributeFamilyDescriptor::getCachedView);
    if (hasTransactions) {
        return view.map(v -> new TransactionalCachedView(this, v));
    }
    return view;
}
Also used : TransactionalCachedView(cz.o2.proxima.direct.transaction.TransactionalCachedView) CachedView(cz.o2.proxima.direct.view.CachedView) TransactionalCachedView(cz.o2.proxima.direct.transaction.TransactionalCachedView)

Example 8 with CachedView

use of cz.o2.proxima.direct.view.CachedView in project proxima-platform by O2-Czech-Republic.

the class TransactionResourceManager method writeResponseAndUpdateState.

@Override
public void writeResponseAndUpdateState(String transactionId, State updateState, String responseId, Response response, CommitCallback callback) {
    CachedTransaction cachedTransaction = openTransactionMap.get(transactionId);
    if (cachedTransaction != null) {
        DirectAttributeFamilyDescriptor responseFamily = cachedTransaction.getResponseFamily();
        DirectAttributeFamilyDescriptor stateFamily = cachedTransaction.getStateFamily();
        final OnlineAttributeWriter writer = cachedTransaction.getCommitWriter();
        final CachedView stateView = cachedTransaction.getStateView();
        long now = System.currentTimeMillis();
        StreamElement stateUpsert = getStateDesc().upsert(transactionId, now, updateState);
        Commit commit = Commit.of(Arrays.asList(new Commit.TransactionUpdate(stateFamily.getDesc().getName(), stateUpsert), new Commit.TransactionUpdate(responseFamily.getDesc().getName(), getResponseDesc().upsert(transactionId, responseId, now, response))));
        synchronized (stateView) {
            ensureTransactionOpen(transactionId, updateState);
            stateView.cache(stateUpsert);
        }
        synchronized (writer) {
            writer.write(getCommitDesc().upsert(transactionId, System.currentTimeMillis(), commit), callback);
        }
    } else {
        log.warn("Transaction {} is not open, don't have a writer to return response {}", transactionId, response);
        callback.commit(true, null);
    }
}
Also used : DirectAttributeFamilyDescriptor(cz.o2.proxima.direct.core.DirectAttributeFamilyDescriptor) CachedView(cz.o2.proxima.direct.view.CachedView) Commit(cz.o2.proxima.transaction.Commit) OnlineAttributeWriter(cz.o2.proxima.direct.core.OnlineAttributeWriter) StreamElement(cz.o2.proxima.storage.StreamElement)

Example 9 with CachedView

use of cz.o2.proxima.direct.view.CachedView in project proxima-platform by O2-Czech-Republic.

the class DirectDataOperatorTest method testProxyCachedView.

@Test
public void testProxyCachedView() {
    EntityDescriptor proxied = repo.getEntity("proxied");
    AttributeDescriptor<?> target = proxied.getAttribute("_e.*", true);
    AttributeDescriptor<?> source = proxied.getAttribute("event.*");
    CachedView view = direct.getFamiliesForAttribute(source).stream().filter(af -> af.getDesc().getAccess().canCreateCachedView()).findAny().flatMap(DirectAttributeFamilyDescriptor::getCachedView).orElseThrow(() -> new IllegalStateException("Missing cached view for " + source));
    RandomAccessReader reader = direct.getFamiliesForAttribute(target).stream().filter(af -> af.getDesc().getAccess().canRandomRead()).findAny().flatMap(DirectAttributeFamilyDescriptor::getRandomAccessReader).orElseThrow(() -> new IllegalStateException("Missing random reader for " + target));
    view.assign(Collections.singletonList(() -> 0));
    long now = System.currentTimeMillis();
    StreamElement update = StreamElement.upsert(proxied, source, UUID.randomUUID().toString(), "key", "event.def", now, "test2".getBytes(StandardCharsets.UTF_8));
    assertFalse(reader.get("key", target.toAttributePrefix() + "def", target, now).isPresent());
    view.write(update, (succ, exc) -> {
    });
    assertTrue(reader.get("key", target.toAttributePrefix() + "raw-def", target, now).isPresent());
    assertTrue(view.get("key", source.toAttributePrefix() + "def", source, now).isPresent());
}
Also used : Arrays(java.util.Arrays) TestTracker(cz.o2.proxima.storage.watermark.GlobalWatermarkThroughputLimiterTest.TestTracker) EntityDescriptor(cz.o2.proxima.repository.EntityDescriptor) StorageType(cz.o2.proxima.storage.StorageType) DummyFilter(cz.o2.proxima.util.DummyFilter) EventDataToDummy(cz.o2.proxima.transform.EventDataToDummy) CachedView(cz.o2.proxima.direct.view.CachedView) StreamElement(cz.o2.proxima.storage.StreamElement) TransformationRunner(cz.o2.proxima.util.TransformationRunner) Map(java.util.Map) AttributeFamilyProxyDescriptor(cz.o2.proxima.repository.AttributeFamilyProxyDescriptor) Assert.fail(org.junit.Assert.fail) URI(java.net.URI) TransformationDescriptor(cz.o2.proxima.repository.TransformationDescriptor) Optionals(cz.o2.proxima.util.Optionals) TestUtils(cz.o2.proxima.util.TestUtils) Set(java.util.Set) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) GlobalWatermarkThroughputLimiter(cz.o2.proxima.storage.watermark.GlobalWatermarkThroughputLimiter) Objects(java.util.Objects) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) ConfigRepository(cz.o2.proxima.repository.ConfigRepository) KeyValue(cz.o2.proxima.direct.randomaccess.KeyValue) Assert.assertFalse(org.junit.Assert.assertFalse) Accept(cz.o2.proxima.storage.internal.AbstractDataAccessorFactory.Accept) Optional(java.util.Optional) ElementWiseTransformation(cz.o2.proxima.transform.ElementWiseTransformation) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ThroughputLimiter(cz.o2.proxima.storage.ThroughputLimiter) AttributeProxyDescriptor(cz.o2.proxima.repository.AttributeProxyDescriptor) Iterables(com.google.common.collect.Iterables) LimitedCommitLogReader(cz.o2.proxima.direct.commitlog.CommitLogReaders.LimitedCommitLogReader) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) ConfigFactory(com.typesafe.config.ConfigFactory) CommitLogReader(cz.o2.proxima.direct.commitlog.CommitLogReader) RandomAccessReader(cz.o2.proxima.direct.randomaccess.RandomAccessReader) PassthroughFilter(cz.o2.proxima.storage.PassthroughFilter) Config(com.typesafe.config.Config) Assert.assertNotNull(org.junit.Assert.assertNotNull) AttributeDescriptor(cz.o2.proxima.repository.AttributeDescriptor) Assert.assertTrue(org.junit.Assert.assertTrue) CommitLogObserver(cz.o2.proxima.direct.commitlog.CommitLogObserver) IOException(java.io.IOException) Test(org.junit.Test) AttributeFamilyDescriptor(cz.o2.proxima.repository.AttributeFamilyDescriptor) NotSerializableException(java.io.NotSerializableException) ReplicationRunner.runAttributeReplicas(cz.o2.proxima.util.ReplicationRunner.runAttributeReplicas) TimeUnit(java.util.concurrent.TimeUnit) GlobalWatermarkTracker(cz.o2.proxima.storage.watermark.GlobalWatermarkTracker) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) EntityDescriptor(cz.o2.proxima.repository.EntityDescriptor) CachedView(cz.o2.proxima.direct.view.CachedView) RandomAccessReader(cz.o2.proxima.direct.randomaccess.RandomAccessReader) StreamElement(cz.o2.proxima.storage.StreamElement) Test(org.junit.Test)

Example 10 with CachedView

use of cz.o2.proxima.direct.view.CachedView in project proxima-platform by O2-Czech-Republic.

the class InMemStorage method createAccessor.

@Override
public DataAccessor createAccessor(DirectDataOperator op, AttributeFamilyDescriptor familyDescriptor) {
    final EntityDescriptor entity = familyDescriptor.getEntity();
    final URI uri = familyDescriptor.getStorageUri();
    final Map<String, Object> cfg = familyDescriptor.getCfg();
    log.info("Creating accessor {} for URI {}", getClass(), uri);
    holder().observers.computeIfAbsent(uri, k -> Collections.synchronizedNavigableMap(new TreeMap<>()));
    final int numPartitions = Optional.ofNullable(cfg.get(NUM_PARTITIONS)).map(v -> Integer.parseInt(v.toString())).orElse(1);
    final Partitioner partitioner = Optional.ofNullable(cfg.get(ConfigConstants.PARTITIONER)).map(name -> Classpath.newInstance(name.toString(), Partitioner.class)).orElseGet(KeyAttributePartitioner::new);
    final Repository opRepo = op.getRepository();
    final RepositoryFactory repositoryFactory = opRepo.asFactory();
    final OnlineAttributeWriter.Factory<?> writerFactory = new Writer(entity, uri, numPartitions, partitioner).asFactory();
    final CommitLogReader.Factory<?> commitLogReaderFactory = new InMemCommitLogReader(entity, uri, op.getContext().getExecutorFactory(), partitioner, numPartitions).asFactory();
    final RandomAccessReader.Factory<Reader> randomAccessReaderFactory;
    final BatchLogReader.Factory<Reader> batchLogReaderFactory;
    final CachedView.Factory cachedViewFactory;
    if (numPartitions > 1) {
        randomAccessReaderFactory = null;
        batchLogReaderFactory = null;
        cachedViewFactory = null;
    } else {
        final ReaderFactory readerFactory = new Reader(entity, uri, op.getContext().getExecutorFactory()).asFactory();
        randomAccessReaderFactory = readerFactory;
        batchLogReaderFactory = readerFactory;
        cachedViewFactory = new LocalCachedPartitionedView(entity, commitLogReaderFactory.apply(opRepo), writerFactory.apply(opRepo)).asFactory();
    }
    return new DataAccessor() {

        private static final long serialVersionUID = 1L;

        @Nullable
        private transient Repository repo = opRepo;

        @Override
        public URI getUri() {
            return uri;
        }

        @Override
        public Optional<AttributeWriterBase> getWriter(Context context) {
            Objects.requireNonNull(context);
            return Optional.of(writerFactory.apply(repo()));
        }

        @Override
        public Optional<CommitLogReader> getCommitLogReader(Context context) {
            Objects.requireNonNull(context);
            return Optional.of(commitLogReaderFactory.apply(repo()));
        }

        @Override
        public Optional<RandomAccessReader> getRandomAccessReader(Context context) {
            Objects.requireNonNull(context);
            return Optional.ofNullable(randomAccessReaderFactory).map(item -> item.apply(repo()));
        }

        @Override
        public Optional<CachedView> getCachedView(Context context) {
            Objects.requireNonNull(context);
            return Optional.ofNullable(cachedViewFactory).map(item -> item.apply(repo()));
        }

        @Override
        public Optional<BatchLogReader> getBatchLogReader(Context context) {
            Objects.requireNonNull(context);
            return Optional.ofNullable(batchLogReaderFactory).map(item -> item.apply(repo()));
        }

        private Repository repo() {
            if (this.repo == null) {
                this.repo = repositoryFactory.apply();
            }
            return this.repo;
        }
    };
}
Also used : Partitioners(cz.o2.proxima.storage.commitlog.Partitioners) BatchLogReader(cz.o2.proxima.direct.batch.BatchLogReader) ConfigConstants(cz.o2.proxima.repository.ConfigConstants) RepositoryFactory(cz.o2.proxima.repository.RepositoryFactory) KeyAttributePartitioner(cz.o2.proxima.storage.commitlog.KeyAttributePartitioner) Future(java.util.concurrent.Future) WatermarkEstimator(cz.o2.proxima.time.WatermarkEstimator) Pair(cz.o2.proxima.util.Pair) Map(java.util.Map) Optionals(cz.o2.proxima.util.Optionals) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) Set(java.util.Set) ObserveHandle(cz.o2.proxima.direct.commitlog.ObserveHandle) Serializable(java.io.Serializable) CountDownLatch(java.util.concurrent.CountDownLatch) Slf4j(lombok.extern.slf4j.Slf4j) KeyValue(cz.o2.proxima.direct.randomaccess.KeyValue) DirectDataOperator(cz.o2.proxima.direct.core.DirectDataOperator) AbstractOnlineAttributeWriter(cz.o2.proxima.direct.core.AbstractOnlineAttributeWriter) Consumer(cz.o2.proxima.functional.Consumer) OffsetCommitter(cz.o2.proxima.direct.commitlog.CommitLogObserver.OffsetCommitter) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Supplier(java.util.function.Supplier) ObserverUtils(cz.o2.proxima.direct.commitlog.ObserverUtils) ArrayList(java.util.ArrayList) Lists(com.google.common.collect.Lists) DataAccessor(cz.o2.proxima.direct.core.DataAccessor) RawOffset(cz.o2.proxima.direct.randomaccess.RawOffset) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Watermarks(cz.o2.proxima.time.Watermarks) CommitLogReader(cz.o2.proxima.direct.commitlog.CommitLogReader) Nullable(javax.annotation.Nullable) WatermarkIdlePolicy(cz.o2.proxima.time.WatermarkIdlePolicy) AbstractStorage(cz.o2.proxima.storage.AbstractStorage) MoreObjects(com.google.common.base.MoreObjects) CommitLogObserver(cz.o2.proxima.direct.commitlog.CommitLogObserver) AtomicLong(java.util.concurrent.atomic.AtomicLong) Partitioner(cz.o2.proxima.storage.commitlog.Partitioner) Lock(java.util.concurrent.locks.Lock) TreeMap(java.util.TreeMap) AutoService(com.google.auto.service.AutoService) Preconditions(com.google.common.base.Preconditions) Position(cz.o2.proxima.storage.commitlog.Position) ScheduledFuture(java.util.concurrent.ScheduledFuture) AttributeWriterBase(cz.o2.proxima.direct.core.AttributeWriterBase) Partition(cz.o2.proxima.storage.Partition) EntityDescriptor(cz.o2.proxima.repository.EntityDescriptor) TerminationContext(cz.o2.proxima.direct.batch.TerminationContext) CachedView(cz.o2.proxima.direct.view.CachedView) StreamElement(cz.o2.proxima.storage.StreamElement) PartitionedWatermarkEstimator(cz.o2.proxima.time.PartitionedWatermarkEstimator) SerializationException(cz.o2.proxima.scheme.SerializationException) URI(java.net.URI) TypeReference(com.fasterxml.jackson.core.type.TypeReference) OffsetExternalizer(cz.o2.proxima.direct.commitlog.OffsetExternalizer) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) UUID(java.util.UUID) NavigableMap(java.util.NavigableMap) CommitCallback(cz.o2.proxima.direct.core.CommitCallback) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) OnNextContext(cz.o2.proxima.direct.batch.BatchLogObserver.OnNextContext) Entry(java.util.Map.Entry) Optional(java.util.Optional) MinimalPartitionWatermarkEstimator(cz.o2.proxima.direct.time.MinimalPartitionWatermarkEstimator) RandomOffset(cz.o2.proxima.direct.randomaccess.RandomOffset) SortedMap(java.util.SortedMap) ObserverUtils.asRepartitionContext(cz.o2.proxima.direct.commitlog.ObserverUtils.asRepartitionContext) Context(cz.o2.proxima.direct.core.Context) LocalCachedPartitionedView(cz.o2.proxima.direct.view.LocalCachedPartitionedView) Getter(lombok.Getter) BoundedOutOfOrdernessWatermarkEstimator(cz.o2.proxima.direct.time.BoundedOutOfOrdernessWatermarkEstimator) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) OnlineAttributeWriter(cz.o2.proxima.direct.core.OnlineAttributeWriter) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) BatchLogObservers(cz.o2.proxima.direct.batch.BatchLogObservers) HashSet(java.util.HashSet) Factory(cz.o2.proxima.functional.Factory) RandomAccessReader(cz.o2.proxima.direct.randomaccess.RandomAccessReader) ExecutorService(java.util.concurrent.ExecutorService) Classpath(cz.o2.proxima.util.Classpath) Repository(cz.o2.proxima.repository.Repository) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) AttributeDescriptor(cz.o2.proxima.repository.AttributeDescriptor) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) BatchLogObserver(cz.o2.proxima.direct.batch.BatchLogObserver) AttributeFamilyDescriptor(cz.o2.proxima.repository.AttributeFamilyDescriptor) Offset(cz.o2.proxima.direct.commitlog.Offset) TimeUnit(java.util.concurrent.TimeUnit) DataAccessorFactory(cz.o2.proxima.direct.core.DataAccessorFactory) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) CachedView(cz.o2.proxima.direct.view.CachedView) DataAccessor(cz.o2.proxima.direct.core.DataAccessor) CommitLogReader(cz.o2.proxima.direct.commitlog.CommitLogReader) BatchLogReader(cz.o2.proxima.direct.batch.BatchLogReader) CommitLogReader(cz.o2.proxima.direct.commitlog.CommitLogReader) RandomAccessReader(cz.o2.proxima.direct.randomaccess.RandomAccessReader) KeyAttributePartitioner(cz.o2.proxima.storage.commitlog.KeyAttributePartitioner) URI(java.net.URI) RandomAccessReader(cz.o2.proxima.direct.randomaccess.RandomAccessReader) AbstractOnlineAttributeWriter(cz.o2.proxima.direct.core.AbstractOnlineAttributeWriter) OnlineAttributeWriter(cz.o2.proxima.direct.core.OnlineAttributeWriter) RepositoryFactory(cz.o2.proxima.repository.RepositoryFactory) KeyAttributePartitioner(cz.o2.proxima.storage.commitlog.KeyAttributePartitioner) Partitioner(cz.o2.proxima.storage.commitlog.Partitioner) TerminationContext(cz.o2.proxima.direct.batch.TerminationContext) OnNextContext(cz.o2.proxima.direct.batch.BatchLogObserver.OnNextContext) ObserverUtils.asRepartitionContext(cz.o2.proxima.direct.commitlog.ObserverUtils.asRepartitionContext) Context(cz.o2.proxima.direct.core.Context) AttributeWriterBase(cz.o2.proxima.direct.core.AttributeWriterBase) TreeMap(java.util.TreeMap) EntityDescriptor(cz.o2.proxima.repository.EntityDescriptor) Repository(cz.o2.proxima.repository.Repository) LocalCachedPartitionedView(cz.o2.proxima.direct.view.LocalCachedPartitionedView) BatchLogReader(cz.o2.proxima.direct.batch.BatchLogReader) AbstractOnlineAttributeWriter(cz.o2.proxima.direct.core.AbstractOnlineAttributeWriter) OnlineAttributeWriter(cz.o2.proxima.direct.core.OnlineAttributeWriter)

Aggregations

CachedView (cz.o2.proxima.direct.view.CachedView)26 KeyValue (cz.o2.proxima.direct.randomaccess.KeyValue)21 CountDownLatch (java.util.concurrent.CountDownLatch)21 Test (org.junit.Test)21 OnlineAttributeWriter (cz.o2.proxima.direct.core.OnlineAttributeWriter)20 ArrayList (java.util.ArrayList)15 CommitLogReader (cz.o2.proxima.direct.commitlog.CommitLogReader)14 StreamElement (cz.o2.proxima.storage.StreamElement)14 AttributeDescriptor (cz.o2.proxima.repository.AttributeDescriptor)13 CommitLogObserver (cz.o2.proxima.direct.commitlog.CommitLogObserver)12 ObserveHandle (cz.o2.proxima.direct.commitlog.ObserveHandle)12 AttributeFamilyDescriptor (cz.o2.proxima.repository.AttributeFamilyDescriptor)12 EntityDescriptor (cz.o2.proxima.repository.EntityDescriptor)12 Optionals (cz.o2.proxima.util.Optionals)12 Lists (com.google.common.collect.Lists)11 ConfigFactory (com.typesafe.config.ConfigFactory)11 DirectDataOperator (cz.o2.proxima.direct.core.DirectDataOperator)11 Partition (cz.o2.proxima.storage.Partition)11 MoreObjects (com.google.common.base.MoreObjects)10 Offset (cz.o2.proxima.direct.commitlog.Offset)10