Skip to content

PulseSharp ​

The engine: setup, the control API and the store contract.

Generated from the XML documentation of PulseSharp.

CursorState ​

csharp
public enum CursorState

The state of a handler in one stream.

Active ​

The handler is up to date or is handling new events.

Retrying ​

The last event failed and will be tried again at HandlerCursor.RetryAt.

Failed ​

The handler gave up on an event. The stream is stopped for this handler until you retry or skip it.

HandlerCursor ​

csharp
public sealed record HandlerCursor

How far one handler has got in one stream.

ParameterDescription
HandlerNameThe stable name of the handler.
StreamThe stream name.
PositionThe position of the last event the handler finished, or 0 when it has finished none.
StateWhether the handler is active, retrying or failed in this stream.
AttemptsHow many times the current event has failed.
LastErrorThe last error, when the current event has failed.
RetryAtWhen the next attempt is due, while retrying.

HandlerCursor(string, string, long, CursorState, int, string, DateTimeOffset?) ​

How far one handler has got in one stream.

ParameterDescription
HandlerNameThe stable name of the handler.
StreamThe stream name.
PositionThe position of the last event the handler finished, or 0 when it has finished none.
StateWhether the handler is active, retrying or failed in this stream.
AttemptsHow many times the current event has failed.
LastErrorThe last error, when the current event has failed.
RetryAtWhen the next attempt is due, while retrying.

HandlerName ​

The stable name of the handler.

Stream ​

The stream name.

Position ​

The position of the last event the handler finished, or 0 when it has finished none.

State ​

Whether the handler is active, retrying or failed in this stream.

Attempts ​

How many times the current event has failed.

LastError ​

The last error, when the current event has failed.

RetryAt ​

When the next attempt is due, while retrying.

HandlerLeaseStatus ​

csharp
public readonly record struct HandlerLeaseStatus

The answer to a handler lease request.

ParameterDescription
HeldWhether the asking runner holds the lease now.
RevisionThe handler's current revision. A change means the cursors were changed by someone else.

HandlerLeaseStatus(bool, long) ​

The answer to a handler lease request.

ParameterDescription
HeldWhether the asking runner holds the lease now.
RevisionThe handler's current revision. A change means the cursors were changed by someone else.

Held ​

Whether the asking runner holds the lease now.

Revision ​

The handler's current revision. A change means the cursors were changed by someone else.

INotifyingStore ​

csharp
public interface INotifyingStore

Optional for stores: tells this app instance at once when another instance saved new events, jobs or cursor changes, so handlers and jobs start right away. Without it, other instances find new work by polling, within about one Advanced.PollInterval.

The engine calls INotifyingStore.ListenForChanges once when the app starts. The store should keep listening until the token is cancelled, and reconnect on its own after a failure; polling covers the gap.

ListenForChanges(Action, CancellationToken) ​

Listens for changes made by any app instance, and calls changed for each one, until cancellationToken is cancelled.

ParameterDescription
changedCalled when something changed. Cheap and safe to call often.
cancellationTokenStops listening when the app stops.

Returns: A task that completes when listening has stopped.

IPulseControl ​

csharp
public interface IPulseControl

Lets an app or an operator see and steer handlers: list their cursors, retry or skip a failed event, or rewind a handler so it handles every event again.

Changes go through the store, so they work from any app instance, whichever instance currently delivers the handler.

GetCursors(string, CancellationToken) ​

Lists the cursors of one handler, or of all handlers.

ParameterDescription
handlerNameThe handler, or null for all handlers.
cancellationTokenCancels the read.

Returns: The cursors, ordered by handler and stream.

Throws ArgumentException when no handler has this name.

Retry(string, string, CancellationToken) ​

Tries the stuck event of a stream again now, with a fresh attempt count.

ParameterDescription
handlerNameThe handler.
streamThe stream.
cancellationTokenCancels the change.

Returns: A task that completes when the change is stored. The app instance that holds the handler applies it within about one poll interval.

Throws ArgumentException when no handler has this name.

Throws InvalidOperationException when the handler has no cursor for this stream.

RetryFailed(string, CancellationToken) ​

