Git Product home page Git Product logo

simple-eventstore-kotlin's People

Contributors

gtrefs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

simple-eventstore-kotlin's Issues

Add better query supports: projection

Problem

Currently a query is a fold over all domain events in an eventstore which may result into some boiler plate code. For example, two queries for different events result into two folds which only differ in the actual type of the event.

val registeredUsers: (List<DomainEvent>) -> List<UserRegistered> = { it.fold(emptyList(),
         { s,d -> when(d){ is UserRegistered -> s + d else -> s }}
)} 
val loggedInUsers: (List<DomainEvent>) -> List<UserLoggedIn> = { it.fold(emptyList(),
        {s, d -> when(d){ is UserLoggedIn -> s + d else -> s}} 
)}

Another problem occurs when we want to compose queries. For example, if we want to get all users which are currently viewing a specific page, we need to first query for all logged in users and then filter those which are on the page. However, composing those queries is quite hard with fold.

A little projection algebra

Let's think about query again. Instead using the fold model we can see it as a function.

  • A projection is a function from a list of events to a structure.
typealias Projection<T> = (List<DomainEvent>) -> T
  • An empty projection does not project anything
val empty:Projection<List<DomainEvent>> = { it } // identity function

Deserialization

In #2 a little DSL was developed to describe the Serialization of events. However, the other way round is missing. When we have a SerializedEvent how to recover the actual event instance?

Currently, this is done by the DomainEventFactory. The serialization contract requires, that the companion object of an event is of type DomainEventFactory. During deserialization the the event class is loaded with the Classloader of the current Thread. This results into the instantiation of the companion object which is accessed through reflection:

Class.forName(type).kotlin.companionObjectInstance as DomainEventFactory

This is really intrusive and cumbersome as this has to be done for every domain event.

However, when the Serialization DSL is used we know at runtime how a SerializedEvent is constructed from a given event. This information seems also to be exploitable for back-conversion.

Idea

Modify the serialization DSL to create some kind of parse tree or a dependency graph which represents the information how an event of any type can be converted to a SerializedDomain Event.

val now = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli()
val colorChanged = ColorChangedEvent(now, Color(120,120,120,100), Color(120,120,120,50))
val serialization = serialize<ColorChangedEvent> {}
val serializedEvent = serialization(colorChanged)

val serializationTree = serialization.tree
val deserializationTree = serializationTree.toDeserialization

val deserialized = deserializationTree.toEvent(serializedEvent)

A serialization tree of ColorChangedEvent could look like this:

val serializationTree = Tree(ColorChangeEvent::class, "", 
            listOf(Leaf(Long::class, "timeStamp"), 
                     Tree(Color::class, "oldColor", 
                         listOf(Leaf(Byte::class, "red"), 
                                  Leaf(Byte::class, "green"), 
                                  Leaf(Byte::class, "blue"),
                                  Leaf(Byte::class, "alpha"))),
                     Tree(Color::class, "newColor", 
                         listOf(Leaf(Byte::class, "red"), 
                                  Leaf(Byte::class, "green"), 
                                  Leaf(Byte::class, "blue"),
                                  Leaf(Byte::class, "alpha"))))
interface Node<E>
data class Tree<E>(val type:KClass<E>, val name: String, val parameters: List<Node>) : Node {}
data class Leaf<E>(val type:KClass<E>, val name: String) : Node {} 

Toplogical order could be implemented with a depth-first search.

Serialization improvements

Types are good for compile time safety. However, for parsing type-safety is hard to achieve and not easily feasible without language specific type information.

Serialization

The current serialization process is two-fold.

  • First, the serialize method of a DomainEvent is called resulting in a SerializeableDomainEvent. A SerializeableDomainEvent represent a flattened DomainEvent which consists of a type, some meta information like time of creation and some payload. All parameters should be easy to serialize to a specific format. Thus, primitive data types are preferred.
  • Second, a Storage does the translation between a SerializableDomainEvent and the actual format.

Deserialization

For deserialization, it is required that the default companion object of a DomainEvent implements the DomainEventFactory interface which describes how to desiraliaze a SerializableDomainEvent into a DomainEvent of proper type. For convinience, SerializeableDomainEventprovides a deserialize which does the deserialization by creating and using a DomainEventFactory. The contract looks as follows:

val event = TestEvent("hello")
val contract = event.serialize().deserialize()

event.should.equal(contract)

1. Problem: Leaking abstraction

The loss of type information during the serialization process results in a leak of the Storage abstraction. For example, JsonFileStorage serializes LocalDateTimes into arrays of Ints which is not converted back into a LocalDateTime during deserialization. This results into a broken serialization contract.

2. Problem: Clumsy serilization API

The serilization API currently consists of SeriliazableDomainEvent which is rather unflexible. It would be nice to exploit the ability of Kotlin for writing DSLs.

Storage should be async

I/O is expensive. Currently, the storage does not provide an async API. This should be changed. Example:

Storage().readAll().thenApply { ... }

Serialization Dsl

See also #1

A possible DSL could look like this:

val now = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli()
val colorChanged = ColorChangedEvent(now, Color(120,120,120,100), Color(120,120,120,50))
serialize<ColorChangedEvent> {
            meta {
                +("time" to it.timeStamp)
            }
            payload {
                +("oldColor" to it.oldColor)
                +("newColor" to it.newColor)
            }
}(colorChanged)

serialize returns a function which is applied to a given instance. type is defaulted to the class name.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.