2. Build a read model with Cratis Chronicle
A read model in Cratis Chronicle turns recorded events into data your application can query. Here you’ll build a library catalog that shows which books are on loan, then a second view containing only borrowed books. Chronicle applies your event mappings to maintain both views.
Continue with the connected client and book ID from the previous chapter. Keep that ID: BookAdded, BookBorrowed, and BookReturned must belong to the same book for these views to describe its history.
In event-modeling, this is the view pattern: events feed a read model that a UI can query. This chapter builds that part of the library:
First, a couple more facts
Section titled “First, a couple more facts”Add two event types alongside BookAdded: BookBorrowed records the member’s name, and BookReturned records that the book came back. Include them in your client’s event-type discovery or registration, as you did for BookAdded:
using Cratis.Chronicle.Events;
[EventType]public record BookBorrowed(string MemberName);
[EventType]public record BookReturned;import io.cratis.chronicle.events.EventType
@EventTypedata class BookBorrowed(val memberName: String)
@EventTypeclass BookReturnedimport io.cratis.chronicle.events.EventType;
@EventTyperecord BookBorrowed(String memberName) {}
@EventTyperecord BookReturned() {}defmodule MyApp.Events.BookBorrowed do use Cratis.Chronicle.Events.EventType, id: "book-borrowed"
defstruct [:member_name]end
defmodule MyApp.Events.BookReturned do use Cratis.Chronicle.Events.EventType, id: "book-returned"
defstruct []endimport { eventType } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class BookBorrowed { @field(String) memberName: string; constructor(memberName: string) { this.memberName = memberName; }}
@eventType()class BookReturned {}BookReturned has no payload fields. The event’s context supplies the book’s event-source ID and when it happened, so the event does not need to repeat that information.
Declare what you want to read
Section titled “Declare what you want to read”Define a Book read model and map the three events onto its properties. The mapping is a projection: instructions for deriving state from events, including how to rebuild it from history.
Follow the catalog example below in C#, TypeScript, or Elixir. Use the Kotlin and Java borrowed-book view later in this chapter.
using Cratis.Chronicle.Projections.ModelBound;
[FromEvent<BookAdded>]public record Book( BookId Id,
string Title, string Isbn,
[SetValue<BookAdded>(false)] [SetValue<BookBorrowed>(true)] [SetValue<BookReturned>(false)] bool OnLoan,
[SetFrom<BookBorrowed>(nameof(BookBorrowed.MemberName))] string? BorrowedBy);import io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.projections.SetFromimport io.cratis.chronicle.projections.SetFromContextimport io.cratis.chronicle.projections.SetValueimport io.cratis.chronicle.readModels.ReadModel
@ReadModel@FromEvent(BookAdded::class)data class TutorialBookDetails( @SetFromContext(eventType = BookAdded::class, contextProperty = "eventSourceId") val id: String = "", val title: String = "", val isbn: String = "", @SetValue(eventType = BookAdded::class, value = "false") @SetValue(eventType = BookBorrowed::class, value = "true") @SetValue(eventType = BookReturned::class, value = "false") val onLoan: Boolean = false, @SetFrom(propertyPath = "memberName", eventType = BookBorrowed::class) @SetValue(eventType = BookReturned::class, clear = true) val borrowedBy: String? = null,)import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.projections.SetFrom;import io.cratis.chronicle.projections.SetFromContext;import io.cratis.chronicle.projections.SetValue;import io.cratis.chronicle.readModels.ReadModel;
@ReadModel@FromEvent(eventType = BookAdded.class)record TutorialBookDetails( @SetFromContext(eventType = BookAdded.class, contextProperty = "eventSourceId") String id, String title, String isbn, @SetValue(eventType = BookAdded.class, value = "false") @SetValue(eventType = BookBorrowed.class, value = "true") @SetValue(eventType = BookReturned.class, value = "false") boolean onLoan, @SetFrom(propertyPath = "memberName", eventType = BookBorrowed.class) @SetValue(eventType = BookReturned.class, clear = true) String borrowedBy) {}defmodule MyApp.ReadModels.Book do use Cratis.Chronicle.ReadModels.ReadModel
defstruct id: "", title: "", isbn: "", on_loan: false, borrowed_by: ""
from MyApp.Events.BookAdded, set: [id: :event_source_id, title: :title, isbn: :isbn, on_loan: false]
from MyApp.Events.BookBorrowed, set: [on_loan: true, borrowed_by: :member_name]
from MyApp.Events.BookReturned, set: [on_loan: false]endimport { fromEvent, Guid, setFrom, setValue } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@fromEvent(BookAdded)export class Book { id: Guid = Guid.empty;
@setFrom(BookAdded, 'title') title = '';
@setFrom(BookAdded, 'isbn') isbn = '';
@setValue(BookAdded, false) @setValue(BookBorrowed, true) @setValue(BookReturned, false) onLoan = false;
@setFrom(BookBorrowed, 'memberName') @field(String) borrowedBy: string | null = null;}In the C# example, BookAdded supplies Title and Isbn and sets OnLoan to false. BookBorrowed sets OnLoan to true and copies MemberName into BorrowedBy. BookReturned sets OnLoan back to false. Chronicle applies these mappings in event order, including when it rebuilds the view.
This mapping does not clear BorrowedBy on return. It retains the last borrower’s name, so use OnLoan to decide whether that name describes a current loan.
Query it
Section titled “Query it”Chronicle materializes this projection: an observer processes events and stores the resulting state in a sink, the projection’s storage destination. The C# default is MongoDB. With the default naming, Book instances live in the Books collection in the database named after your event store.
For the C# query below, use the MongoDB setup in Get started to supply an IMongoCollection<Book> for that collection. Books is the query class; each document it reads is a Book instance. Its OnLoan() method returns only books whose OnLoan flag is true:
using MongoDB.Driver;
public class Books(IMongoCollection<Book> collection){ public IEnumerable<Book> OnLoan() => collection.Find(b => b.OnLoan).ToList();}import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.readModels.ReadModel
@ReadModeldata class TutorialBook(val title: String = "", val onLoan: Boolean = false)
/** * Kotlin has no raw MongoCollection to query directly - reads go through the read model service * instead, which returns already-deserialized instances to filter in memory. */class Books(private val store: IEventStore) { suspend fun onLoan(): List<TutorialBook> = store.readModels.getInstances(TutorialBook::class).filter { it.onLoan }}import io.cratis.chronicle.IEventStore;import io.cratis.chronicle.java.ReadModelsJavaBridge;import io.cratis.chronicle.readModels.ReadModel;
import java.util.List;import java.util.stream.Collectors;
@ReadModelrecord TutorialBook(String title, boolean onLoan) {}
// Java has no raw MongoCollection to query directly - reads go through the read model service// instead, which returns already-deserialized instances to filter in memory.class Books { private final IEventStore store;
Books(IEventStore store) { this.store = store; }
List<TutorialBook> onLoan() { return ReadModelsJavaBridge.getInstances(store.getReadModels(), TutorialBook.class).stream() .filter(TutorialBook::onLoan) .collect(Collectors.toList()); }}defmodule MyApp.TutorialQueryBooksService do alias MyApp.ReadModels.Book
def on_loan do with {:ok, books} <- Cratis.Chronicle.all(Book) do {:ok, Enum.filter(books, & &1.on_loan)} end endendimport { IEventStore } from '@cratis/chronicle';
class Books { constructor(private readonly store: IEventStore) {}
async onLoan(): Promise<Book[]> { const books = await this.store.readModels.getInstances(Book); return books.filter(book => book.onLoan); }}Restart or reconnect your client with the new event types and projection included in its discovery or registration. Then exercise the mapping using the append pattern from the first chapter:
- Query the on-loan view after
BookAddedhas been projected. The book is not in this result becauseOnLoanisfalse. - Append
BookBorrowedwith a member’s name under the saved book ID. Once the projection catches up, query again: the book appears withOnLoanset totrueandBorrowedByset to that name. - Append
BookReturnedunder the same ID. After processing, the book disappears from the on-loan result. ItsBookinstance still exists in the catalog withOnLoanset tofalse.
A view that removes itself
Section titled “A view that removes itself”The catalog retains every book, while its query filters for current loans. You can also make membership in a view represent the loan itself: create a BorrowedBook when a book is borrowed and remove it when the book comes back. Then querying all instances answers “what’s out on loan?” without a flag filter:
using Cratis.Chronicle.Projections.ModelBound;
[FromEvent<BookBorrowed>][RemovedWith<BookReturned>]public record BorrowedBook( BookId Id,
string MemberName);import io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.projections.RemovedWithimport io.cratis.chronicle.readModels.ReadModel
@ReadModel@FromEvent(BookBorrowed::class)@RemovedWith(BookReturned::class)data class BorrowedBook( val id: String = "", val memberName: String = "")import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.projections.RemovedWith;import io.cratis.chronicle.readModels.ReadModel;
@ReadModel@FromEvent(eventType = BookBorrowed.class)@RemovedWith(eventType = BookReturned.class)class BorrowedBook { private String id = ""; private String memberName = "";
public BorrowedBook() {}
public String getId() { return id; } public void setId(String id) { this.id = id; }
public String getMemberName() { return memberName; } public void setMemberName(String memberName) { this.memberName = memberName; }}defmodule MyApp.ReadModels.BorrowedBook do use Cratis.Chronicle.ReadModels.ReadModel
defstruct id: "", member_name: ""
from MyApp.Events.BookBorrowed, set: [id: :event_source_id, member_name: :member_name]
removed_with MyApp.Events.BookReturned, []endimport { fromEvent, Guid, removedWith, setFrom } from '@cratis/chronicle';
@fromEvent(BookBorrowed)@removedWith(BookReturned)export class BorrowedBook { id: Guid = Guid.empty;
@setFrom(BookBorrowed, 'memberName') memberName = '';}This example includes Kotlin and Java implementations using @FromEvent and @RemovedWith. In C#, [FromEvent<BookBorrowed>] creates the instance, mapping MemberName by convention and using the book’s event-source ID as its key. [RemovedWith<BookReturned>] removes that instance when a return event arrives for the same book.
Query all instances of this view:
using MongoDB.Driver;
public class BorrowedBooks(IMongoCollection<BorrowedBook> collection){ public IEnumerable<BorrowedBook> All() => collection.Find(_ => true).ToList();}import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.readModels.ReadModel
@ReadModeldata class TutorialBorrowedBook(val title: String = "", val memberName: String = "")
/** * Kotlin has no raw MongoCollection to query directly - reads go through the read model service * instead. */class BorrowedBooks(private val store: IEventStore) { suspend fun all(): List<TutorialBorrowedBook> = store.readModels.getInstances(TutorialBorrowedBook::class)}import io.cratis.chronicle.IEventStore;import io.cratis.chronicle.java.ReadModelsJavaBridge;import io.cratis.chronicle.readModels.ReadModel;
import java.util.List;
@ReadModelrecord TutorialBorrowedBook(String title, String memberName) {}
// Java has no raw MongoCollection to query directly - reads go through the read model service// instead.class BorrowedBooks { private final IEventStore store;
BorrowedBooks(IEventStore store) { this.store = store; }
List<TutorialBorrowedBook> all() { return ReadModelsJavaBridge.getInstances(store.getReadModels(), TutorialBorrowedBook.class); }}defmodule MyApp.TutorialBorrowedBooksService do alias MyApp.ReadModels.BorrowedBook
def all do Cratis.Chronicle.all(BorrowedBook) endendimport { IEventStore } from '@cratis/chronicle';
class BorrowedBooks { constructor(private readonly store: IEventStore) {}
all(): Promise<BorrowedBook[]> { return this.store.readModels.getInstances(BorrowedBook); }}After registering this projection, append another borrow and return for the same book ID. Once each event is processed, the BorrowedBooks query first includes the book and then excludes it. Unlike the first view, the returned book no longer has an instance in this sink. Removing that instance does not delete its events from the log.
Both views use the same history. One retains the catalog entry and its loan flag; the other retains only current loans. Choose a view’s shape around the question its caller needs to answer.
What you did
Section titled “What you did”You mapped borrow and return events onto queryable state. The catalog keeps the book after a return; the BorrowedBook view removes it. Both depend on processing recorded events, so their stored results can lag an append.
The application can now show loans. In the final chapter, you’ll react to a return by calling a notification service for the next member waiting. Continue to reactors →