Tries every failed stream again now, with a fresh attempt count. Use it when the cause is fixed, for example after the printer has paper again.

ParameterDescription
handlerNameThe handler, or null for all handlers.
cancellationTokenCancels the change.

Returns: How many streams will be tried again. The app instance that holds each handler applies the change within about one poll interval.

Throws ArgumentException when no handler has this name.

Example

csharp
var retried = await control.RetryFailed();

Skip(string, string, CancellationToken) ​

Skips the stuck event of a stream: the handler never handles it, and continues with the next event.

ParameterDescription
handlerNameThe handler.
streamThe stream.
cancellationTokenCancels the change.

Returns: A task that completes when the change is stored. The app instance that holds the handler applies it within about one poll interval.

Throws ArgumentException when no handler has this name.

Throws InvalidOperationException when the stream has no waiting event for this handler.

Rewind(string, CancellationToken) ​

Rewinds a handler to the start, so it handles every stored event again, in order. Use it after fixing a bug in a handler, or to rebuild data the handler writes.

ParameterDescription
handlerNameThe handler.
cancellationTokenCancels the change.

Returns: A task that completes when the change is stored. The app instance that holds the handler applies it within about one poll interval.

Throws ArgumentException when no handler has this name.

GetJob(Guid, CancellationToken) ​

Reads one job.

ParameterDescription
jobIdThe id returned by IPulse.Enqueue.
cancellationTokenCancels the read.

Returns: The job, or null when no job has this id.

GetJobs(JobState?, int, CancellationToken) ​

Lists jobs, newest first.

ParameterDescription
stateOnly jobs in this state, or null for all jobs.
limitThe maximum number of jobs to return. The default is 100.
cancellationTokenCancels the read.

Returns: The jobs.

CancelJob(Guid, CancellationToken) ​

Cancels a job. A waiting job is cancelled at once. A running job gets a cancel request: its handler's CancellationToken is cancelled within about one poll interval.

ParameterDescription
jobIdThe job.
cancellationTokenCancels the request.

Returns: true when the job was waiting or running; false when it does not exist or has already finished.

RetryJob(Guid, CancellationToken) ​

Runs a failed or cancelled job again, with a fresh attempt count.

ParameterDescription
jobIdThe job.
cancellationTokenCancels the request.

Returns: true when the job will run again; false when it does not exist or is not failed or cancelled.

IPulseStore ​

csharp
public interface IPulseStore

Where PulseSharp keeps events, handler cursors and jobs. Implement it to support another database.

A store only saves and reads: ordering, retries, leases and delivery live in the engine. Event and job data arrive already serialized, so a store never deals with .NET types. Every method must be safe to call from several threads at once.

Initialize(CancellationToken) ​

Prepares the store, for example by creating or upgrading its tables. PulseSharp calls it once when the app starts, before any handler or job runs. It must be safe to call more than once.

ParameterDescription
cancellationTokenCancels the preparation.

Returns: A task that completes when the store is ready.

Append(NewEvent, ExpectedVersion, DbTransaction, CancellationToken) ​

Saves an event at the end of its stream, after checking expectedVersion atomically.

ParameterDescription
newEventThe event to save.
expectedVersionWhat the stream must look like for the save to succeed.
transactionThe caller's transaction to save the event in, or null. Stores that can't use it ignore it.
cancellationTokenCancels the save.

Returns: The saved event with its global and stream positions.

Throws ExpectedVersionMismatchException when the stream does not match expectedVersion.

AppendAll(IReadOnlyList<NewEvent>, ExpectedVersion, DbTransaction, CancellationToken) ​

Saves several events at the end of one stream in one commit: all of them, in the order given, or none. expectedVersion is checked atomically against the stream before the first event.

ParameterDescription
eventsThe events to save. All belong to the same stream. There is at least one.
expectedVersionWhat the stream must look like for the save to succeed.
transactionThe caller's transaction to save the events in, or null. Stores that can't use it ignore it.
cancellationTokenCancels the save.

Returns: The saved events with their global and stream positions, in the order given.

Throws ExpectedVersionMismatchException when the stream does not match expectedVersion. Nothing is saved.

ReadAfter(long, IReadOnlySet<string>, int, CancellationToken) ​

