io.vlingo.symbio.State Java Examples

The following examples show how to use io.vlingo.symbio.State. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DispatcherControlActor.java    From vlingo-symbio with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void dispatchUnconfirmed() {
  try {
    final LocalDateTime now = LocalDateTime.now();
    final Collection<? extends Dispatchable<? extends Entry<?>, ? extends State<?>>> dispatchables = delegate.allUnconfirmedDispatchableStates();
    for (final Dispatchable<? extends Entry<?>, ? extends State<?>> dispatchable : dispatchables) {
      final LocalDateTime then = dispatchable.createdOn();
      final Duration duration = Duration.between(then, now);
      if (Math.abs(duration.toMillis()) > confirmationExpiration) {
        dispatchers.forEach(d -> d.dispatch(dispatchable));
      }
    }
  } catch (final Exception e) {
    logger().error(getClass().getSimpleName() + " dispatchUnconfirmed() failed because: " + e.getMessage(), e);
  }
}
 
Example #2
Source File: InMemoryStreamReader.java    From vlingo-symbio with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public Completes<EntityStream<T>> streamFor(final String streamName, final int fromStreamVersion) {
  int version = fromStreamVersion;
  State<T> snapshot = snapshotsView.get(streamName);
  if (snapshot != null) {
    if (snapshot.dataVersion > version) {
      version = snapshot.dataVersion;
    } else {
      snapshot = null; // reading from beyond snapshot
    }
  }
  final List<BaseEntry<T>> entries = new ArrayList<>();
  final Map<Integer,Integer> versionIndexes = streamIndexesView.get(streamName);
  if (versionIndexes != null) {
    Integer journalIndex = versionIndexes.get(version);

    while (journalIndex != null) {
      final BaseEntry<T> entry = journalView.get(journalIndex);
      entries.add(entry);
      journalIndex = versionIndexes.get(++version);
    }
  }
  return Completes.withSuccess(new EntityStream<>(streamName, version - 1, entries, snapshot));
}
 
Example #3
Source File: SourcedTypeRegistry.java    From vlingo-lattice with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Construct my default state with {@code sourcedTypes} creating the {@code Journal}
 * of type {@code journalType}, and register me with the {@code world}.
 * @param world the World to which I am registered
 * @param journalType the concrete {@code Actor} type of the Journal to create
 * @param dispatcher the {@code Dispatcher<Dispatchable<Entry<?>,State<?>>>} of the journalType
 * @param sourcedTypes all {@code Class<Sourced<?>>} types of to register
 * @param <A> the type of Actor used for the Journal implementation
 * @param <S> the {@code Sourced<?>} types to register
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public <A extends Actor, S extends Sourced<?>> SourcedTypeRegistry(
        final World world,
        final Class<A> journalType,
        final Dispatcher<Dispatchable<Entry<?>,State<?>>> dispatcher,
        final Class<S> ... sourcedTypes) {

  this(world);

  final Journal<?> journal = world.actorFor(Journal.class, journalType, dispatcher);

  EntryAdapterProvider.instance(world);

  for (Class<S> sourcedType : sourcedTypes) {
    this.register(new Info(journal, sourcedType, sourcedType.getSimpleName()));
  }
}
 
Example #4
Source File: InMemoryObjectStoreDelegate.java    From vlingo-symbio with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public QuerySingleResult queryObject(final QueryExpression expression) {
  final String id;
  if (expression.isListQueryExpression()) {
    id = idParameterAsString(expression.asListQueryExpression().parameters.get(0));
  } else if (expression.isMapQueryExpression()) {
    id = idParameterAsString(expression.asMapQueryExpression().parameters.get("id"));
  } else {
    throw new StorageException(Result.Error, "Unknown query type: " + expression);
  }

  final Map<Long, State<?>> store = stores.computeIfAbsent(expression.type, (type) -> new HashMap<>());
  final State<?> found = (id == null || id.equals("-1")) ? null : store.get(Long.parseLong(id));

  final Object result = Optional
          .ofNullable(found)
          .map(stateAdapterProvider::fromRaw)
          .orElse(null);
  return new QuerySingleResult(result);
}
 
