Cratis Chronicle append notifications and observer completion
Cratis Chronicle’s .NET client reports local append outcomes through AppendOperations. Use these
notifications to record diagnostics or capture events in a test. A notification does not mean
observers have processed the events; use WaitForCompletion() when your next step depends on
that processing.
AppendOperations
Section titled “AppendOperations”using Cratis.Chronicle.EventSequences;
public interface IObservingAppendsEventSequence{ IObservable<IEnumerable<AppendedEventWithResult>> AppendOperations { get; }}import io.cratis.chronicle.eventSequences.AppendedEventWithResultimport kotlinx.coroutines.flow.SharedFlow
/** * The shape of [io.cratis.chronicle.eventSequences.IEventSequence.appendOperations] - a hot * [SharedFlow] that emits after every [io.cratis.chronicle.eventSequences.IEventSequence.append] * or [io.cratis.chronicle.eventSequences.IEventSequence.appendMany] call made through that instance. */interface EventSequenceAppendOperationsShape { val appendOperations: SharedFlow<List<AppendedEventWithResult>>}import io.cratis.chronicle.eventSequences.AppendedEventWithResult;import io.cratis.chronicle.eventSequences.IEventLog;
import java.util.List;import java.util.function.Consumer;
import kotlinx.coroutines.Job;
// The shape of the Java bridge for observing append operations: EventLogJavaBridge.watchAppendOperations// subscribes a callback that receives a list of AppendedEventWithResult after every append or// appendMany call made through the event log, returning the Job backing the subscription.interface EventSequenceAppendOperationsShape { Job watchAppendOperations(IEventLog eventLog, Consumer<List<AppendedEventWithResult>> callback);}Elixir does not support this workflow yet.import { AppendedEventWithResult } from '@cratis/chronicle';
// eventLog.appendOperations is an AsyncIterable<AppendedEventWithResult[]> - a hot,// multicast stream: iterating it yields every batch of events appended through this// specific event log instance from the moment you start iterating (never for// transactional appends, and never replayed for a late subscriber).type ObservingAppendsShape = AsyncIterable<AppendedEventWithResult[]>;Both IEventSequence and IEventLog expose this observable. An ordinary single-event Append
that returns a result emits a collection containing one AppendedEventWithResult. An ordinary,
nonempty AppendMany emits the full batch as one collection. An idempotent retry that finds an
event already appended does not notify it as a new append.
Each entry pairs the event supplied to the append call with its result:
| Member | Type | Description |
|---|---|---|
Event |
AppendedEvent |
The event and its context |
Event.Content |
object |
The event object supplied to the append call |
Event.Context |
EventContext |
Metadata: event source, sequence number, correlation ID, causation chain |
Result |
AppendResult |
Success flag, sequence number, violations, and errors |
Rejected appends can also produce notifications, so check Result.IsSuccess rather than treating a
notification as proof that an event was stored. Notifications are local to this event-sequence
instance; they do not report writes from other clients or processes. Transactional appends through
ITransactionalEventSequence do not fire this observable.
Subscribing
Section titled “Subscribing”Subscribe on the IEventSequence or IEventLog used by the code you want to monitor:
using Cratis.Chronicle.EventSequences;
public class ObservingAppendsMonitor(IEventLog eventLog) : IDisposable{ readonly IDisposable _subscription = eventLog.AppendOperations.Subscribe(OnAppended);
static void OnAppended(IEnumerable<AppendedEventWithResult> operations) { foreach (var item in operations) { Console.WriteLine($"Event {item.Event.Content.GetType().Name} appended: success={item.Result.IsSuccess}"); } }
public void Dispose() => _subscription.Dispose();}import io.cratis.chronicle.eventSequences.IEventLogimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.launch
/** * Collects append operations for as long as [scope] is active, logging each appended event's * outcome. */class AppendMonitor(eventLog: IEventLog, scope: CoroutineScope) { init { scope.launch { eventLog.appendOperations.collect { operations -> operations.forEach { println("Event ${it.event::class.simpleName} appended: success=${it.result.isSuccess}") } } } }}import io.cratis.chronicle.eventSequences.IEventLog;
import io.cratis.chronicle.java.EventLogJavaBridge;import kotlinx.coroutines.Job;
class EventsObservingAppendsSubscribing { // Subscribes to append operations for the lifetime of the returned Job; cancel it to stop. Job subscribe(IEventLog eventLog) { return EventLogJavaBridge.watchAppendOperations(eventLog, operations -> operations.forEach(operation -> System.out.println("Event " + operation.getEvent().getClass().getSimpleName() + " appended: success=" + operation.getResult().isSuccess()))); }}Elixir does not support this workflow yet.import { IEventLog } from '@cratis/chronicle';
async function monitorAppends(eventLog: IEventLog): Promise<void> { for await (const operations of eventLog.appendOperations) { for (const item of operations) { console.log(`Event ${item.event.eventType.id.value} appended: success=${item.result.isSuccess}`); } }}The monitor prints each event’s type and whether its append succeeded. Its Dispose method
releases the subscription; tie that disposal to the monitor’s lifetime. The client invokes
subscribers before returning the append result, so keep notification handlers short.
Integration Testing
Section titled “Integration Testing”For a kernel-backed integration test, IEventAppendCollection from
Cratis.Chronicle.XUnit.Integration collects this client’s event-log append outcomes as
AppendedEventWithResult entries. Follow Event append collection
to set up the fixture and wait for follow-up events.
Waiting for Observer Completion After Append
Section titled “Waiting for Observer Completion After Append”A successful append means the event is persisted, not that its observers have caught up. Projections, reducers, and reactors process events asynchronously. A read model queried immediately after an append may still show the earlier state.
Call WaitForCompletion() on the AppendResult or AppendManyResult when the next step needs
affected observers to finish, such as an integration-test assertion. The extension method is in
Cratis.Chronicle.Observation. Check the append’s IsSuccess first: an append that never reached
the log has nothing to wait for, so its completion result reports success without validating the append.
With the current .NET client and server, the wait includes observers that handle the appended event
types and observers subscribed to all events. Each observer waits through its last matching event
in an AppendMany batch. If its tag, event source type, or event stream type filters exclude the
whole bounded append range, it does not block the wait. The server still waits when it cannot
establish a match, including for disconnected observers or an unknown or oversized append range.
The completion result exposes IsSuccess, FailedPartitions, TimedOut, and
OutstandingObservers. The last property contains observer IDs still behind at the deadline.
The default server timeout is five seconds; pass a TimeSpan to change it or
Timeout.InfiniteTimeSpan to wait without a deadline. The .NET client allows an additional 200 ms
for the server to return timeout details. A timeout returns IsSuccess false and TimedOut true
rather than throwing.
A successful append on the in-process testing surfaces (EventScenario and EventStoreForTesting)
has no observer service to wait on. Calling WaitForCompletion() there throws
CannotWaitForObserverCompletion. Assert through those testing surfaces directly, or use a
kernel-backed fixture to check observer completion.
Append
Section titled “Append”using Cratis.Chronicle.Events;using Cratis.Chronicle.EventSequences;using Cratis.Chronicle.Observation;
[EventType]public record ObservingAppendsSomeEvent(string Data);
public class ObservingAppendsCompletionWaiter(IEventLog eventLog){ public async Task AppendAndWait(EventSourceId eventSourceId) { var appendResult = await eventLog.Append(eventSourceId, new ObservingAppendsSomeEvent("example"));
// A failed append has nothing to wait for, and waiting on it reports success. if (!appendResult.IsSuccess) { return; }
var completion = await appendResult.WaitForCompletion();
if (!completion.IsSuccess) { foreach (var failedPartition in completion.FailedPartitions) { Console.WriteLine($"Observer {failedPartition.ObserverId} failed partition {failedPartition.Partition}"); } } }}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.ObservingAppendsSomeEvent do use Cratis.Chronicle.Events.EventType, id: "observing-appends-some-event"
defstruct [:data]end
defmodule MyApp.ObservingAppendsCompletionWaiter do alias Cratis.Chronicle.EventSequences.EventLog alias MyApp.Events.ObservingAppendsSomeEvent
def append_and_wait(event_source_id) do case EventLog.append_and_wait_for_completion(event_source_id, %ObservingAppendsSomeEvent{ data: "example" }) do {:ok, %{success: true}} -> :ok
{:ok, %{success: false, failed_partitions: failed_partitions}} -> Enum.each(failed_partitions, fn failed_partition -> IO.puts("Observer failed partition: #{inspect(failed_partition)}") end)
{:error, reason} -> {:error, reason} end endendimport { eventType, IEventLog } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class ObservingAppendsSomeEvent { @field(String) readonly data: string;
constructor(data: string = '') { this.data = data; }}
async function appendAndWait(eventLog: IEventLog, eventSourceId: string): Promise<void> { const appendResult = await eventLog.append(eventSourceId, new ObservingAppendsSomeEvent('example')); const completion = await appendResult.waitForCompletion();
if (!completion.isSuccess) { for (const failedPartition of completion.failedPartitions) { console.log(`Observer ${failedPartition.observerId} failed partition ${failedPartition.partition}`); } }}AppendMany
Section titled “AppendMany”using Cratis.Chronicle.Events;using Cratis.Chronicle.EventSequences;using Cratis.Chronicle.Observation;
[EventType]public record ObservingAppendsFirstEvent(string Data);
[EventType]public record ObservingAppendsSecondEvent(string Data);
public class ObservingAppendsBatchCompletionWaiter(IEventLog eventLog){ public async Task AppendManyAndWait(EventSourceId eventSourceId) { var appendManyResult = await eventLog.AppendMany(eventSourceId, new object[] { new ObservingAppendsFirstEvent("first"), new ObservingAppendsSecondEvent("second") });
// A failed append has nothing to wait for, and waiting on it reports success. if (!appendManyResult.IsSuccess) { return; }
var completion = await appendManyResult.WaitForCompletion(); if (!completion.IsSuccess) { // Inspect failed partitions from affected observers } }}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.ObservingAppendsFirstEvent do use Cratis.Chronicle.Events.EventType, id: "observing-appends-first-event"
defstruct [:data]end
defmodule MyApp.Events.ObservingAppendsSecondEvent do use Cratis.Chronicle.Events.EventType, id: "observing-appends-second-event"
defstruct [:data]end
defmodule MyApp.ObservingAppendsBatchCompletionWaiter do alias Cratis.Chronicle.EventSequences.{AppendResult, EventLog} alias MyApp.Events.{ObservingAppendsFirstEvent, ObservingAppendsSecondEvent}
def append_many_and_wait(event_source_id) do events = [ %ObservingAppendsFirstEvent{data: "first"}, %ObservingAppendsSecondEvent{data: "second"} ]
case EventLog.append_many_with_result(event_source_id, events) do {:ok, %AppendResult{} = append_many_result} -> case AppendResult.wait_for_completion(append_many_result, timeout: 10_000) do {:ok, %{success: true}} -> :ok
{:ok, %{success: false, failed_partitions: failed_partitions}} -> # Inspect failed partitions from affected observers {:error, {:failed_partitions, failed_partitions}}
{:error, reason} -> {:error, reason} end
# A failed append has nothing to wait for. {:error, %AppendResult{} = rejected} -> {:error, rejected}
{:error, reason} -> {:error, reason} end endendimport { eventType, IEventLog } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class ObservingAppendsFirstEvent { @field(String) readonly data: string;
constructor(data: string = '') { this.data = data; }}
@eventType()class ObservingAppendsSecondEvent { @field(String) readonly data: string;
constructor(data: string = '') { this.data = data; }}
async function appendManyAndWait(eventLog: IEventLog, eventSourceId: string): Promise<void> { const appendManyResults = await eventLog.appendMany(eventSourceId, [ new ObservingAppendsFirstEvent('first'), new ObservingAppendsSecondEvent('second') ]);
for (const appendResult of appendManyResults) { const completion = await appendResult.waitForCompletion(); if (!completion.isSuccess) { // Inspect completion.failedPartitions from affected observers. } }}Both examples check append success before waiting, then inspect completion separately. The events can be stored while an affected observer has failed or timed out.
Client and server compatibility
Section titled “Client and server compatibility”The .NET client sends per-event-type tail sequence numbers and explicitly marks the first number in the append range, including a batch that starts at zero. Older .NET clients that omit that range information cannot get the same filter-aware waits. A range larger than the server’s bounded scan also falls back to waiting through the relevant tail.
TypeScript’s waitForCompletion and Elixir’s wait_for_completion and
append_and_wait_for_completion send only the overall append tail. Their requests do not narrow
the wait by event type or identify the append range for filter-aware waits. Their timeout behavior
differs from .NET’s; do not assume the same timeout diagnostics across clients.
An older server ignores the new fields, so even a newer .NET client can time out on a filtered observer or mixed-type batch. If the server ignores the deadline, client cancellation returns a timed-out result without outstanding observer names.
If the next step can tolerate a read model catching up later, you do not need to wait. Design that path to handle an older view rather than assuming every successful append is immediately visible.