Reads events after a global position, in global order, limited to some event names.

ParameterDescription
globalPositionOnly events after this position are returned. 0 reads from the start.
eventNamesOnly events with one of these names are returned.
maxCountThe maximum number of events to return.
cancellationTokenCancels the read.

Returns: The events, ordered by global position.

ReadStream(string, long, int, CancellationToken) ​

Reads the events of one stream after a stream position, in stream order.

ParameterDescription
streamThe stream name.
afterStreamPositionOnly events after this position are returned. 0 reads from the start.
maxCountThe maximum number of events to return.
cancellationTokenCancels the read.

Returns: The events, ordered by stream position.

LoadCursors(string, CancellationToken) ​

Loads every cursor of one handler.

ParameterDescription
handlerNameThe handler.
cancellationTokenCancels the read.

Returns: The cursors, one per stream.

SaveCursor(HandlerCursor, long, CancellationToken) ​

Saves a cursor, replacing the one with the same handler and stream, but only when the handler's revision is still revision. A stale writer (a handler that lost its lease, or a change made by IPulseControl in the meantime) is rejected.

ParameterDescription
cursorThe cursor.
revisionThe handler revision the writer is working with (see IPulseStore.LeaseHandler).
cancellationTokenCancels the save.

Returns: true when the cursor was saved; false when the revision has changed.

SaveCursors(IReadOnlyList<HandlerCursor>, long, CancellationToken) ​

Saves several cursors of one handler in one commit, with the same revision check as IPulseStore.SaveCursor. All of them are saved, or none (when the revision has changed). This is how a handler that works on many streams at once saves its progress with a single commit instead of one per stream.

ParameterDescription
cursorsThe cursors. All belong to the same handler.
revisionThe handler revision the writer is working with (see IPulseStore.LeaseHandler).
cancellationTokenCancels the save.

Returns: true when the cursors were saved; false when the revision has changed.

LeaseHandler(string, string, DateTimeOffset, TimeSpan, CancellationToken) ​

Takes or renews the lease of a handler, so that only one app instance delivers its events at a time. The lease is granted when nobody holds it, when it expired, or when workerId already holds it.

ParameterDescription
handlerNameThe handler.
workerIdThe runner asking for the lease.
nowThe current time.
durationHow long the lease lasts without renewal.
cancellationTokenCancels the request.

Returns: Whether the lease is held, and the handler's current revision.

ReleaseHandler(string, string, CancellationToken) ​

Gives up the lease of a handler held by workerId, so another instance can take it at once.

ParameterDescription
handlerNameThe handler.
workerIdThe runner giving up the lease.
cancellationTokenCancels the request.

Returns: A task that completes when the lease is released.

ChangeCursors(string, IReadOnlyList<HandlerCursor>, CancellationToken) ​

Changes cursors of a handler on behalf of IPulseControl, atomically: increases the handler's revision by one (creating the handler's record when needed) and saves cursors with the new revision, in one transaction. Writes made with an older revision are rejected from then on, and the lease holder reloads its cursors.

ParameterDescription
handlerNameThe handler.
cursorsThe cursors to save. They all belong to handlerName.
cancellationTokenCancels the change.

Returns: The new revision.

AddJob(NewJob, DbTransaction, CancellationToken) ​

Saves a new job in the JobState.Pending state.

ParameterDescription
newJobThe job.
transactionThe caller's transaction to save the job in, or null. Stores that can't use it ignore it.
cancellationTokenCancels the save.

Returns: The saved job.

ClaimNextJob(IReadOnlySet<string>, string, DateTimeOffset, TimeSpan, CancellationToken) ​

Atomically claims the next job to run: a pending or retrying job whose RunAt has come (earliest first, then oldest first), or a running job whose lease has expired. The claimed job becomes running, its attempt count grows by one, and the lease belongs to workerId until now + lease.

ParameterDescription
jobNamesOnly jobs with one of these names can be claimed.
workerIdThe worker that claims the job.
nowThe current time.
leaseHow long the claim lasts without renewal.
cancellationTokenCancels the claim.

Returns: The claimed job, or null when no job is due.

RenewLease(Guid, string, DateTimeOffset, CancellationToken) ​