Example #5
Source File: InMemoryObjectStoreActor.java    From vlingo-symbio with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public <T extends StateObject, E> void persistAll(Collection<StateSources<T, E>> allStateSources, Metadata metadata, long updateId, PersistResultInterest interest, Object object) {
  final Collection<T> allPersistentObjects = new ArrayList<>();
  try {
    for (StateSources<T, E> stateSources : allStateSources) {
      final T stateObject = stateSources.stateObject();
      final State<?> state = storeDelegate.persist(stateObject, updateId, metadata);
      allPersistentObjects.add(stateObject);

      final int entryVersion = (int) stateSources.stateObject().version();
      final List<BaseEntry<?>> entries = entryAdapterProvider.asEntries(stateSources.sources(), entryVersion, metadata);
      this.storeDelegate.persistEntries(entries);

      final Dispatchable<BaseEntry<?>, State<?>> dispatchable = buildDispatchable(state, entries);
      this.storeDelegate.persistDispatchable(dispatchable);

      dispatch(buildDispatchable(state, entries));
    }

    interest.persistResultedIn(Success.of(Result.Success), allPersistentObjects, allPersistentObjects.size(), allPersistentObjects.size(), object);
  } catch (final StorageException e){
    logger().error("Failed to persist all objects", e);
    interest.persistResultedIn(Failure.of(e), null, 0, 0, object);
  }
}
 
Example #6
Source File: InMemoryObjectStoreActor.java    From vlingo-symbio with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public <T extends StateObject, E> void persist(StateSources<T, E> stateSources, Metadata metadata, long updateId, PersistResultInterest interest, Object object) {
  try {
    final T stateObject = stateSources.stateObject();
    final List<Source<E>> sources = stateSources.sources();

    final State<?> raw = storeDelegate.persist(stateObject, updateId, metadata);

    final int entryVersion = (int) stateSources.stateObject().version();
    final List<BaseEntry<?>> entries = entryAdapterProvider.asEntries(sources, entryVersion, metadata);
    final Dispatchable<BaseEntry<?>, State<?>> dispatchable = buildDispatchable(raw, entries);

    this.storeDelegate.persistEntries(entries);
    this.storeDelegate.persistDispatchable(dispatchable);

    dispatch(dispatchable);
    interest.persistResultedIn(Success.of(Result.Success), stateObject, 1, 1, object);
  } catch (StorageException e){
    logger().error("Failed to persist all objects", e);
    interest.persistResultedIn(Failure.of(e), null, 0, 0, object);
  }
}
 
Example #7
Source File: InMemoryObjectStoreActor.java    From vlingo-symbio with Mozilla Public License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public InMemoryObjectStoreActor(
        final List<Dispatcher<Dispatchable<BaseEntry<?>,State<?>>>> dispatchers,
        final long checkConfirmationExpirationInterval,
        final long confirmationExpiration ) {

  this.entryAdapterProvider = EntryAdapterProvider.instance(stage().world());

  this.dispatchers = dispatchers;

  this.entryReaders = new HashMap<>();

  this.storeDelegate = new InMemoryObjectStoreDelegate(StateAdapterProvider.instance(stage().world()));

  this.dispatcherControl = stage().actorFor(
          DispatcherControl.class,
          Definition.has(
                  DispatcherControlActor.class,
                  new DispatcherControlInstantiator(
                          dispatchers,
                          this.storeDelegate,
                          checkConfirmationExpirationInterval,
                          confirmationExpiration)));
}
 
Example #8
Source File: InMemoryObjectStoreActorTest.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void testThatMultiPersistQueryResolves() {
  dispatcher.afterCompleting(3);
  final AccessSafely persistAllAccess = persistInterest.afterCompleting(1);

  final Person person1 = new Person("Tom Jones", 78);
  final Person person2 = new Person("Dean Martin", 78);
  final Person person3 = new Person("Sally Struthers", 71);
  objectStore.persistAll(Arrays.asList(StateSources.of(person1), StateSources.of(person2), StateSources.of(person3)), persistInterest);
  final int persistSize = persistAllAccess.readFrom("size");
  assertEquals(3, persistSize);

  final AccessSafely queryAllAccess = queryResultInterest.afterCompleting(1);
  objectStore.queryAll(QueryExpression.using(Person.class, "findAll"), queryResultInterest, null);
  final int querySize = queryAllAccess.readFrom("size");
  assertEquals(3, querySize);
  assertEquals(person1, queryAllAccess.readFrom("object", 0));
  assertEquals(person2, queryAllAccess.readFrom("object", 1));
  assertEquals(person3, queryAllAccess.readFrom("object", 2));

  assertEquals(3, dispatcher.dispatchedCount());

  Dispatchable<Entry<?>, State<?>> dispatched = dispatcher.getDispatched().get(0);
  validateDispatchedState(person1, dispatched);
  List<Entry<?>> dispatchedEntries = dispatched.entries();
  Assert.assertTrue(dispatchedEntries.isEmpty());

  dispatched = dispatcher.getDispatched().get(1);
  validateDispatchedState(person2, dispatched);
  dispatchedEntries = dispatched.entries();
  Assert.assertTrue(dispatchedEntries.isEmpty());

  dispatched = dispatcher.getDispatched().get(2);
  validateDispatchedState(person3, dispatched);
  dispatchedEntries = dispatched.entries();
  Assert.assertTrue(dispatchedEntries.isEmpty());
}
 
