io.vlingo.symbio.store.dispatch.Dispatchable Java Examples

The following examples show how to use io.vlingo.symbio.store.dispatch.Dispatchable. 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: 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 #2
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 #3
Source File: StateProjectionDispatcherTest.java    From vlingo-lattice with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testThatDescribedProjectionsRegister() {
  final ProjectToDescription description = new ProjectToDescription(DescribedProjection.class, "op1", "op2");

  final Dispatcher dispatcher =
          world.actorFor(Dispatcher.class, TextProjectionDispatcherActor.class, Collections.singletonList(description));

  final Outcome outcome = new Outcome(2);
  final AccessSafely accessOutcome = outcome.afterCompleting(2);
  dispatcher.controlWith(outcome);

  final TextState state = new TextState("123", Object.class, 1, "blah1", 1, Metadata.with("", "op1"));
  dispatcher.dispatch(new Dispatchable<>("123", LocalDateTime.now(), state, Collections.emptyList()));

  final TextState state2 = new TextState("1235", Object.class, 1, "blah2", 1, Metadata.with("", "op2"));
  dispatcher.dispatch(new Dispatchable<>("1235", LocalDateTime.now(), state2, Collections.emptyList()));

  assertEquals(2, (int) accessOutcome.readFrom("count"));
}
 
Example #4
Source File: QueryModelStoreProvider.java    From vlingo-examples with Mozilla Public License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public static QueryModelStoreProvider using(final Stage stage, final StatefulTypeRegistry registry) {
  if (instance != null) return instance;

  final StateAdapterProvider stateAdapterProvider = new StateAdapterProvider(stage.world());
  stateAdapterProvider.registerAdapter(UserData.class, new UserDataStateAdapter());
  stateAdapterProvider.registerAdapter(ProfileData.class, new ProfileDataStateAdapter());
  new EntryAdapterProvider(stage.world()); // future

  final Dispatcher noop = new Dispatcher() {
    public void controlWith(final DispatcherControl control) { }
    public void dispatch(Dispatchable d) { }
  };

  final StateStore store = stage.actorFor(StateStore.class, InMemoryStateStoreActor.class, Arrays.asList(noop));

  final Queries queries = stage.actorFor(Queries.class, QueriesActor.class, store);

  instance = new QueryModelStoreProvider(registry, store, queries);

  return instance;
}
 
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 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 #9
Source File: MockStateStoreDispatcher.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void dispatch(Dispatchable dispatchable) {
  dispatchAttemptCount++;
  if (processDispatch.get()) {
    final String dispatchId = dispatchable.id();
    access.writeUsing("dispatched", dispatchId, new Dispatch(dispatchable.typedState(), dispatchable.entries()));
    control.confirmDispatched(dispatchId, confirmDispatchedResultInterest);
  }
}
 
Example #10
Source File: InMemoryEventJournalActorTest.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void testThatJournalAppendsOneEventWithSnapshot() {
  dispatcher.afterCompleting(1);
  interest.afterCompleting(1);

  final Test1Source source = new Test1Source();
  final String streamName = "123";
  final int streamVersion = 1;

  journal.appendWith(streamName, streamVersion, new Test1Source(), new SnapshotState(), interest, object);

  final List<JournalData<String, SnapshotState>> entries = interest.getEntries();
  final JournalData<String, SnapshotState> journalData = entries.get(0);
  assertNotNull(journalData);
  Assert.assertEquals(streamName, journalData.streamName);
  Assert.assertEquals(streamVersion, journalData.streamVersion);
  Assert.assertEquals(Result.Success, journalData.result);
  Assert.assertTrue(journalData.snapshot.isPresent());

  final List<Source<String>> sourceList = journalData.sources;
  Assert.assertEquals(1, sourceList.size());
  Assert.assertEquals(source, sourceList.get(0));

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

  Assert.assertNotNull(dispatched.createdOn());
  Assert.assertTrue(dispatched.state().isPresent());
  Assert.assertNotNull(dispatched.id());
  final Collection<Entry<?>> dispatchedEntries = dispatched.entries();
  Assert.assertEquals(1, dispatchedEntries.size());
}
 
Example #11
Source File: InMemoryEventJournalActorTest.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void testThatJournalAppendsOneEvent() {
  dispatcher.afterCompleting(1);
  interest.afterCompleting(1);

  final Test1Source source = new Test1Source();
  final String streamName = "123";
  final int streamVersion = 1;
  journal.append(streamName, streamVersion, source, interest, object);

  assertEquals(1, interest.getReceivedAppendsSize());

  final List<JournalData<String, SnapshotState>> entries = interest.getEntries();
  final JournalData<String, SnapshotState> journalData = entries.get(0);
  assertNotNull(journalData);
  Assert.assertEquals(streamName, journalData.streamName);
  Assert.assertEquals(streamVersion, journalData.streamVersion);
  Assert.assertEquals(Result.Success, journalData.result);
  Assert.assertFalse(journalData.snapshot.isPresent());

  final List<Source<String>> sourceList = journalData.sources;
  Assert.assertEquals(1, sourceList.size());
  Assert.assertEquals(source, sourceList.get(0));

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

  Assert.assertNotNull(dispatched.createdOn());
  Assert.assertFalse(dispatched.state().isPresent());
  Assert.assertNotNull(dispatched.id());
  final Collection<Entry<?>> dispatchedEntries = dispatched.entries();
  Assert.assertEquals(1, dispatchedEntries.size());
}
 