Extends the lease of a running job, when workerId still holds it.

ParameterDescription
jobIdThe job.
workerIdThe worker.
leaseUntilThe new end of the lease.
cancellationTokenCancels the renewal.

Returns: Whether the worker still holds the lease, and whether a cancel was requested.

SaveProgress(Guid, string, int, int, CancellationToken) ​

Saves the progress of a running job held by workerId.

ParameterDescription
jobIdThe job.
workerIdThe worker.
doneItems finished.
totalItems in total.
cancellationTokenCancels the save.

Returns: A task that completes when the progress is saved.

CompleteJob(Guid, string, DateTimeOffset, CancellationToken) ​

Marks a running job held by workerId as succeeded and ends its lease.

ParameterDescription
jobIdThe job.
workerIdThe worker.
nowThe current time.
cancellationTokenCancels the save.

Returns: A task that completes when the job is saved.

FailJobAttempt(Guid, string, string, DateTimeOffset?, DateTimeOffset, CancellationToken) ​

Records a failed attempt of a running job held by workerId and ends its lease.

ParameterDescription
jobIdThe job.
workerIdThe worker.
errorThe error.
retryAtWhen to try again (the job becomes retrying), or null to mark it failed.
nowThe current time.
cancellationTokenCancels the save.

Returns: A task that completes when the job is saved.

CancelRunningJob(Guid, string, DateTimeOffset, CancellationToken) ​

Marks a running job held by workerId as cancelled and ends its lease.

ParameterDescription
jobIdThe job.
workerIdThe worker.
nowThe current time.
cancellationTokenCancels the save.

Returns: A task that completes when the job is saved.

ReleaseJob(Guid, string, CancellationToken) ​

Hands a running job held by workerId back without counting the attempt (the app is stopping).

ParameterDescription
jobIdThe job.
workerIdThe worker.
cancellationTokenCancels the save.

Returns: A task that completes when the job is saved.

GetJob(Guid, CancellationToken) ​

Reads one job.

ParameterDescription
jobIdThe job.
cancellationTokenCancels the read.

Returns: The job, or null.

GetJobs(JobState?, int, CancellationToken) ​

Lists jobs, newest first.

ParameterDescription
stateOnly jobs in this state, or null for all.
limitThe maximum number of jobs.
cancellationTokenCancels the read.

Returns: The jobs.

RequestCancel(Guid, DateTimeOffset, CancellationToken) ​

Cancels a pending or retrying job at once, or flags a running job for cancellation.

ParameterDescription
jobIdThe job.
nowThe current time.
cancellationTokenCancels the request.

Returns: true when the job was pending, retrying or running.

DeleteFinishedJobs(DateTimeOffset, int, CancellationToken) ​

Deletes jobs that succeeded or were cancelled before a time. Failed, pending, retrying and running jobs are kept.

ParameterDescription
finishedBeforeOnly jobs that finished before this time are deleted.
maxCountThe most jobs to delete in one call.
cancellationTokenCancels the delete.

Returns: How many jobs were deleted.

RetryJob(Guid, DateTimeOffset, CancellationToken) ​

Makes a failed or cancelled job pending again, with a fresh attempt count and progress.

ParameterDescription
jobIdThe job.
nowThe current time, used as the new run time.
cancellationTokenCancels the request.

Returns: true when the job was failed or cancelled.

ISyncStore ​

csharp
public interface ISyncStore

A store that can also take part in sync: it saves events that were emitted on another node, finds the events to send to another node, and remembers how far each remote node has got.

Positions are local to each node. Event ids are global, so a store skips an event whose id it already has.

AppendReplicated(IReadOnlyList<NewEvent>, CancellationToken) ​

Saves events that were emitted on another node, in one atomic step, keeping their id, origin and emit time. Each event gets the next global position and the next position in its stream on this node. An event whose id is already in the store is skipped, so sending the same batch twice is harmless.

ParameterDescription
eventsThe events, in the order they should be saved.
cancellationTokenCancels the save.

Returns: The events that were new, in order, with their positions on this node.

ReadForSync(SyncQuery, CancellationToken) ​

Reads the events that match a query, in global order.