Example #9
Source File: InMemoryStateStoreTest.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void testThatStateStoreDispatches() {
  interest.afterCompleting(3);
  final AccessSafely accessDispatcher = dispatcher.afterCompleting(3);

  final Entity1 entity1 = new Entity1("123", 1);
  store.write(entity1.id, entity1, 1, interest);
  final Entity1 entity2 = new Entity1("234", 2);
  store.write(entity2.id, entity2, 1, interest);
  final Entity1 entity3 = new Entity1("345", 3);
  store.write(entity3.id, entity3, 1, interest);

  assertEquals(3, (int) accessDispatcher.readFrom("dispatchedStateCount"));
  final State<?> state123 = accessDispatcher.readFrom("dispatchedState", dispatchId("123"));
  assertEquals("123", state123.id);
  final State<?> state234 = accessDispatcher.readFrom("dispatchedState", dispatchId("234"));
  assertEquals("234", state234.id);
  final State<?> state345 = accessDispatcher.readFrom("dispatchedState", dispatchId("345"));
  assertEquals("345", state345.id);

  interest.afterCompleting(4);
  final AccessSafely accessDispatcher1 = dispatcher.afterCompleting(4);

  accessDispatcher1.writeUsing("processDispatch", false);
  final Entity1 entity4 = new Entity1("456", 4);
  store.write(entity4.id, entity4, 1, interest);
  final Entity1 entity5 = new Entity1("567", 5);
  store.write(entity5.id, entity5, 1, interest);

  accessDispatcher1.writeUsing("processDispatch", true);
  dispatcher.dispatchUnconfirmed();
  accessDispatcher1.readFrom("dispatchedStateCount");

  assertEquals(5, (int) accessDispatcher1.readFrom("dispatchedStateCount"));

  final State<?> state456 = accessDispatcher1.readFrom("dispatchedState", dispatchId("456"));
  assertEquals("456", state456.id);
  final State<?> state567 = accessDispatcher1.readFrom("dispatchedState", dispatchId("567"));
  assertEquals("567", state567.id);
}
 
Example #10
Source File: DispatcherControlActor.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
public DispatcherControlActor(
        final List<Dispatcher<Dispatchable<? extends Entry<?>, ? extends State<?>>>> dispatchers,
        final DispatcherControlDelegate<? extends Entry<?>, ? extends State<?>> delegate,
        final long checkConfirmationExpirationInterval,
        final long confirmationExpiration) {
  this.dispatchers = dispatchers;
  this.delegate = delegate;
  this.confirmationExpiration = confirmationExpiration;
  this.cancellable = scheduler().schedule(this, null, DEFAULT_REDISPATCH_DELAY, checkConfirmationExpirationInterval);
  this.dispatchers.forEach(d -> d.controlWith(this));
}
 
Example #11
Source File: DispatcherControl.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
public DispatcherControlInstantiator(
        final Dispatcher<Dispatchable<? extends Entry<?>, ? extends State<?>>> dispatcher,
        final DispatcherControlDelegate<? extends Entry<?>, ? extends State<?>> delegate,
        final long checkConfirmationExpirationInterval,
        final long confirmationExpiration) {
  this(Arrays.asList(dispatcher), delegate, checkConfirmationExpirationInterval, confirmationExpiration);
}
 
Example #12
Source File: DispatcherControl.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
public DispatcherControlInstantiator(
        final List<Dispatcher<Dispatchable<? extends Entry<?>, ? extends State<?>>>> dispatchers,
        final DispatcherControlDelegate<? extends Entry<?>, ? extends State<?>> delegate,
        final long checkConfirmationExpirationInterval,
        final long confirmationExpiration) {
  this.dispatchers = dispatchers;
  this.delegate = delegate;
  this.checkConfirmationExpirationInterval = checkConfirmationExpirationInterval;
  this.confirmationExpiration = confirmationExpiration;
}
 
