Interface FluxCapacitor

All Superinterfaces:
AutoCloseable
All Known Implementing Classes:
DefaultFluxCapacitor

public interface FluxCapacitor extends AutoCloseable
High-level client for Flux Capacitor. If you are using anything other than this to interact with the service at runtime you're probably doing it wrong.

To start handling messages build an instance of this API and invoke registerHandlers(java.lang.Object...).

Once you are handling messages you can simply use the static methods provided (e.g. to publish messages etc). In those cases it is not necessary to inject an instance of this API. This minimizes the need for dependencies in your functional classes and maximally cashes in on location transparency.

To build an instance of this client check out DefaultFluxCapacitor.

  • Field Details

    • applicationInstance

      static final AtomicReference<FluxCapacitor> applicationInstance
      Flux Capacitor instance set by the current application. Used as a fallback when no threadlocal instance was set. This is added as a convenience for applications that never have more than one than FluxCapacitor instance which will be the case for nearly all applications. On application startup simply fill this application instance.
    • instance

      static final ThreadLocal<FluxCapacitor> instance
      Flux Capacitor instance bound to the current thread. Normally there's only one FluxCapacitor client per application. Before messages are passed to message handlers the FluxCapacitor client binds itself to this field. By doing so message handlers can interact with Flux Capacitor without injecting any dependencies.
  • Method Details

    • get

      static FluxCapacitor get()
      Returns the Flux Capacitor instance bound to the current thread or else set by the current application. Throws an exception if no instance was registered.
    • getOptionally

      static Optional<FluxCapacitor> getOptionally()
      Returns the FluxCapacitor client bound to the current thread or else set by the current application as Optional. Returns an empty Optional if no instance was registered.
    • currentClock

      static Clock currentClock()
      Gets the clock of the current FluxCapacitor instance (obtained via getOptionally()). If there is no current instance the system's UTC clock is returned.
    • currentTime

      static Instant currentTime()
      Gets the time according to the current FluxCapacitor clock (obtained via currentClock()). If there is no current FluxCapacitor instance the system's UTC time is returned.
    • generateId

      static String generateId()
      Gets the IdentityProvider of the current FluxCapacitor to generate a unique identifier. If there is no current FluxCapacitor instance a new UUID is generated.
    • currentIdentityProvider

      static IdentityProvider currentIdentityProvider()
      Fetches the IdentityProvider of the current FluxCapacitor. If there is no current FluxCapacitor instance a new UUID factory is generated.
    • currentCorrelationData

      static Map<String,String> currentCorrelationData()
      Gets the current correlation data, which by default depends on the current Client, Tracker and DeserializingMessage
    • publishEvent

      static void publishEvent(Object event)
      Publishes the given application event. The event may be an instance of a Message in which case it will be published as is. Otherwise the event is published using the passed value as payload without additional metadata.

      Note that the published event will not be available for event sourcing as it is does not belong to any aggregate.

      See Also:
    • publishEvent

      static void publishEvent(Object payload, Metadata metadata)
      Publishes an event with given payload and metadata.
      See Also:
    • sendAndForgetCommand

      static void sendAndForgetCommand(Object command)
      Sends the given command and doesn't wait for a result. The command may be an instance of a Message in which case it will be sent as is. Otherwise the command is published using the passed value as payload without additional metadata.
      See Also:
    • sendAndForgetCommands

      static void sendAndForgetCommands(Object... commands)
      Sends the given commands and doesn't wait for results. Commands may be an instance of a Message in which case it will be sent as is. Otherwise, the commands are published using the passed value as payload without additional metadata.
      See Also:
    • sendAndForgetCommand

      static void sendAndForgetCommand(Object payload, Metadata metadata)
      Sends a command with given payload and metadata and don't wait for a result.
      See Also:
    • sendAndForgetCommand

      static void sendAndForgetCommand(Object payload, Metadata metadata, Guarantee guarantee)
      Sends a command with given payload and metadata and don't wait for a result. With a guarantee the method will wait for the command itself to be sent or stored.
      See Also:
    • sendCommand

      static <R> CompletableFuture<R> sendCommand(Object command)
      Sends the given command and returns a future that will be completed with the command's result. The command may be an instance of a Message in which case it will be sent as is. Otherwise the command is published using the passed value as payload without additional metadata.
    • sendCommand

      static <R> CompletableFuture<R> sendCommand(Request<R> command)
      Sends the given command and returns a future that will be completed with the command's result. The command may be an instance of a Message in which case it will be sent as is. Otherwise the command is published using the passed value as payload without additional metadata.

      The return type is determined by the given command.

    • sendCommands

      static <R> List<CompletableFuture<R>> sendCommands(Object... commands)
      Sends the given commands and returns a list of futures that will be completed with the commands' results. The commands may be instances of a Message in which case they will be sent as is. Otherwise, the commands are published using the passed values as payload without additional metadata.
    • sendCommand

      static <R> CompletableFuture<R> sendCommand(Object payload, Metadata metadata)
      Sends a command with given payload and metadata and returns a future that will be completed with the command's result.
    • sendCommand

      static <R> CompletableFuture<R> sendCommand(Request<R> payload, Metadata metadata)
      Sends a command with given payload and metadata and returns a future that will be completed with the command's result.

      The return type is determined by the given command.

    • sendCommandAndWait

      static <R> R sendCommandAndWait(Object command)
      Sends the given command and returns the command's result. The command may be an instance of a Message in which case it will be sent as is. Otherwise, the command is published using the passed value as payload without additional metadata.
    • sendCommandAndWait

      static <R> R sendCommandAndWait(Request<R> command)
      Sends the given command and returns the command's result. The command may be an instance of a Message in which case it will be sent as is. Otherwise, the command is published using the passed value as payload without additional metadata.

      The return type is determined by the given command.

    • sendCommandAndWait

      static <R> R sendCommandAndWait(Object payload, Metadata metadata)
      Sends a command with given payload and metadata and returns a future that will be completed with the command's result.
    • sendCommandAndWait

      static <R> R sendCommandAndWait(Request<R> payload, Metadata metadata)
      Sends a command with given payload and metadata and returns a future that will be completed with the command's result.

      The return type is determined by the given command.

    • query

      static <R> CompletableFuture<R> query(Object query)
      Sends the given query and returns a future that will be completed with the query's result. The query may be an instance of a Message in which case it will be sent as is. Otherwise, the query is published using the passed value as payload without additional metadata.
    • query

      static <R> CompletableFuture<R> query(Request<R> query)
      Sends the given query and returns a future that will be completed with the query's result. The query may be an instance of a Message in which case it will be sent as is. Otherwise, the query is published using the passed value as payload without additional metadata.

      The return type is determined by the given query.

    • query

      static <R> CompletableFuture<R> query(Object payload, Metadata metadata)
      Sends a query with given payload and metadata and returns a future that will be completed with the query's result.
    • query

      static <R> CompletableFuture<R> query(Request<R> payload, Metadata metadata)
      Sends a query with given payload and metadata and returns a future that will be completed with the query's result.

      The return type is determined by the given query.

    • queryAndWait

      static <R> R queryAndWait(Object query)
      Sends the given query and returns the query's result. The query may be an instance of a Message in which case it will be sent as is. Otherwise, the query is published using the passed value as payload without additional metadata.
    • queryAndWait

      static <R> R queryAndWait(Request<R> query)
      Sends the given query and returns the query's result. The query may be an instance of a Message in which case it will be sent as is. Otherwise, the query is published using the passed value as payload without additional metadata.

      The return type is determined by the given query.

    • queryAndWait

      static <R> R queryAndWait(Object payload, Metadata metadata)
      Sends a query with given payload and metadata and returns the query's result.
    • queryAndWait

      static <R> R queryAndWait(Request<R> payload, Metadata metadata)
      Sends a query with given payload and metadata and returns the query's result.

      The return type is determined by the given query.

    • schedule

      static String schedule(Object schedule, Instant deadline)
      Schedules a message for the given timestamp, returning the schedule's id. The schedule parameter may be an instance of a Message in which case it will be scheduled as is. Otherwise, the schedule is published using the passed value as payload without additional metadata.
    • schedule

      static void schedule(Object schedule, String scheduleId, Instant deadline)
      Schedules a message with given scheduleId for the given timestamp. The schedule parameter may be an instance of a Message in which case it will be scheduled as is. Otherwise, the schedule is published using the passed value as payload without additional metadata.
    • schedule

      static String schedule(Object schedule, Duration delay)
      Schedules a message after the given delay, returning the schedule's id. The schedule parameter may be an instance of a Message in which case it will be scheduled as is. Otherwise, the schedule is published using the passed value as payload without additional metadata.
    • schedule

      static void schedule(Object schedule, String scheduleId, Duration delay)
      Schedules a message with given scheduleId after given delay. The schedule parameter may be an instance of a Message in which case it will be scheduled as is. Otherwise, the schedule is published using the passed value as payload without additional metadata.
    • scheduleCommand

      static String scheduleCommand(Object command, Instant deadline)
      Schedules a command for the given timestamp, returning the command schedule's id. The command parameter may be an instance of a Message in which case it will be scheduled as is. Otherwise, the command is scheduled using the passed value as payload without additional metadata.
    • scheduleCommand

      static void scheduleCommand(Object command, String scheduleId, Instant deadline)
      Schedules a command with given scheduleId for the given timestamp. The command parameter may be an instance of a Message in which case it will be scheduled as is. Otherwise, the command is published using the passed value as payload without additional metadata.
    • scheduleCommand

      static String scheduleCommand(Object command, Duration delay)
      Schedules a command after given delay, returning the command schedule's id. The command parameter may be an instance of a Message in which case it will be scheduled as is. Otherwise, the command is scheduled using the passed value as payload without additional metadata.
    • scheduleCommand

      static void scheduleCommand(Object command, String scheduleId, Duration delay)
      Schedules a command with given scheduleId after given delay. The command parameter may be an instance of a Message in which case it will be scheduled as is. Otherwise, the command is published using the passed value as payload without additional metadata.
    • cancelSchedule

      static void cancelSchedule(String scheduleId)
      Cancels the schedule with given scheduleId.
    • publishMetrics

      static void publishMetrics(Object metrics)
      Publishes a metrics event. The parameter may be an instance of a Message in which case it will be sent as is. Otherwise the metrics event is published using the passed value as payload without additional metadata.

      Metrics events can be published in any form to log custom performance metrics about an application.

    • publishMetrics

      static void publishMetrics(Object payload, Metadata metadata)
      Publishes a metrics event with given payload and metadata. Metrics events can be published in any form to log custom performance metrics about an application.
    • loadAggregate

      static <T> Entity<T> loadAggregate(Id<T> aggregateId)
      Loads the aggregate root of type <T> with given aggregateId.

      If the aggregate is loaded while handling an event of the aggregate, the returned Aggregate will automatically be replayed back to the event currently being handled. Otherwise, the most recent state of the aggregate is loaded.

      See Also:
    • loadAggregate

      static <T> Entity<T> loadAggregate(Object aggregateId, Class<T> aggregateType)
      Loads the aggregate root of type <T> with given aggregateId.

      If the aggregate is loaded while handling an event of the aggregate, the returned Aggregate will automatically be replayed back to the event currently being handled. Otherwise, the most recent state of the aggregate is loaded.

      See Also:
    • loadAggregateFor

      static <T> Entity<T> loadAggregateFor(Object entityId, Class<?> defaultType)
      Loads the aggregate root of type <T> that currently contains the entity with given entityId. If no such aggregate exists an empty aggregate root is returned with given defaultType as its type.

      This method can also be used if the entity is the aggregate root (aggregateId is equal to entityId). If the entity is associated with more than one aggregate the behavior of this method is unpredictable, though the default behavior is that any one of the associated aggregates is returned.

      If the aggregate is loaded while handling an event of the aggregate, the returned Aggregate will automatically be replayed back to the event currently being handled. Otherwise, the most recent state of the aggregate is loaded.

      See Also:
    • loadAggregateFor

      static <T> Entity<T> loadAggregateFor(Object entityId)
      Loads the aggregate root that currently contains the entity with given entityId. If no such aggregate exists an empty aggregate root is returned of type Object. In that case be aware that applying events to create the aggregate may yield an undesired result; to prevent this use loadAggregateFor(Object, Class).

      This method can also be used if the entity is the aggregate root (aggregateId is equal to entityId). If the entity is associated with more than one aggregate the behavior of this method is unpredictable, though the default behavior is that any one of the associated aggregates is returned.

      If the aggregate is loaded while handling an event of the aggregate, the returned Aggregate will automatically be replayed back to the event currently being handled. Otherwise, the most recent state of the aggregate is loaded.

      See Also:
    • loadEntity

      static <T> Entity<T> loadEntity(Object entityId)
      Loads the entity with given id. If the entity is not associated with any aggregate yet, a new aggregate root is loaded with the entityId as aggregate identifier. In case multiple entities are associated with the given entityId the most recent entity is returned.
    • loadEntity

      static <T> Entity<T> loadEntity(Id<T> entityId)
      Loads the entity with given id. If the entity is not associated with any aggregate yet, a new aggregate root is loaded with the entityId as aggregate identifier. In case multiple entities are associated with the given entityId the most recent entity is returned.
    • loadEntityValue

      static <T> Optional<T> loadEntityValue(Object entityId)
      Loads the current entity value for given entity id. Entity may be the aggregate root or any ancestral entity. If no such entity exists an empty optional is returned.
    • loadEntityValue

      static <T> Optional<T> loadEntityValue(Id<T> entityId)
      Loads the current entity value for given entity id. Entity may be the aggregate root or any ancestral entity. If no such entity exists an empty optional is returned.
    • index

      static CompletableFuture<Void> index(Object object, Object collection)
      Index given object for search.

      If the object has a property annotated with EntityId, it will be used as the id of the document. Otherwise, a random id will be assigned to the document.

      This method returns once the object is stored.

      See Also:
    • index

      static CompletableFuture<Void> index(Object object, Object id, Object collection)
      Index given object for search. This method returns once the object is stored.
      See Also:
    • index

      static CompletableFuture<Void> index(Object object, Object id, Object collection, Instant timestamp)
      Index given object for search. This method returns once the object is stored.
      See Also:
    • index

      static CompletableFuture<Void> index(Object object, Object id, Object collection, Instant begin, Instant end)
      Index given object for search. This method returns once the object is stored.
      See Also:
    • index

      static <T> CompletableFuture<Void> index(Collection<? extends T> objects, Object collection, Function<? super T,String> idFunction, Function<? super T,Instant> timestampFunction, Function<? super T,Instant> endFunction)
      Index given objects for search. Use idFunction to provide the document's required id. Use timestampFunction and endFunction to provide the object's timestamp. If none are supplied the document will not be timestamped.

      This method returns once all objects are stored.

      See Also:
    • search

      static Search search(Object collection)
      Search the given collection for documents. Usually collection is the String name of the collection. However, it is also possible to call it with a Collection containing one or multiple collection names.

      If collection is of type Class it is expected that the class is annotated with Searchable. It will then use the collection configured there.

      For all other inputs, the collection name will be obtained by calling Object.toString() on the input.

      Example usage: FluxCapacitor.search("myCollection").query("foo !bar").fetch(100);

    • search

      static Search search(Object collection, Object... additionalCollections)
      Search the given collections for documents.

      If collection is of type Class it is expected that the class is annotated with * Searchable. It will then use the collection configured there. For all other inputs, the collection name will be obtained by calling Object.toString() on the input.

      Example usage: FluxCapacitor.search("myCollection", "myOtherCollection).query("foo !bar").fetch(100);

    • search

      static Search search(SearchQuery.Builder queryBuilder)
      Search documents using given reusable query builder.

      Example usage: FluxCapacitor.search(SearchQuery.builder().search("myCollection").query("foo !bar")).fetch(100);

    • registerHandlers

      default Registration registerHandlers(Object... handlers)
      Registers given handlers and initiates message tracking (i.e. listening for messages).

      The given handlers will be inspected for annotated handler methods (e.g. methods annotated with HandleCommand). Depending on this inspection message tracking will commence for any handled message types. To stop listening at any time invoke Registration.cancel() on the returned object.

      Note that an exception may be thrown if tracking for a given message type is already in progress.

      If any of the handlers is a local handler or contains local handler methods, i.e. if type or method is annotated with LocalHandler, the target object will (also) be registered as local handler. Local handlers will handle messages in the publishing thread. If a published message can be handled locally it will not be published to the Flux Capacitor service. Local handling of messages may come in handy in several situations: e.g. when the message is expressly meant to be handled only by the current application or if the message needs to be handled as quickly as possible. However, in most cases it will not be necessary to register local handlers.

      Note that it will generally not be necessary to invoke this method manually if you use Spring to configure your application.

      See Also:
    • registerHandlers

      default Registration registerHandlers(List<?> handlers)
      Registers given handlers and initiates message tracking.
      See Also:
    • withClock

      void withClock(Clock clock)
      Have Flux Capacitor use the given Clock when generating timestamps, e.g. when creating a Message.
    • aggregateRepository

      AggregateRepository aggregateRepository()
      Returns a client to assist with event sourcing.
    • eventStore

      EventStore eventStore()
      Returns the store for aggregate events.
    • snapshotStore

      SnapshotStore snapshotStore()
      Returns the store for aggregate snapshots.
    • scheduler

      Scheduler scheduler()
      Returns the message scheduling client.
    • commandGateway

      CommandGateway commandGateway()
      Returns the gateway for command messages.
    • queryGateway

      QueryGateway queryGateway()
      Returns the gateway for query messages.
    • eventGateway

      EventGateway eventGateway()
      Returns the message gateway for application events. Use aggregateRepository() to publish events belonging to an aggregate.
    • resultGateway

      ResultGateway resultGateway()
      Returns the gateway for result messages sent by handlers of commands and queries.
    • errorGateway

      ErrorGateway errorGateway()
      Returns the gateway for any error messages published while handling a command or query.
    • metricsGateway

      MetricsGateway metricsGateway()
      Returns the gateway for metrics events. Metrics events can be published in any form to log custom performance metrics about an application.
    • webRequestGateway

      WebRequestGateway webRequestGateway()
      Returns the gateway for sending web requests.
    • tracking

      Tracking tracking(MessageType messageType)
      Returns a client to assist with the tracking of a given message type.
    • keyValueStore

      KeyValueStore keyValueStore()
      Returns a client for the key value service offered by Flux Capacitor.
    • documentStore

      DocumentStore documentStore()
      Returns a client for the document search service offered by Flux Capacitor.
    • userProvider

      UserProvider userProvider()
      Returns the UserProvider used by Flux Capacitor to authenticate users. May be null if user authentication is disabled.
    • cache

      Cache cache()
      Returns the cache used by the client to cache aggregates etc.
    • correlationDataProvider

      CorrelationDataProvider correlationDataProvider()
      Returns the provider of correlation data for published messages.
    • serializer

      Serializer serializer()
      Returns the default serializer
    • clock

      Clock clock()
      Returns the clock used by Flux Capacitor to generate timestamps.
    • identityProvider

      IdentityProvider identityProvider()
      Returns the factory used by Flux Capacitor to generate identifiers.
    • propertySource

      PropertySource propertySource()
      Returns the PropertySource configured for this FluxCapacitor instance.
    • client

      Client client()
      Returns the low level client used by this FluxCapacitor instance to interface with the Flux Capacitor service. Of course the returned client may also be a stand-in for the actual service.
    • apply

      default <R> R apply(ThrowingFunction<FluxCapacitor,R> function)
      Applies the given function with this Flux Capacitor set as current threadlocal instance.
    • execute

      default void execute(ThrowingConsumer<FluxCapacitor> task)
      Executes the given task with this Flux Capacitor set as current threadlocal instance.
    • beforeShutdown

      Registration beforeShutdown(Runnable task)
      Register a task to run before this Flux Capacitor instance is closed.
    • close

      void close()
      Specified by:
      close in interface AutoCloseable