ParameterDescription
queryWhich events to read.
cancellationTokenCancels the read.

Returns: The events, ordered by global position.

CountForSync(SyncQuery, CancellationToken) ​

Counts the events that match a query, in the same way ISyncStore.ReadForSync selects them, but without reading their data. SyncQuery.MaxCount caps the count. This is how a device knows how many events are waiting.

ParameterDescription
queryWhich events to count.
cancellationTokenCancels the count.

Returns: The number of matching events, at most SyncQuery.MaxCount.

LoadSyncPosition(string, SyncDirection, CancellationToken) ​

Loads how far sync has got with a remote node.

ParameterDescription
remoteThe name of the remote node.
directionWhether to load the push or the pull position.
cancellationTokenCancels the read.

Returns: For a push, the last global position on this node that was sent. For a pull, the last global position on the remote node that was received. 0 when nothing has been synced yet.

SaveSyncPosition(string, SyncDirection, long, CancellationToken) ​

Saves how far sync has got with a remote node, replacing the earlier position.

ParameterDescription
remoteThe name of the remote node.
directionWhether this is the push or the pull position.
positionThe position.
cancellationTokenCancels the save.

Returns: A task that completes when the position is saved.

JobInfo ​

csharp
public sealed record JobInfo

The state and progress of one job.

ParameterDescription
JobIdThe id returned by IPulse.Enqueue.
JobNameThe stored name of the job type.
StateThe state of the job.
AttemptsHow many times the job has started.
DoneThe progress the handler last reported: items finished.
TotalThe progress the handler last reported: items in total, or 0 when unknown.
LastErrorThe error of the last failed attempt.
EnqueuedAtWhen the job was enqueued.
RunAtThe earliest time the job runs, or runs again after a failure.
StartedAtWhen the latest attempt started.
FinishedAtWhen the job succeeded, failed for good, or was cancelled.

JobInfo(Guid, string, JobState, int, int, int, string, DateTimeOffset, DateTimeOffset, DateTimeOffset?, DateTimeOffset?) ​

The state and progress of one job.

ParameterDescription
JobIdThe id returned by IPulse.Enqueue.
JobNameThe stored name of the job type.
StateThe state of the job.
AttemptsHow many times the job has started.
DoneThe progress the handler last reported: items finished.
TotalThe progress the handler last reported: items in total, or 0 when unknown.
LastErrorThe error of the last failed attempt.
EnqueuedAtWhen the job was enqueued.
RunAtThe earliest time the job runs, or runs again after a failure.
StartedAtWhen the latest attempt started.
FinishedAtWhen the job succeeded, failed for good, or was cancelled.

JobId ​

The id returned by IPulse.Enqueue.

JobName ​

The stored name of the job type.

State ​

The state of the job.

Attempts ​

How many times the job has started.

Done ​

The progress the handler last reported: items finished.

Total ​

The progress the handler last reported: items in total, or 0 when unknown.

LastError ​

The error of the last failed attempt.

EnqueuedAt ​

When the job was enqueued.

RunAt ​

The earliest time the job runs, or runs again after a failure.

StartedAt ​

When the latest attempt started.

FinishedAt ​

When the job succeeded, failed for good, or was cancelled.

JobLeaseStatus ​

csharp
public readonly record struct JobLeaseStatus

The answer to a lease renewal.

ParameterDescription
HeldWhether the worker still holds the lease.
CancelRequestedWhether a cancel was requested for the job.

JobLeaseStatus(bool, bool) ​

The answer to a lease renewal.

ParameterDescription
HeldWhether the worker still holds the lease.
CancelRequestedWhether a cancel was requested for the job.

Held ​

Whether the worker still holds the lease.

CancelRequested ​

Whether a cancel was requested for the job.

JobState ​

csharp
public enum JobState

The state of a job.

Pending ​

Waiting to run, now or at JobInfo.RunAt.

Running ​

A worker is running the job.

Retrying ​

The last attempt failed. The job runs again at JobInfo.RunAt.

Succeeded ​

The job finished successfully.

Failed ​

The job failed on every attempt. Use IPulseControl.RetryJob to run it again.

Canceled ​

The job was cancelled.

NewEvent ​