Example #13
Source File: InMemoryObjectStoreActorTest.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void testThatObjectPersistsQueries() {
  dispatcher.afterCompleting(1);
  final AccessSafely persistAccess = persistInterest.afterCompleting(1);
  final Person person = new Person("Tom Jones", 85);
  final Test1Source source = new Test1Source();
  objectStore.persist(StateSources.of(person, source), persistInterest);
  final int persistSize = persistAccess.readFrom("size");
  assertEquals(1, persistSize);
  assertEquals(person, persistAccess.readFrom("object", 0));

  final QueryExpression query = MapQueryExpression
          .using(Person.class, "find", MapQueryExpression.map("id", "" + person.persistenceId()));

  final AccessSafely queryAccess = queryResultInterest.afterCompleting(1);
  objectStore.queryObject(query, queryResultInterest, null);
  final int querySize = queryAccess.readFrom("size");
  assertEquals(1, querySize);
  assertEquals(person, queryAccess.readFrom("object", 0));

  assertEquals(1, dispatcher.dispatchedCount());
  final Dispatchable<Entry<?>, State<?>> dispatched = dispatcher.getDispatched().get(0);
  validateDispatchedState(person, dispatched);

  final List<Entry<?>> dispatchedEntries = dispatched.entries();
  Assert.assertEquals(1, dispatchedEntries.size());
  final Entry<?> entry = dispatchedEntries.get(0);
  Assert.assertNotNull(entry.id());
  Assert.assertEquals(source.getClass().getName(), entry.typeName());
  Assert.assertEquals(Metadata.nullMetadata(), entry.metadata());
}
 
Example #14
Source File: ExchangeDispatcher.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void dispatch(Dispatchable<Entry<String>, State<String>> dispatchable) {
  logger.debug("Going to dispatch id {}", dispatchable.id());
  dispatchable.entries()
              .forEach(entry -> {
                try {
                  this.exchange.send(JsonSerialization.deserialized(entry.entryData(), entry.typed()));
                } catch (Exception e) {
                  logger.error("Entry {} of dispatch id {} will not be sent", dispatchable.id(), entry.id(), e);
                }
              });
  this.control.confirmDispatched(dispatchable.id(), this);
}
 
Example #15
Source File: StateStoreProjectionActor.java    From vlingo-lattice with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Construct my final state with the {@code StateStore}, which must
 * be provided by my concrete extenders, as well as with a
 * {@code stateAdapter} and a {@code entryAdapter}.
 * @param stateStore the StateStore from which previous state is read and merged current state is written
 * @param stateAdapter the {@code StateAdapter<Object, State<?>>} used by my extenders to adapt persistent state
 * @param entryAdapter the {@code EntryAdapter<Source<?>, Entry<?>>} used by my extenders to adapt persistent entries
 */
public StateStoreProjectionActor(
        final StateStore stateStore,
        final StateAdapter<Object, State<?>> stateAdapter,
        final EntryAdapter<Source<?>, Entry<?>> entryAdapter) {

  this.stateStore = stateStore;
  this.stateAdapter = stateAdapter;
  this.entryAdapter = entryAdapter;
  this.readInterest = selfAs(ReadResultInterest.class);
  this.writeInterest = selfAs(WriteResultInterest.class);

  this.adaptedSources = new ArrayList<>(2);
}
 
Example #16
Source File: InMemoryObjectStoreDelegate.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public QueryMultiResults queryAll(final QueryExpression expression) {
  // NOTE: No query constraints accepted; selects all stored objects

  final Set<Object> all = new HashSet<>();
  final Map<Long, State<?>> store = stores.computeIfAbsent(expression.type, (type) -> new HashMap<>());
  for (final State<?> entry : store.values()) {
    final Object stateObject = stateAdapterProvider.fromRaw(entry);
    all.add(stateObject);
  }

  return new QueryMultiResults(all);
}
 
Example #17
Source File: ExchangeDispatcher.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void dispatch(Dispatchable<Entry<String>, State<String>> dispatchable) {
    logger.debug("Going to dispatch id {}", dispatchable.id());

    for (Entry<String> entry : dispatchable.entries()) {
        try {
            this.exchange.send(JsonSerialization.deserialized(entry.entryData(), entry.typed()));
        } catch (Exception e) {
            logger.error("Entry {} of dispatch id {} will not be sent", dispatchable.id(), entry.id(), e);
        }
    }
    this.control.confirmDispatched(dispatchable.id(), this);
}
 