Example #12
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 #13
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 #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());

    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 #15
Source File: Bootstrap.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
@NotNull
@SuppressWarnings("rawtypes")
private Dispatcher createNoOpDispatcher() {
    return new Dispatcher() {
            public void controlWith(final DispatcherControl control) { }
            public void dispatch(Dispatchable d) { }
        };
}
 
Example #16
Source File: InMemoryStateStoreActor.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public InMemoryStateStoreActor(
        final List<Dispatcher<Dispatchable<Entry<?>, RS>>> dispatchers,
        final long checkConfirmationExpirationInterval,
        final long confirmationExpiration) {

  if (dispatchers == null) {
    throw new IllegalArgumentException("Dispatcher must not be null.");
  }
  this.dispatchers = dispatchers;
  this.entryAdapterProvider = EntryAdapterProvider.instance(stage().world());
  this.stateAdapterProvider = StateAdapterProvider.instance(stage().world());
  this.entries = new CopyOnWriteArrayList<>();
  this.entryReaders = new HashMap<>();
  this.store = new HashMap<>();
  this.dispatchables = new CopyOnWriteArrayList<>();
  this.readAllResultCollector = new ReadAllResultCollector();

  final InMemoryDispatcherControlDelegate<Entry<?>, RS> dispatcherControlDelegate = new InMemoryDispatcherControlDelegate<>(dispatchables);

  this.dispatcherControl = stage().actorFor(
    DispatcherControl.class,
    Definition.has(
      DispatcherControlActor.class,
      new DispatcherControlInstantiator(
        dispatchers,
        dispatcherControlDelegate,
        checkConfirmationExpirationInterval,
        confirmationExpiration)));
}
 
Example #17
Source File: InMemoryJournal.java    From vlingo-symbio with Mozilla Public License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public InMemoryJournal(
        final List<Dispatcher<Dispatchable<Entry<T>,RS>>> dispatchers,
        final World world,
        final long checkConfirmationExpirationInterval,
        final long confirmationExpiration) {

  this.entryAdapterProvider = EntryAdapterProvider.instance(world);
  this.stateAdapterProvider = StateAdapterProvider.instance(world);
  this.journal = new ArrayList<>();
  this.journalReaders = new HashMap<>(1);
  this.streamReaders = new HashMap<>(1);
  this.streamIndexes = new HashMap<>();
  this.snapshots = new HashMap<>();

  this.dispatchers = dispatchers;
  this.dispatchables = new CopyOnWriteArrayList<>();
  final InMemoryDispatcherControlDelegate<Entry<T>, RS> dispatcherControlDelegate = new InMemoryDispatcherControlDelegate<>(dispatchables);

  this.dispatcherControl = world.stage().actorFor(
          DispatcherControl.class,
          Definition.has(
                  DispatcherControlActor.class,
                  new DispatcherControlInstantiator(
                          dispatchers,
                          dispatcherControlDelegate,
                          checkConfirmationExpirationInterval,
                          confirmationExpiration)));
}
 
Example #18
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 #19
Source File: MockTextDispatcher.java    From vlingo-lattice with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public void dispatch(final Dispatchable<Entry<?>,State<?>> dispatchable) {
  if (processDispatch.get()) {
    access.writeUsing("dispatched", dispatchable.id(), new Dispatch<>(dispatchable.typedState(), dispatchable.entries()));
  }
}
 
Example #20
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 #21
Source File: MockJournalDispatcher.java    From vlingo-lattice with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public void dispatch(final Dispatchable<Entry<String>, State<?>> dispatchable) {
  access.writeUsing("appendedAll", dispatchable.entries());
}
 
Example #22
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<?>> dispatchable) {
    this.entries.addAll(dispatchable.entries());
}
 
Example #23
Source File: MockDispatcher.java    From vlingo-examples with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public void dispatch(final Dispatchable<Entry<?>, State<?>> dispatchable) {
}
 
Example #24
Source File: MockDispatcher.java    From vlingo-examples with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public void dispatch(final Dispatchable<Entry<?>, State<?>> dispatchable) {
}
 
Example #25
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 #26
Source File: MockDispatcher.java    From vlingo-examples with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public void dispatch(final Dispatchable<Entry<?>, State<?>> dispatchable) {
}
 
Example #27
Source File: InMemoryDispatcherControlDelegate.java    From vlingo-symbio with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public Collection<Dispatchable<E, RS>> allUnconfirmedDispatchableStates() {
  return dispatchables;
}
 
Example #28
Source File: InMemoryDispatcherControlDelegate.java    From vlingo-symbio with Mozilla Public License 2.0 4 votes vote down vote up
public InMemoryDispatcherControlDelegate(final List<Dispatchable<E, RS>> dispatchables) {
  this.dispatchables = dispatchables;
}
 
Example #29
Source File: InMemoryObjectStoreActor.java    From vlingo-symbio with Mozilla Public License 2.0 4 votes vote down vote up
private static Dispatchable<BaseEntry<?>, State<?>> buildDispatchable(final State<?> state, final List<BaseEntry<?>> entries) {
  final String id = getDispatchId(state, entries);
  return new Dispatchable<>(id, LocalDateTime.now(), state, entries);
}
 
Example #30
Source File: InMemoryObjectStoreActor.java    From vlingo-symbio with Mozilla Public License 2.0 4 votes vote down vote up
private void dispatch(final Dispatchable<BaseEntry<?>, State<?>> dispatchable){
  this.dispatchers.forEach(d -> d.dispatch(dispatchable));
}