csharp
public sealed record NewEvent

An event to save. The engine has already serialized its data.

ParameterDescription
EventIdThe globally unique id of the event (UUIDv7).
StreamThe stream name.
EventNameThe stored name of the event type.
DataThe serialized event (UTF-8 JSON).
OriginThe node that emitted the event.
EmittedAtWhen the event was emitted.

NewEvent(Guid, string, string, Byte[], string, DateTimeOffset) ​

An event to save. The engine has already serialized its data.

ParameterDescription
EventIdThe globally unique id of the event (UUIDv7).
StreamThe stream name.
EventNameThe stored name of the event type.
DataThe serialized event (UTF-8 JSON).
OriginThe node that emitted the event.
EmittedAtWhen the event was emitted.

EventId ​

The globally unique id of the event (UUIDv7).

Stream ​

The stream name.

EventName ​

The stored name of the event type.

Data ​

The serialized event (UTF-8 JSON).

Origin ​

The node that emitted the event.

EmittedAt ​

When the event was emitted.

NewJob ​

csharp
public sealed record NewJob

A job to save. The engine has already serialized its data.

ParameterDescription
JobIdThe globally unique id of the job (UUIDv7).
JobNameThe stored name of the job type.
DataThe serialized job (UTF-8 JSON).
EnqueuedAtWhen the job was enqueued.
RunAtThe earliest time the job may run.

NewJob(Guid, string, Byte[], DateTimeOffset, DateTimeOffset) ​

A job to save. The engine has already serialized its data.

ParameterDescription
JobIdThe globally unique id of the job (UUIDv7).
JobNameThe stored name of the job type.
DataThe serialized job (UTF-8 JSON).
EnqueuedAtWhen the job was enqueued.
RunAtThe earliest time the job may run.

JobId ​

The globally unique id of the job (UUIDv7).

JobName ​

The stored name of the job type.

Data ​

The serialized job (UTF-8 JSON).

EnqueuedAt ​

When the job was enqueued.

RunAt ​

The earliest time the job may run.

PulseSharpAdvanced ​

csharp
public sealed class PulseSharpAdvanced

Settings most apps never need to change. The defaults suit desktop apps, web apps and workers alike.

PollInterval ​

How often handlers and jobs check for new work when nothing wakes them up. The default is 1 second.

MaxParallelStreams ​

How many streams one handler works on at the same time. Events of one stream are always handled in order, one at a time. The default is 8.

MaxParallelJobs ​

How many jobs this app instance runs at the same time. The default is 4.

HandlerTimeout ​

How long one handler may take for one event. When the time is up, the handler's cancellation token is cancelled; if the handler has not stopped 10 seconds later, PulseSharp stops waiting, counts the attempt as failed and retries as usual, so a handler that hangs can never block its stream for good. The default is 5 minutes; null sets no limit.

JobTimeout ​

How long one run of a job may take. It works like PulseSharpAdvanced.HandlerTimeout: the job is cancelled, then abandoned, and the attempt counts as failed. The default is 1 hour; null sets no limit.

KeepFinishedJobs ​

How long to keep jobs that succeeded or were cancelled. After that, the app instance that runs jobs deletes them, so the job table does not grow forever. Failed jobs are kept until they are retried. The default is 7 days; null keeps every job.

JsonOptions ​

The JSON options used to store events and jobs. The default uses JsonSerializerDefaults.Web. For trimming and Native AOT, set options whose TypeInfoResolver is your source-generated JsonSerializerContext.

PulseSharpBuilder ​

csharp
public sealed class PulseSharpBuilder

Configures PulseSharp: the store, the handlers and the delivery settings. Get one from services.AddPulseSharp(pulse => { ... }).

Services ​

The service collection PulseSharp is added to. Extension packages, such as sync, register their services here.

Node ​

The name of this app instance, stored with every event it emits, for example till-1 or cloud. The default is the machine name.

MaxAttempts ​

How many times a handler tries one event before its stream stops for that handler. The default is 5.

RetryDelay ​

The wait before the first retry. Each later retry waits twice as long, up to 5 minutes. The default is 1 second.

Advanced ​

