Event log
Append an event to record what happened, then decide whether you need to wait for its consequences. Chronicle’s event log is its primary event sequence. Start with a connected event store and a registered event type; TypeScript client setup covers both. For a non-local server, complete the connection security setup first.
Call eventStore.eventLog.append(eventSourceId, event) with the ID of the source the event belongs to. For an order, that might be order-123 and an instance of your registered OrderPlaced class. The ID groups that order’s events; it is not the event type. Appending events shows the shared workflow, and Event sources and streams explains optional named routing.
Inspect the returned AppendResult.isSuccess before doing anything that assumes the event was stored. A constraint violation, concurrency violation, or append error is returned in constraintViolations, concurrencyViolation, or errors; it does not automatically throw. Prevalidation and transport failures can still reject the append call. For a batch, appendMany returns one result per event, so check each result.
An accepted append does not mean a reactor, reducer, or projection has finished processing it. In a script or test, you can wait on that accepted result with waitForCompletion(): inspect completion.isSuccess and completion.failedPartitions, and handle rejection separately. A timeout or cancellation stops the wait, not the append. Do not append the event again just because the wait ended. The failed-partitions example shows these branches together. If you then need current state, read the model and handle absence; a successful wait does not promise that a particular model/key exists.
Enriching event content before append
Section titled “Enriching event content before append”Use eventEnrichmentProviders on ChronicleOptions to fill schema-defined content fields from client-side context after serialization, such as the namespace that recorded an event. Providers apply to production append and both appendMany overloads on every event store and event sequence created by that client, including the event log.
import { ChronicleClient, ChronicleOptions, eventType, type EventEnrichmentProvider } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType('EnrichedOrderPlaced')class EnrichedOrderPlaced { @field(String) readonly orderNumber: string; @field(String) readonly recordedInNamespace: string;
constructor(orderNumber: string, recordedInNamespace = '') { this.orderNumber = orderNumber; this.recordedInNamespace = recordedInNamespace; }}
async function appendEnrichedOrder(): Promise<void> { const recordNamespace: EventEnrichmentProvider = (content, context) => { content.recordedInNamespace = context.namespace; };
const client = new ChronicleClient(ChronicleOptions.fromConnectionString( 'chronicle://localhost:35000', { eventEnrichmentProviders: [recordNamespace] } )); try { const store = await client.getEventStore('Orders', 'sales'); const result = await store.eventLog.append('order-123', new EnrichedOrderPlaced('123')); if (!result.isSuccess) { throw new Error('Order was not appended'); } } finally { client.dispose(); }}A provider receives a mutable serialized JSON object and read-only EventEnrichmentContext: the original event, event type, event store, namespace, sequence ID, source ID, and correlation ID. It may add, replace, or remove content properties, including nested values. Keep the result JSON-serializable and compatible with the registered event schema; this is not a way to bypass schema validation. Treat the original event and context as read-only. Routing, tags, subjects, causation, and other append metadata are separate from content and are not changed by enrichment.
Providers may return void or Promise<void>. They run and are awaited in configured order, each seeing the preceding provider’s mutations. Batch events are enriched sequentially in input order, with the complete provider list applied to each event before moving to the next. All enrichment finishes before the append request is sent. A provider that throws or rejects (or content that fails JSON serialization) rejects the append; later providers are not invoked and no append request is sent, including when a later event in a batch fails. Providers’ own external side effects are not rolled back.
With no providers, content and append behavior are unchanged. Configuration copies the provider list when options are created; configure it before constructing the client. These callbacks are not run by the synchronous in-process testing client, compensation, or event import.
TypeScript client notes
Section titled “TypeScript client notes”- An append without route options leaves the route to the kernel. Clients before this change sent a
Defaultroute themselves, so existing streams need attention; follow Preserve existing append routes before upgrading. AppendOptionsacceptssourceType,streamType,streamId,subject,occurred,correlationId,tags,namedTags,concurrencyScope, andconcurrencyScopes. Rich batch entries override shared metadata; concurrency scopes remain independent.- Structured named tags are
NamedTagvalues: a nonblank name and an exact, possibly empty, value. Pass them asnamedTagsonAppendOptions(shared by every event) or on anEventForEventSourceIdentry (that event only). Each event gets its own tags first, then the shared ones, keeping the first occurrence of each exact name and value pair. An invalid tag throwsInvalidNamedTagbefore anything is sent. An append that carries named tags uses the kernel’s dedicated named-tag call, so a kernel without named-tag support rejects it instead of dropping the tags. Read them back fromcontext.namedTagson read and delivered events. - A batch can combine non-empty named tags with registered
eventSourceentries, on the same or on different events, and every event keeps its event source. This needs Chronicle kernel 19.37.4 or later; older kernels drop the registered event source in such a batch (kernel issue). The client throwsNamedTagsWithRegisteredEventSourceNotSupportedbefore sending this combination when the kernel version is older, unknown, or unparseable. WithskipCompatibilityCheck=truethe version is unknown, so this combination also throws. Single appends and batches without this combination are unaffected. eventLog.redact(sequenceNumber, reason)andeventLog.redactForEventSource(eventSourceId, reason, eventTypes?)permanently rewrite an event’s (or an entire event source’s) content — a destructive GDPR/compliance erasure, never a field-level mask. Read Event redaction before using them.eventLog.copy(sourceId, targetId, ...eventTypes)starts a durable kernel job that copies the events of one event source onto another and returns the job’sGuid. Pass event type classes to limit the copy; with none, events of every type are copied. It resolves once the kernel accepts the job, not when the copy has finished. See Copying events.eventLog.compensate(sequenceNumber, event, options?)appends a compensating event that offsets the event atsequenceNumber. The event goes to the event source, stream and subject of the compensated event, sooptionsaccepts onlycorrelationId,tagsandoccurred. The event class must be declared with@compensationFor(OriginalEvent); a rejected compensation, such as a missing compensated event or a compensation type that does not match, is reported inresult.errors. See Event compensation.eventLog.getForEventSourceIdAndEventTypes(eventSourceId, eventTypes, ...)andeventLog.getFromSequenceNumber(sequenceNumber, eventSourceId?, eventTypes?)read appended events back, filtered by event source and/or event type. Use Getting events when you need the events themselves rather than a read model.- Route arguments on
getForEventSourceIdAndEventTypesandgetTailSequenceNumberdo not default to the legacyDefaultroute. An omitted dimension does not narrow the read, so it also returns the events the kernel routed for an append with no route options. Pass the dimensions explicitly to scope a read to one stream; see Preserve existing append routes. eventLog.getNextSequenceNumber()returns the sequence number the next append will receive (EventSequenceNumber.firstwhen the sequence is empty).eventLog.completeStream(eventStreamType, eventStreamId)permanently closes a non-default stream; further appends to it are rejected with aStreamClosedconstraint violation. See Closing streams.eventLog.appendOperationsis a hot, multicastAsyncIterableof every append this event log instance makes, together with its result. Observing appends describes this client-side observation; it is not observer completion.appendResult.waitForCompletion(timeoutMs?)waits for every observer affected by an accepted append to catch up or fail. Pass{ timeoutMs?, signal? }instead to cancel the underlying wait RPC when the caller aborts; either the signal or timeout cancels it. The timeout defaults to 5 seconds. Timeout, cancellation, and RPC failures reject the wait; observer failures are returned in its completion result. For an unsuccessful append it resolves immediately withisSuccess: trueand no failed partitions, because there is nothing to wait for. That is why you must check the append’s ownisSuccessfirst. See Failed Partitions.appendMany(events: EventForEventSourceId[], options?)sends everyoptions.concurrencyScopeslabel, including labels that are not append targets. A target without an explicit entry uses the sharedconcurrencyScopeoption. The kernel requires at least one event per batch; a scope-only batch is rejected.- For optimistic concurrency, use
EventSequenceNumber.beforeFirst.valueassequenceNumberwhen a scope must assert that no matching event exists. It is sent as the wireExpectsNoMatchingEventflag, not as a sequence number;EventSequenceNumber.unset.valuemeans no expected revision. On a kernel that does not support the flag, the check is skipped, so verify server compatibility before relying on this for a first append.