Example #18
Source File: InMemoryObjectStoreDelegate.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T extends StateObject> Collection<State<?>> persistAll(final Collection<T> stateObjects, final long updateId, final Metadata metadata) {
  final List<State<?>> states = new ArrayList<>(stateObjects.size());
  for (final T stateObject : stateObjects) {
    final State<?> raw = persist(stateObject, metadata);
    states.add(raw);
  }

  return states;
}
 
Example #19
Source File: InMemoryStreamReader.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
public InMemoryStreamReader(
        final List<BaseEntry<T>> journalView,
        final Map<String, Map<Integer,Integer>> streamIndexesView,
        final Map<String, State<T>> snapshotsView,
        final String name) {

  this.journalView = journalView;
  this.streamIndexesView = streamIndexesView;
  this.snapshotsView = snapshotsView;
  this.name = name;
}
 
Example #20
Source File: StatefulEntityTest.java    From vlingo-lattice with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public State<String> toRawState(final String id, final Entity1State state, final int stateVersion, final Metadata metadata) {
  final String serialization = JsonSerialization.serialized(state);
  return new TextState(id, Entity1State.class, typeVersion(), serialization, stateVersion);
}
 
Example #21
Source File: MockJournalDispatcher.java    From vlingo-examples with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public void dispatch(final Dispatchable<Entry<String>, State<String>> dispatchable) {
  access.writeUsing("entries", Tuple2.from(dispatchable.entries(), snapshots(dispatchable.entries().size(), dispatchable.typedState())));
}
 
Example #22
Source File: UserIdStateAdapter.java    From vlingo-examples with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public <ST> ST fromRawState(State.TextState textState, Class<ST> aClass) {
    return JsonSerialization.deserialized(textState.data, aClass);
}
 
Example #23
Source File: StatefulEntityTest.java    From vlingo-lattice with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public State<String> toRawState(final Entity1State state, final int stateVersion) {
  return toRawState(state.id, state, stateVersion, Metadata.nullMetadata());
}
 
Example #24
Source File: CartStateAdapter.java    From vlingo-examples with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public <ST> ST fromRawState(State.TextState textState, Class<ST> aClass) {
    return JsonSerialization.deserialized(textState.data, aClass);
}
 
Example #25
Source File: UserIdStateAdapter.java    From vlingo-examples with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public State.TextState toRawState(String id, UserId state, int stateVersion, Metadata metadata) {
    final String serialization = JsonSerialization.serialized(state);
    return new State.TextState(id, CartUserSummaryData.class, typeVersion(), serialization, stateVersion, metadata);
}
 
Example #26
Source File: Sourced.java    From vlingo-lattice with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Restores the initial state of the receiver by means of the {@code snapshot}.
 * @param snapshot the {@code Optional<SNAPSHOT>} holding the {@code Sourced<T,ST>} initial state
 */
private void restoreSnapshot(final State<?> snapshot) {
  if (snapshot != null && !snapshot.isNull()) {
    restoreSnapshot(journalInfo.stateAdapterProvider.fromRaw(snapshot), currentVersion);
  }
}
 
Example #27
Source File: CartStateAdapter.java    From vlingo-examples with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public CartUserSummaryData fromRawState(State.TextState textState) {
    return JsonSerialization.deserialized(textState.data, textState.typed());
}
 
Example #28
Source File: StatefulEntityTest.java    From vlingo-lattice with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public Entity1State fromRawState(final State<String> raw) {
  return JsonSerialization.deserialized(raw.data, Entity1State.class);
}
 
Example #29
Source File: CartStateAdapter.java    From vlingo-examples with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public State.TextState toRawState(String id, CartUserSummaryData state, int stateVersion, Metadata metadata) {
    final String serialization = JsonSerialization.serialized(state);
    return new State.TextState(id, CartUserSummaryData.class, typeVersion(), serialization, stateVersion, metadata);
}
 
Example #30
Source File: TextProjectable.java    From vlingo-lattice with Mozilla Public License 2.0 4 votes vote down vote up
public TextProjectable(final State<String> state, final Collection<Entry<?>> entries, final String projectionId) {
  super(state, entries, projectionId);
}