Settings most apps never need to change: polling, parallelism, time limits, clean-up and JSON options.

UseStore(IPulseStore) ​

Uses a store: the place where events, cursors and jobs are kept. Store packages call this from their own method, such as UseSqlite.

ParameterDescription
storeThe store.

Returns: This builder.

On<TEvent>(string, Func<TEvent, EventContext, CancellationToken, Task>) ​

Adds an inline handler for TEvent.

Type parameterDescription
TEventThe event type.
ParameterDescription
nameThe stable name of the handler, for example print-receipt. PulseSharp stores how far the handler has got under this name, so keep it the same between versions of your app.
handlerThe code that handles one event.

Returns: This builder.

Throws InvalidOperationException when another handler already uses name.

AddHandler<TEvent, THandler>() ​

Adds a handler class for TEvent. A new instance is created from dependency injection for every event. Works with trimming and Native AOT.

Type parameterDescription
TEventThe event type.
THandlerThe handler class. Its stable name is the class name, or the name in HandlerNameAttribute.

Returns: This builder.

Throws InvalidOperationException when another handler already uses the same name.

OnJob<TJob>(Func<TJob, JobContext, CancellationToken, Task>) ​

Adds an inline handler for jobs of type TJob. A job type has exactly one handler.

Type parameterDescription
TJobThe job type. Its stored name is the class name, or the name in JobNameAttribute.
ParameterDescription
handlerThe code that runs one job.

Returns: This builder.

Throws InvalidOperationException when TJob already has a handler.

AddJobHandler<TJob, THandler>() ​

Adds a handler class for jobs of type TJob. A new instance is created from dependency injection for every job. Works with trimming and Native AOT.

Type parameterDescription
TJobThe job type. Its stored name is the class name, or the name in JobNameAttribute.
THandlerThe handler class.

Returns: This builder.

Throws InvalidOperationException when TJob already has another handler.

PulseSharpServiceCollectionExtensions ​

csharp
public static class PulseSharpServiceCollectionExtensions

Adds PulseSharp to a service collection.

AddPulseSharp(IServiceCollection, Action<PulseSharpBuilder>) ​

Adds PulseSharp: IPulse for emitting events, IPulseControl for steering handlers, and a hosted service that delivers events to handlers.

ParameterDescription
servicesThe service collection.
configureChooses the store and adds the handlers.

Returns: The service collection.

Throws InvalidOperationException when pulseSharp is added twice, no store is chosen, two handlers or two event types share a name, or a setting is invalid.

Example

csharp
services.AddPulseSharp(pulse =>
{
    pulse.UseSqlite("app.db");
    pulse.On<SaleCompleted>("print-receipt", async (sale, context, ct) => await PrintReceipt(sale, ct));
    pulse.AddHandler<SaleCompleted, UpdateStock>();
});

StoredEvent ​

csharp
public sealed record StoredEvent

A saved event.

ParameterDescription
GlobalPositionThe position in the whole store, starting at 1. Later events have higher positions.
EventIdThe globally unique id of the event.
StreamThe stream name.
StreamPositionThe position in the stream, starting at 1.
EventNameThe stored name of the event type.
DataThe serialized event (UTF-8 JSON).
OriginThe node that emitted the event.
EmittedAtWhen the event was emitted.

StoredEvent(long, Guid, string, long, string, Byte[], string, DateTimeOffset) ​

A saved event.

ParameterDescription
GlobalPositionThe position in the whole store, starting at 1. Later events have higher positions.
EventIdThe globally unique id of the event.
StreamThe stream name.
StreamPositionThe position in the stream, starting at 1.
EventNameThe stored name of the event type.
DataThe serialized event (UTF-8 JSON).
OriginThe node that emitted the event.
EmittedAtWhen the event was emitted.

GlobalPosition ​

The position in the whole store, starting at 1. Later events have higher positions.

EventId ​

The globally unique id of the event.

Stream ​

The stream name.

StreamPosition ​

The position in the stream, starting at 1.

EventName ​

The stored name of the event type.

Data ​

The serialized event (UTF-8 JSON).

Origin ​

The node that emitted the event.

EmittedAt ​

When the event was emitted.

StoredJob ​

csharp
public sealed record StoredJob

