Cratis Chronicle event reads for inspecting history
Read events directly from Cratis Chronicle when you need to inspect an entity’s history or diagnose the facts behind its current state. Use an event source read for one entity, a sequence-number read for a known position, or a metadata lookup when you do not need the payload.
The .NET examples use IEventSequence and its specialized IEventLog. For a history view that should not load everything at once, use .NET keyset-paged reads: pages advance by sequence number rather than by an offset. GetPage reads forward or backward within inclusive bounds; GetLatest starts at the tail and returns matching events newest first. Both return a continuation only when another matching page exists.
Read metadata by sequence locator
Section titled “Read metadata by sequence locator”Use GetMetadataAt when you already know an event’s sequence number and need its context,
not its payload. The single-locator overload returns null for a missing event. The batch
overload returns an immutable dictionary keyed by sequence number and omits missing events.
using Cratis.Chronicle.Events;using Cratis.Chronicle.EventSequences;
public static class EventMetadataReads{ // Call only after your application authorizes access to these events. public static async Task Read(IEventSequence eventSequence) { EventMetadata? metadata = await eventSequence.GetMetadataAt((EventSequenceNumber)42UL); if (metadata is not null) { Console.WriteLine($"{metadata.EventStreamType}: {metadata.CausedBy.Resolution}"); }
var batch = await eventSequence.GetMetadataAt([42UL, 43UL]); foreach (var entry in batch.Values) { Console.WriteLine($"{entry.SequenceNumber}: {entry.CausedBy.Name ?? "Name unavailable"}"); } }}defmodule MyApp.MetadataAtReader do alias Chronicle.EventSequences.Streams
# Call only after your application authorizes access to these events. def read do case Streams.get_metadata_at(42) do {:ok, metadata} -> IO.puts("#{metadata.event_stream_type}: #{metadata.resolved_caused_by.resolution}")
{:error, :not_found} -> :ok end
{:ok, batch} = Streams.get_metadata([42, 43])
for entry <- batch do name = if entry.caused_by, do: entry.caused_by.name, else: "Name unavailable" IO.puts("#{entry.sequence_number}: #{name}") end endendA request accepts at most 500 locators, including duplicates. Chronicle rejects larger requests before querying storage and removes duplicates from accepted requests. These are point lookups, not reads of everything after a checkpoint.
Metadata includes routing, occurred time, correlation, causation, tags, subject, source name, and the caused-by identity chain. It contains no payload, generation, content hash or revision content, and does not release compliance-protected data. Identity names resolve from storage on each read, so a rename appears on the next metadata read. See identity resolution for the resolution statuses and privacy boundaries.
Your application must authorize access to the event store, namespace and requested events before calling this API. Metadata can still contain personal information, including identity names, tags and causation properties.
Examples
Section titled “Examples”Read events for a single event source
Section titled “Read events for a single event source”using Cratis.Chronicle.Events;using Cratis.Chronicle.EventSequences;using System.Collections.Immutable;
[EventType]public record GettingEventsOrderPlaced(string OrderId, decimal Total);
[EventType]public record GettingEventsOrderCancelled(string OrderId, string Reason);
public class GettingEventsOrderHistoryReader(IEventLog eventLog){ public async Task<IImmutableList<AppendedEvent>> GetOrderEvents(EventSourceId orderId) { // Filters the timeline to only the order events you care about. var eventTypes = new[] { typeof(GettingEventsOrderPlaced).GetEventType(), typeof(GettingEventsOrderCancelled).GetEventType() };
return await eventLog.GetForEventSourceIdAndEventTypes(orderId, eventTypes); }}import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.events.EventType
@EventTypedata class EventsForSourceAccountOpened(val accountId: String = "", val ownerName: String = "")
suspend fun getAccountOpenedEvents(store: IEventStore, accountId: String) = store.eventLog.getForEventSourceIdAndEventTypes(accountId, listOf(EventsForSourceAccountOpened::class))import io.cratis.chronicle.EventStore;import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.eventSequences.AppendedEvent;
import java.util.List;
import io.cratis.chronicle.java.EventLogJavaBridge;
@EventTyperecord EventsForSourceAccountOpened(String accountId, String ownerName) {}
class EventsGettingEventsForEventSource { List<AppendedEvent> getAccountOpenedEvents(EventStore store, String accountId) { return EventLogJavaBridge.getForEventSourceIdAndEventTypes( store.getEventLog(), accountId, List.of(EventsForSourceAccountOpened.class)); }}defmodule MyApp.Events.GettingEventsOrderPlaced do use Chronicle.Events.EventType, id: "getting-events-order-placed"
defstruct [:order_id, :total]end
defmodule MyApp.Events.GettingEventsOrderCancelled do use Chronicle.Events.EventType, id: "getting-events-order-cancelled"
defstruct [:order_id, :reason]end
defmodule MyApp.GettingEventsOrderHistoryReader do alias Chronicle.EventSequences.EventLog alias MyApp.Events.{GettingEventsOrderCancelled, GettingEventsOrderPlaced}
def get_order_events(order_id) do # Filters the timeline to only the order events you care about. EventLog.get_for_event_source(order_id, event_types: [GettingEventsOrderPlaced, GettingEventsOrderCancelled] ) endendimport { eventType, IEventStore } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class GettingEventsOrderPlaced { @field(String) readonly orderId: string; @field(Number) readonly total: number;
constructor(orderId: string = '', total: number = 0) { this.orderId = orderId; this.total = total; }}
@eventType()class GettingEventsOrderCancelled { @field(String) readonly orderId: string; @field(String) readonly reason: string;
constructor(orderId: string = '', reason: string = '') { this.orderId = orderId; this.reason = reason; }}
async function getOrderEvents(store: IEventStore, orderId: string): Promise<void> { // Filters the timeline to only the order events you care about. const events = await store.eventLog.getForEventSourceIdAndEventTypes( orderId, [GettingEventsOrderPlaced, GettingEventsOrderCancelled]);
for (const event of events) { console.log(`${event.eventType.id.value} at sequence ${event.context.sequenceNumber}`); }}The .NET example filters by event source and event types. Kotlin supports an optional event-source filter on getFromSequenceNumber, and Java’s blocking wrapper accepts it too. Use TypeScript’s getForEventSourceIdAndEventTypes to filter by event source and event types. Elixir provides get_for_event_source/3.
Read from a checkpoint
Section titled “Read from a checkpoint”using Cratis.Chronicle.Events;using Cratis.Chronicle.EventSequences;using System.Collections.Immutable;
public class GettingEventsReplayEvents(IEventLog eventLog){ public async Task<IImmutableList<AppendedEvent>> ReadFrom(EventSequenceNumber sequenceNumber) { // Replays from a known checkpoint to rebuild projections or read models. return await eventLog.GetFromSequenceNumber(sequenceNumber); }}import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.eventSequences.AppendedEventimport io.cratis.chronicle.eventSequences.EventSequenceNumber
/** * Replays every event from a known checkpoint onwards, across all event sources - useful for * rebuilding projections or read models from a saved position. */suspend fun readFrom(store: IEventStore, sequenceNumber: Long): List<AppendedEvent> = store.eventLog.getFromSequenceNumber(EventSequenceNumber(sequenceNumber))import io.cratis.chronicle.EventStore;import io.cratis.chronicle.eventSequences.AppendedEvent;
import java.util.List;
import io.cratis.chronicle.java.EventLogJavaBridge;
class EventsGettingEventsFromCheckpoint { // Replays every event from a known checkpoint onwards, across all event sources. List<AppendedEvent> readFrom(EventStore store, long sequenceNumber) { return EventLogJavaBridge.getFromSequenceNumber(store.getEventLog(), sequenceNumber, null, null); }}defmodule MyApp.GettingEventsReplayEvents do alias Chronicle.EventSequences.EventLog
def read_from(sequence_number) do # Replays from a known checkpoint to rebuild projections or read models. EventLog.get_from_sequence_number(sequence_number) endendimport { EventSequenceNumber, IEventStore } from '@cratis/chronicle';
async function readFrom(store: IEventStore, sequenceNumber: EventSequenceNumber): Promise<void> { // Replays from a known checkpoint to rebuild projections or read models. const events = await store.eventLog.getFromSequenceNumber(sequenceNumber);
for (const event of events) { console.log(`${event.eventType.id.value} at sequence ${event.context.sequenceNumber}`); }}The start position is inclusive: passing the last processed sequence number reads it again if it matches the filters. Save the next unread position when you want to resume without rereading that event. Kotlin, Java, and TypeScript expose getFromSequenceNumber; Elixir exposes get_from_sequence_number/3.
Read the last events in a sequence
Section titled “Read the last events in a sequence”using Cratis.Chronicle.Events;using Cratis.Chronicle.EventSequences;using System.Collections.Immutable;using System.Linq;
public class GettingEventsTailReader(IEventLog eventLog){ public async Task<IImmutableList<AppendedEvent>> ReadLast(int count) { // Reads from the computed start and trims in memory to the requested count. var tail = await eventLog.GetTailSequenceNumber(); var start = tail.IsActualValue && tail.Value >= (ulong)count ? tail - (count - 1) : EventSequenceNumber.First;
var events = await eventLog.GetFromSequenceNumber(start); return events.TakeLast(count).ToImmutableList(); }}import io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.eventSequences.AppendedEventimport io.cratis.chronicle.eventSequences.EventSequenceNumber
/** * Reads from a computed start position and trims in memory to the requested count. */suspend fun readLast(store: IEventStore, count: Int): List<AppendedEvent> { val tail = store.eventLog.getTailSequenceNumber() val start = if (tail.isActualValue && tail.value >= count - 1) { EventSequenceNumber(tail.value - (count - 1)) } else { EventSequenceNumber.first }
val events = store.eventLog.getFromSequenceNumber(start) return events.takeLast(count)}import io.cratis.chronicle.EventStore;import io.cratis.chronicle.eventSequences.AppendedEvent;
import java.util.List;
import io.cratis.chronicle.java.EventLogJavaBridge;
class EventsGettingEventsTail { // Reads from a computed start position and trims in memory to the requested count. // The tail sequence number bridge returns -1 when the sequence is unavailable (empty). List<AppendedEvent> readLast(EventStore store, int count) { long tail = EventLogJavaBridge.getTailSequenceNumber(store.getEventLog(), null); long start = tail >= 0 && tail >= count - 1 ? tail - (count - 1) : 0;
List<AppendedEvent> events = EventLogJavaBridge.getFromSequenceNumber(store.getEventLog(), start, null, null); return events.size() > count ? events.subList(events.size() - count, events.size()) : events; }}defmodule MyApp.GettingEventsTailReader do alias Chronicle.EventSequences.EventLog
def read_last(count) do # Reads from the computed start and trims in memory to the requested count. with {:ok, tail} <- EventLog.get_tail_sequence_number() do start = if tail >= count, do: tail - (count - 1), else: 0
with {:ok, events} <- EventLog.get_from_sequence_number(start) do {:ok, Enum.take(events, -count)} end end endendimport { IEventStore } from '@cratis/chronicle';
async function reportSequencePosition(store: IEventStore): Promise<void> { // The tail is the most recently appended event; unset (EventSequenceNumber.unset) // when the sequence is empty. const tail = await store.eventLog.getTailSequenceNumber();
// getNextSequenceNumber is one past the tail, or EventSequenceNumber.first when // empty - the sequence number the next appended event will receive. const next = await store.eventLog.getNextSequenceNumber();
console.log(`Tail: ${tail.value}, next append will be at: ${next.value}`);}This .NET example calculates a start position from the tail, reads forward, and trims the result in memory. It does not limit the server response to that count. Use GetLatest for a bounded newest-first read, or Getting state if you need only the tail sequence number.