PulseSharp
The engine: setup, the control API and the store contract.
Generated from the XML documentation of
PulseSharp.
CursorState
public enum CursorStateThe 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
public sealed record HandlerCursorHow far one handler has got in one stream.
| Parameter | Description |
|---|---|
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. |
HandlerCursor(string, string, long, CursorState, int, string, DateTimeOffset?)
How far one handler has got in one stream.
| Parameter | Description |
|---|---|
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. |
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
public readonly record struct HandlerLeaseStatusThe answer to a handler lease request.
| Parameter | Description |
|---|---|
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. |
HandlerLeaseStatus(bool, long)
The answer to a handler lease request.
| Parameter | Description |
|---|---|
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. |
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
public interface INotifyingStoreOptional 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.
| Parameter | Description |
|---|---|
changed | Called when something changed. Cheap and safe to call often. |
cancellationToken | Stops listening when the app stops. |
Returns: A task that completes when listening has stopped.
IPulseControl
public interface IPulseControlLets 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.
| Parameter | Description |
|---|---|
handlerName | The handler, or null for all handlers. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
handlerName | The handler. |
stream | The stream. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
handlerName | The handler, or null for all handlers. |
cancellationToken | Cancels 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
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.
| Parameter | Description |
|---|---|
handlerName | The handler. |
stream | The stream. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
handlerName | The handler. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
jobId | The id returned by IPulse.Enqueue. |
cancellationToken | Cancels the read. |
Returns: The job, or null when no job has this id.
GetJobs(JobState?, int, CancellationToken)
Lists jobs, newest first.
| Parameter | Description |
|---|---|
state | Only jobs in this state, or null for all jobs. |
limit | The maximum number of jobs to return. The default is 100. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
jobId | The job. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
jobId | The job. |
cancellationToken | Cancels the request. |
Returns: true when the job will run again; false when it does not exist or is not failed or cancelled.
IPulseStore
public interface IPulseStoreWhere 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.
| Parameter | Description |
|---|---|
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
newEvent | The event to save. |
expectedVersion | What the stream must look like for the save to succeed. |
transaction | The caller's transaction to save the event in, or null. Stores that can't use it ignore it. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
events | The events to save. All belong to the same stream. There is at least one. |
expectedVersion | What the stream must look like for the save to succeed. |
transaction | The caller's transaction to save the events in, or null. Stores that can't use it ignore it. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
globalPosition | Only events after this position are returned. 0 reads from the start. |
eventNames | Only events with one of these names are returned. |
maxCount | The maximum number of events to return. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
stream | The stream name. |
afterStreamPosition | Only events after this position are returned. 0 reads from the start. |
maxCount | The maximum number of events to return. |
cancellationToken | Cancels the read. |
Returns: The events, ordered by stream position.
LoadCursors(string, CancellationToken)
Loads every cursor of one handler.
| Parameter | Description |
|---|---|
handlerName | The handler. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
cursor | The cursor. |
revision | The handler revision the writer is working with (see IPulseStore.LeaseHandler). |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
cursors | The cursors. All belong to the same handler. |
revision | The handler revision the writer is working with (see IPulseStore.LeaseHandler). |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
handlerName | The handler. |
workerId | The runner asking for the lease. |
now | The current time. |
duration | How long the lease lasts without renewal. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
handlerName | The handler. |
workerId | The runner giving up the lease. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
handlerName | The handler. |
cursors | The cursors to save. They all belong to handlerName. |
cancellationToken | Cancels the change. |
Returns: The new revision.
AddJob(NewJob, DbTransaction, CancellationToken)
Saves a new job in the JobState.Pending state.
| Parameter | Description |
|---|---|
newJob | The job. |
transaction | The caller's transaction to save the job in, or null. Stores that can't use it ignore it. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
jobNames | Only jobs with one of these names can be claimed. |
workerId | The worker that claims the job. |
now | The current time. |
lease | How long the claim lasts without renewal. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
jobId | The job. |
workerId | The worker. |
leaseUntil | The new end of the lease. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
jobId | The job. |
workerId | The worker. |
done | Items finished. |
total | Items in total. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
jobId | The job. |
workerId | The worker. |
now | The current time. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
jobId | The job. |
workerId | The worker. |
error | The error. |
retryAt | When to try again (the job becomes retrying), or null to mark it failed. |
now | The current time. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
jobId | The job. |
workerId | The worker. |
now | The current time. |
cancellationToken | Cancels 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).
| Parameter | Description |
|---|---|
jobId | The job. |
workerId | The worker. |
cancellationToken | Cancels the save. |
Returns: A task that completes when the job is saved.
GetJob(Guid, CancellationToken)
Reads one job.
| Parameter | Description |
|---|---|
jobId | The job. |
cancellationToken | Cancels the read. |
Returns: The job, or null.
GetJobs(JobState?, int, CancellationToken)
Lists jobs, newest first.
| Parameter | Description |
|---|---|
state | Only jobs in this state, or null for all. |
limit | The maximum number of jobs. |
cancellationToken | Cancels the read. |
Returns: The jobs.
RequestCancel(Guid, DateTimeOffset, CancellationToken)
Cancels a pending or retrying job at once, or flags a running job for cancellation.
| Parameter | Description |
|---|---|
jobId | The job. |
now | The current time. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
finishedBefore | Only jobs that finished before this time are deleted. |
maxCount | The most jobs to delete in one call. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
jobId | The job. |
now | The current time, used as the new run time. |
cancellationToken | Cancels the request. |
Returns: true when the job was failed or cancelled.
ISyncStore
public interface ISyncStoreA 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.
| Parameter | Description |
|---|---|
events | The events, in the order they should be saved. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
query | Which events to read. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
query | Which events to count. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
remote | The name of the remote node. |
direction | Whether to load the push or the pull position. |
cancellationToken | Cancels 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.
| Parameter | Description |
|---|---|
remote | The name of the remote node. |
direction | Whether this is the push or the pull position. |
position | The position. |
cancellationToken | Cancels the save. |
Returns: A task that completes when the position is saved.
JobInfo
public sealed record JobInfoThe state and progress of one job.
| Parameter | Description |
|---|---|
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. |
JobInfo(Guid, string, JobState, int, int, int, string, DateTimeOffset, DateTimeOffset, DateTimeOffset?, DateTimeOffset?)
The state and progress of one job.
| Parameter | Description |
|---|---|
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. |
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
public readonly record struct JobLeaseStatusThe answer to a lease renewal.
| Parameter | Description |
|---|---|
Held | Whether the worker still holds the lease. |
CancelRequested | Whether a cancel was requested for the job. |
JobLeaseStatus(bool, bool)
The answer to a lease renewal.
| Parameter | Description |
|---|---|
Held | Whether the worker still holds the lease. |
CancelRequested | Whether 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
public enum JobStateThe 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
public sealed record NewEventAn event to save. The engine has already serialized its data.
| Parameter | Description |
|---|---|
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. |
NewEvent(Guid, string, string, Byte[], string, DateTimeOffset)
An event to save. The engine has already serialized its data.
| Parameter | Description |
|---|---|
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. |
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
public sealed record NewJobA job to save. The engine has already serialized its data.
| Parameter | Description |
|---|---|
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. |
NewJob(Guid, string, Byte[], DateTimeOffset, DateTimeOffset)
A job to save. The engine has already serialized its data.
| Parameter | Description |
|---|---|
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. |
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
public sealed class PulseSharpAdvancedSettings 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
public sealed class PulseSharpBuilderConfigures 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.
| Parameter | Description |
|---|---|
store | The store. |
Returns: This builder.
On<TEvent>(string, Func<TEvent, EventContext, CancellationToken, Task>)
Adds an inline handler for TEvent.
| Type parameter | Description |
|---|---|
TEvent | The event type. |
| Parameter | Description |
|---|---|
name | The 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. |
handler | The 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 parameter | Description |
|---|---|
TEvent | The event type. |
THandler | The 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 parameter | Description |
|---|---|
TJob | The job type. Its stored name is the class name, or the name in JobNameAttribute. |
| Parameter | Description |
|---|---|
handler | The 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 parameter | Description |
|---|---|
TJob | The job type. Its stored name is the class name, or the name in JobNameAttribute. |
THandler | The handler class. |
Returns: This builder.
Throws InvalidOperationException when TJob already has another handler.
PulseSharpServiceCollectionExtensions
public static class PulseSharpServiceCollectionExtensionsAdds 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.
| Parameter | Description |
|---|---|
services | The service collection. |
configure | Chooses 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
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
public sealed record StoredEventA saved event.
| Parameter | Description |
|---|---|
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. |
StoredEvent(long, Guid, string, long, string, Byte[], string, DateTimeOffset)
A saved event.
| Parameter | Description |
|---|---|
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. |
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
public sealed record StoredJobA saved job, with its state and lease.
| Parameter | Description |
|---|---|
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. |
StoredJob(Guid, string, Byte[], JobState, int, int, int, string, DateTimeOffset, DateTimeOffset, DateTimeOffset?, DateTimeOffset?, string, DateTimeOffset?, bool)
A saved job, with its state and lease.
| Parameter | Description |
|---|---|
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. |
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.
| Parameter | Description |
|---|---|
now | The current time. |
Returns: true when the job can be claimed.
IsHeldBy(string)
Whether workerId holds the job while it runs.
| Parameter | Description |
|---|---|
workerId | The worker. |
Returns: true when the job is running and leased by the worker.
SyncDirection
public enum SyncDirectionWhich 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
public sealed record SyncQuerySelects the events to send to another node.
| Parameter | Description |
|---|---|
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. |
SyncQuery(long, string, string, IReadOnlyList<string>, int)
Selects the events to send to another node.
| Parameter | Description |
|---|---|
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. |
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.