A saved job, with its state and lease.

ParameterDescription
JobIdThe job id.
JobNameThe stored name of the job type.
DataThe serialized job (UTF-8 JSON).
StateThe state.
AttemptsHow many times the job has been claimed.
DoneReported progress: items finished.
TotalReported progress: items in total.
LastErrorThe error of the last failed attempt.
EnqueuedAtWhen the job was enqueued.
RunAtThe earliest time the job runs, or runs again.
StartedAtWhen the latest attempt started.
FinishedAtWhen the job reached a final state.
LeaseOwnerThe worker holding the job while it runs.
LeaseUntilWhen the lease ends unless renewed.
CancelRequestedWhether a cancel was requested while the job runs.

StoredJob(Guid, string, Byte[], JobState, int, int, int, string, DateTimeOffset, DateTimeOffset, DateTimeOffset?, DateTimeOffset?, string, DateTimeOffset?, bool) ​

A saved job, with its state and lease.

ParameterDescription
JobIdThe job id.
JobNameThe stored name of the job type.
DataThe serialized job (UTF-8 JSON).
StateThe state.
AttemptsHow many times the job has been claimed.
DoneReported progress: items finished.
TotalReported progress: items in total.
LastErrorThe error of the last failed attempt.
EnqueuedAtWhen the job was enqueued.
RunAtThe earliest time the job runs, or runs again.
StartedAtWhen the latest attempt started.
FinishedAtWhen the job reached a final state.
LeaseOwnerThe worker holding the job while it runs.
LeaseUntilWhen the lease ends unless renewed.
CancelRequestedWhether a cancel was requested while the job runs.

JobId ​

The job id.

JobName ​

The stored name of the job type.

Data ​

The serialized job (UTF-8 JSON).

State ​

The state.

Attempts ​

How many times the job has been claimed.

Done ​

Reported progress: items finished.

Total ​

Reported progress: items in total.

LastError ​

The error of the last failed attempt.

EnqueuedAt ​

When the job was enqueued.

RunAt ​

The earliest time the job runs, or runs again.

StartedAt ​

When the latest attempt started.

FinishedAt ​

When the job reached a final state.

LeaseOwner ​

The worker holding the job while it runs.

LeaseUntil ​

When the lease ends unless renewed.

CancelRequested ​

Whether a cancel was requested while the job runs.

IsClaimableAt(DateTimeOffset) ​

Whether the job can be claimed at now: due and waiting, or running with an expired lease.

ParameterDescription
nowThe current time.

Returns: true when the job can be claimed.

IsHeldBy(string) ​

Whether workerId holds the job while it runs.

ParameterDescription
workerIdThe worker.

Returns: true when the job is running and leased by the worker.

SyncDirection ​

csharp
public enum SyncDirection

Which way events travel between this node and a remote node.

Push ​

This node sends its own events to the remote node.

Pull ​

This node receives the remote node's events.

SyncQuery ​

csharp
public sealed record SyncQuery

Selects the events to send to another node.

ParameterDescription
AfterPositionOnly events after this global position are returned. 0 reads from the start.
OriginOnly events emitted by this node, or null for any node.
ExceptOriginNo events emitted by this node, or null to allow every node.
StreamPrefixesOnly events whose stream name starts with one of these prefixes. Empty means every stream.
MaxCountThe maximum number of events to return.

SyncQuery(long, string, string, IReadOnlyList<string>, int) ​

Selects the events to send to another node.

ParameterDescription
AfterPositionOnly events after this global position are returned. 0 reads from the start.
OriginOnly events emitted by this node, or null for any node.
ExceptOriginNo events emitted by this node, or null to allow every node.
StreamPrefixesOnly events whose stream name starts with one of these prefixes. Empty means every stream.
MaxCountThe maximum number of events to return.

AfterPosition ​

Only events after this global position are returned. 0 reads from the start.

Origin ​

Only events emitted by this node, or null for any node.

ExceptOrigin ​

No events emitted by this node, or null to allow every node.

StreamPrefixes ​

Only events whose stream name starts with one of these prefixes. Empty means every stream.

MaxCount ​

The maximum number of events to return.

Released under the MIT License.