Consuming a data subscription
-
A subscription worker is the client-side component that consumes a subscription.
-
The worker connects to the server, receives a batch of documents, hands the batch to your processing code, and when done, acknowledges its progress to the server so the server can keep track and provide the next batch.
-
This page explains how to create and run a subscription worker using the client API.
-
In this article:
- Creating a subscription worker
- Running the worker
- Node connection and failover
- At-least-once delivery
- Worker strategies
- Error handling
- Worker status
- Reading document metadata
- Examples
- Full exception handling with retries
- Setting the batch size
- Processing documents in a session
- Processing dynamic objects
- Processing a blittable object
- Reading a document's metadata
- End when no documents are left
- Including documents in the batch
- Standby workers on several machines
- Primary and secondary workers
- Syntax
Creating a subscription worker
Create a worker using the store's Subscriptions.GetSubscriptionWorker method, passing either the
subscription name or a SubscriptionWorkerOptions object.
subscriptionWorker = store.Subscriptions.GetSubscriptionWorker<Order>(subscriptionName);
This constructs the worker but does not run it yet.
Running the worker
To start processing the documents the server sends, call the worker's Run method, passing the
logic that handles each batch:
subscriptionRuntimeTask = subscriptionWorker.Run(batch =>
{
// your batch-processing logic here
});
From this point on, the worker receives and processes document batches, acknowledging each batch so the server can keep track of the subscription's progress and provide the next batch if available.
The Run method returns a task that stays alive while the worker is processing. If processing is aborted,
this task completes with an exception.
Processing batches synchronously (by passing Run a synchronous function) may delay other operations your
application is running.
When your batch-processing code performs an operation that waits for an external resource (e.g., saving changes
to the server through the batch's session), the thread that runs your code is blocked until the operation
completes, and other operations cannot use this thread meanwhile.
When many threads are blocked this way (e.g., when several workers wait at the same time), other operations may
have to wait for a free thread.
Processing batches asynchronously frees the thread while an operation that waits for an external resource
is in progress, so other operations can use the thread.
To process batches asynchronously, pass Run an async function that awaits asynchronous methods
(like the LoadAsync and SaveChangesAsync methods of a session opened with batch.OpenAsyncSession).
See, for instance, the Async tab of the
processing documents in a session
example.
Whether you process batches synchronously or asynchronously, the worker passes the next batch to your code only after your code finishes processing the current batch.
Node connection and failover
-
The worker first contacts one of the database group's nodes. If this node does not run the subscription task, the node redirects the worker to the node that does.
The worker keeps using the node that runs the task as long as no error occurs. -
If the task is pinned to its mentor node, the worker is always redirected to the mentor node, so while the mentor node is down the worker cannot process the subscription.
-
If the worker loses the connection and cannot reach the node again, the worker tries the database group's other nodes in turn. A node that does not run the task redirects the worker to the node that does.
At-least-once delivery
The server advances a subscription's progress only when the worker acknowledges a batch.
If a worker stops (or its connection fails) before acknowledging a batch, the server will re-send the
same batch the next time a worker connects to the subscription.
Delivery is therefore at-least-once: documents may be processed more than once, but none are skipped. Make your processing idempotent to make sure that reprocessing a document has no unintended effect.
Concurrent subscriptions add another way a document can be reprocessed, by reassigning a dropped worker's documents to the other workers.
Worker strategies
A worker is configured with a strategy, set in the
SubscriptionWorkerOptions
Strategy property, that decides whether the worker may connect to the subscription
and how it behaves toward a worker that is already connected.
The following strategies allow only one worker connected at a time:
OpenIfFree
The server lets the worker connect only if no other worker is connected.
If another worker is already connected, the incoming worker throws aSubscriptionInUseException.WaitForFree
If the subscription is in use, the worker waits for the connected worker to disconnect, then takes its place.
This suits failover, where a standby worker waits to take over from the active one.TakeOver
The incoming worker tries to take over the existing connection.
It succeeds if the connected worker does not itself useTakeOver.- If the takeover succeeds, the worker that has been taken over throws a
SubscriptionInUseException. - If the takeover fails, the incoming worker throws the exception instead.
- If the takeover succeeds, the worker that has been taken over throws a
To let several workers consume the same subscription at the same time, use the Concurrent strategy.
See Concurrent subscriptions.
First worker to connect sets the subscription mode
The first worker to connect sets whether the subscription runs in single-worker or concurrent mode, and this mode holds until all workers disconnect:
- A subscription running concurrent workers admits only other concurrent workers. A worker that uses
a single-worker strategy is rejected with
SubscriptionInUseException. - A subscription running a single-worker strategy admits no concurrent worker until the connected
worker disconnects. A concurrent worker is rejected with
SubscriptionInUseException.
Error handling
Connection failures
When an error interrupts the worker's communication with the server, the worker tries to reconnect
(see Node connection and failover).
The worker keeps retrying even when it cannot reach any server, or when the cluster has no leader to
name the node responsible for the subscription, until the period set in MaxErroneousPeriod passes
(see Reconnection and timeouts).
The worker stops without reconnecting in these cases:
- The subscription does not exist (e.g., it was deleted).
- The subscription is in use by another worker, or another worker took it over (see Worker strategies).
- The worker uses the
Concurrentstrategy on a sharded database, which does not support concurrent subscriptions (see Unsupported features). - The subscription was disabled, or the worker's connection was dropped (see Dropping connections).
- The worker failed to connect for longer than
MaxErroneousPeriod. - The subscription cannot run in its current state (e.g., a revisions subscription on a collection whose revisions are disabled).
- An authorization error occurred.
- The database does not exist.
- Your batch-processing code threw an exception, and
IgnoreSubscriberErrorsis not set (see Errors while processing a batch). - The worker runs with
CloseWhenNoDocsLeftand no documents are left (see End when no documents are left).
When the worker stops instead of reconnecting, the task returned by Run completes in error.
To follow the worker's connection and reconnection attempts,
see Worker status.
Errors while processing a batch
When your batch-processing code throws an exception, the worker's response depends on the
IgnoreSubscriberErrors option of the SubscriptionWorkerOptions object:
false(default)
Processing stops. The worker wraps the exception in aSubscriberErrorExceptionand rethrows it without acknowledging progress, so the task returned byRuncompletes in error.true
The failed batch is acknowledged without a retry, and the worker continues with the next batches.
Reconnection and timeouts
These SubscriptionWorkerOptions properties govern reconnection and connection timeouts:
TimeToWaitBeforeConnectionRetry
How long the worker waits before each reconnect attempt.
Default: 5 seconds.MaxErroneousPeriod
How long the worker may keep failing to reconnect, counted from the first failure since its last successful connection, before the worker stops retrying.
Default: 5 minutes.ConnectionStreamTimeout
How long the worker waits for data from the server, or for a write to the server to complete, before treating the connection as broken and trying to reconnect.
Default: 30 seconds. Cannot be set below 15 seconds.
var options = new SubscriptionWorkerOptions(subscriptionName);
// Set the worker's timeout period
options.ConnectionStreamTimeout = TimeSpan.FromSeconds(45);
Worker status
Status and state changes
To check the worker's current activity (e.g., whether the worker is connected to the server), read the worker's Status property.
The Status property returns a SubscriptionWorkerStatus object,
whose State property holds one of the following states:
NotStarted
The worker was created, butRunhas not been called yet.Connecting
The worker is connecting to the subscription, at startup or before a reconnection.WaitingForDocuments
The worker is connected and waiting for the next batch.Processing
Your processing code is handling a batch.
This state lasts until the worker acknowledges the batch to the server.Retrying
The connection failed, and the worker is waiting to reconnect (see Connection failures).Faulted
The worker stopped without reconnecting, and the task returned byRuncompleted in error.Stopped
The worker was disposed, or the cancellation token passed toRunwas canceled.
Once the worker reaches Faulted or Stopped, the worker's state no longer changes.
When the state is Retrying or Faulted, the Exception property of the SubscriptionWorkerStatus object holds the failure
that caused the state.
If the worker fails repeatedly, the Exception property holds the latest failure.
The FailingSinceUtc property of the SubscriptionWorkerStatus object holds the time of the first failure since the worker's
last successful connection, or null while the worker is connected.
Read Status when your application needs the worker's state at a specific moment (e.g., when a health check runs).
To be notified of every state change as soon as the change happens (e.g., to raise an alert when the worker starts retrying),
subscribe to the worker's OnStateChanged event.
The event passes the worker and the worker's new status (a SubscriptionWorkerStatus object) to your handler.
The worker does not continue until your handler returns, so avoid long-running or blocking work in the handler:
a handler that never returns keeps the worker from continuing.
If the handler throws an exception, the worker catches the exception and continues.
// FailingSinceUtc is null while the worker is connected, and is set while the worker is failing
SubscriptionWorkerStatus status = subscriptionWorker.Status;
if (status.FailingSinceUtc != null)
Console.WriteLine($"Failing since {status.FailingSinceUtc}: {status.Exception?.Message}");
// Write each change of the worker's state to the console
subscriptionWorker.OnStateChanged += (worker, newStatus) =>
{
Console.WriteLine($"Worker state: {newStatus.State}");
};
To monitor the subscription on the server side using Studio, see Monitoring a data subscription.
Worker events
The worker's events are standard C# events: attach a handler to an event using +=, and detach the handler using -=
(see Subscribing to store events, which shows both operations
on the document store's events).
To detach a handler later, keep a reference to the handler when you attach it (e.g., use a named method rather than
a lambda expression), since -= must receive the same handler.
To react to the worker's connections, failures, acknowledged batches, and disposal, subscribe to these worker events:
OnEstablishedSubscriptionConnection
Fires each time the worker connects to the subscription, both the first time and after every reconnection.OnUnexpectedSubscriptionError
Fires when the worker hits an error it does not recognize (e.g., a dropped network connection), before the worker waits to reconnect.OnSubscriptionConnectionRetry
Fires each time the worker is about to reconnect, after the wait set inTimeToWaitBeforeConnectionRetry.AfterAcknowledgment
Fires after the server acknowledges the progress of a processed batch.
The handler receives the acknowledged batch and returns aTask. The worker passes the next batch to your code only after this task completes.OnDisposed
Fires after the worker is disposed.
When the worker stops instead of reconnecting, neither OnUnexpectedSubscriptionError
nor OnSubscriptionConnectionRetry fires.
The following code writes a message to the console on each connection, unrecognized error, and reconnection attempt:
// Fires on the first connection and after every reconnection
subscriptionWorker.OnEstablishedSubscriptionConnection += () =>
{
Console.WriteLine("Connected to the subscription");
};
// Fires for an error the worker does not recognize, before the wait
subscriptionWorker.OnUnexpectedSubscriptionError += exception =>
{
Console.WriteLine($"Unexpected subscription error: {exception.Message}");
};
// Fires before each reconnection attempt, after the wait
subscriptionWorker.OnSubscriptionConnectionRetry += exception =>
{
Console.WriteLine($"Reconnecting to the subscription after: {exception.Message}");
};
Reading document metadata
The Metadata property of each batch item holds the metadata
of the item's document (see SubscriptionBatch<T>.Item),
with properties set by RavenDB (e.g., @collection and @last-modified) and any property you set yourself (like trace.id,
which the worker in the example below reads from each item's document).
subscriptionRuntimeTask = subscriptionWorker.Run(batch =>
{
foreach (var item in batch.Items)
{
// Read a metadata property you set yourself
// ('TryGetValue' returns false if the metadata does not hold the property)
if (item.Metadata.TryGetValue("trace.id", out string traceId))
{
// your processing logic here
}
}
});
Changing a document's metadata changes the document. If the changed document matches the subscription's query,
the subscription sends the document to the worker with the changed metadata held in the item's Metadata property.
- When a subscription's query applies a projection,
the
Metadataproperty of each item holds the metadata of the item's projected object, not the metadata of the source document. - When a subscription sends document revisions, each item holds two revisions of a
document, each revision carrying its own metadata.
The item'sMetadataproperty holds only a few properties RavenDB sets for the item itself, like@idand@change-vector, not the metadata of either revision.
See Example: Reading a document's metadata
See Reading a revision's metadata
Examples
Example: Full exception handling with retries
In this example, the client handles the exceptions the worker may throw, recreating the worker to resume processing when the error is recoverable.
while (true)
{
// Create the worker:
var options = new SubscriptionWorkerOptions(subscriptionName);
// Configure the worker:
// Allow a downtime of up to 2 hours,
// and wait 2 minutes before reconnecting
options.MaxErroneousPeriod = TimeSpan.FromHours(2);
options.TimeToWaitBeforeConnectionRetry = TimeSpan.FromMinutes(2);
subscriptionWorker = store.Subscriptions.GetSubscriptionWorker<Order>(options);
try
{
// Before each reconnection attempt, write the error that caused it to the console
subscriptionWorker.OnSubscriptionConnectionRetry += exception =>
{
Console.WriteLine($"Reconnecting to the subscription after: {exception.Message}");
};
// Run the worker:
await subscriptionWorker.Run(batch =>
{
foreach (var item in batch.Items)
{
// Forcefully stop subscription processing if the order's Company is "companies/2-A"
// and throw an exception to let external logic handle the specific case
if (item.Result.Company == "companies/2-A")
{
// The custom exception thrown from here
// will be wrapped by `SubscriberErrorException`
throw new UnsupportedCompanyException(
"Company ID cannot be 'companies/2-A', please fix");
}
// Process the order document - provide your own logic
ProcessOrder(item.Result);
}
}, cancellationToken);
// The Run method will stop if the subscription worker is disposed,
// exiting the while loop
return;
}
catch (Exception e)
{
Console.WriteLine($"Failure in subscription {subscriptionName}: {e.Message}");
// The following exceptions are not recoverable
if (e is DatabaseDoesNotExistException ||
e is SubscriptionDoesNotExistException ||
e is SubscriptionInvalidStateException ||
e is AuthorizationException)
throw;
if (e is SubscriptionClosedException)
// Subscription probably closed explicitly by admin
return;
if (e is SubscriberErrorException se)
{
// For UnsupportedCompanyException we want to throw an exception,
// otherwise, continue processing
if (se.InnerException != null && se.InnerException is UnsupportedCompanyException)
{
throw;
}
// Call continue to skip the current while(true) iteration and try reconnecting
// in the next one, allowing the worker to process future batches.
continue;
}
// Handle this depending on the subscription opening strategy
if (e is SubscriptionInUseException)
continue;
// Call return to exit the while(true) loop,
// dispose of the worker (via finally), and stop the subscription.
return;
}
finally
{
subscriptionWorker.Dispose();
}
}
Example: Setting the batch size
In this example, the worker sets the maximum number of documents the server sends in each batch.
var workerWBatch = store.Subscriptions.GetSubscriptionWorker<Order>(
new SubscriptionWorkerOptions(subscriptionName)
{
MaxDocsPerBatch = 20
});
var subscriptionRuntimeTask = workerWBatch.Run(x =>
{
// your custom logic
});
Example: Processing documents in a session
In this example, the subscription sends to the worker Orders that have no shipping date.
The worker sets each document's ShippedAt field and saves it back through a session.
Open the session using batch.OpenSession or batch.OpenAsyncSession, not store.OpenSession or store.OpenAsyncSession.
- Sync
- Async
// Create the subscription task on the server:
var subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions()
{
Query = @"from Orders as o where o.ShippedAt = null"
});
// Create the subscription worker that will consume the documents:
var subscriptionWorker = store.Subscriptions.GetSubscriptionWorker<Order>(subscriptionName);
var subscriptionRuntimeTask = subscriptionWorker.Run(batch =>
{
// Open a session using 'batch.OpenSession'
using (var session = batch.OpenSession())
{
foreach (var order in batch.Items.Select(x => x.Result))
{
TransferOrderToShipmentCompany(order); // call your custom method
order.ShippedAt = DateTime.UtcNow; // update the document field
}
// Save the updated Order documents
session.SaveChanges();
}
});
// Create the subscription task on the server:
var subscriptionName = await store.Subscriptions.CreateAsync(new SubscriptionCreationOptions()
{
Query = @"from Orders as o where o.ShippedAt = null"
});
// Create the subscription worker that will consume the documents:
var subscriptionWorker = store.Subscriptions.GetSubscriptionWorker<Order>(subscriptionName);
// Pass an async function, so the thread is not blocked while your code awaits the server
var subscriptionRuntimeTask = subscriptionWorker.Run(async batch =>
{
// Open an asynchronous session using 'batch.OpenAsyncSession'
using (var session = batch.OpenAsyncSession())
{
foreach (var order in batch.Items.Select(x => x.Result))
{
TransferOrderToShipmentCompany(order); // call your custom method
order.ShippedAt = DateTime.UtcNow; // update the document field
}
// Save the updated Order documents
await session.SaveChangesAsync();
}
});
Example: Processing dynamic objects
In this example, the subscription projects each Order into a dynamic shape, and the worker processes the
dynamic objects it receives.
// Create the subscription task on the server:
var subscriptionName = "My dynamic subscription";
store.Subscriptions.Create(new SubscriptionCreationOptions<Order>()
{
Name = subscriptionName,
Projection = order =>
new { DynamicField = "Company: " + order.Company + " Employee: " + order.Employee }
});
// Create the subscription worker that will consume the documents:
var subscriptionWorker = store.Subscriptions.GetSubscriptionWorker(subscriptionName);
var subscriptionRuntimeTask = subscriptionWorker.Run(batch =>
{
foreach (var item in batch.Items)
{
// Access the dynamic field in the document
dynamic field = item.Result.DynamicField;
// Call your custom method
ProcessItem(field);
}
});
Example: Processing a blittable object
In this example, the worker processes documents as low-level blittable objects.
Working with blittable objects directly can help in extreme high-performance scenarios, but is risky because it uses unmanaged memory directly.
// Create the subscription task on the server:
var subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions<Order>
{
Projection = x => new
{
x.Employee
}
});
// Create the subscription worker that will consume the documents:
var subscriptionWorker =
// Specify `BlittableJsonReaderObject` as the generic type parameter
store.Subscriptions.GetSubscriptionWorker<BlittableJsonReaderObject>(subscriptionName);
var subscriptionRuntimeTask = subscriptionWorker.Run(batch =>
{
foreach (var item in batch.Items)
{
// Access the Employee field within the blittable object
var employeeField = item.Result["Employee"].ToString();
ProcessItem(employeeField); // call your custom method
}
});
Example: Reading a document's metadata
In this example, the application sets a trace.id metadata property in an Order document, and the worker reads this property from each order
the subscription sends.
For an explanation of the metadata an item holds, see
Reading document metadata.
Setting the metadata property
using (var session = store.OpenSession())
{
var order = session.Load<Order>("orders/1-A");
// Set a metadata property of your own
session.Advanced.GetMetadataFor(order)["trace.id"] = "1234567";
// Saving the change makes the subscription send the order to the worker,
// if the order matches the subscription's query
session.SaveChanges();
}
Reading the metadata property in the worker
var worker = store.Subscriptions.GetSubscriptionWorker<Order>(subscriptionName);
var subscriptionRuntimeTask = worker.Run(batch =>
{
foreach (var item in batch.Items)
{
// 'TryGetValue' returns false for orders whose metadata does not hold 'trace.id'
if (item.Metadata.TryGetValue("trace.id", out string traceId))
{
Console.WriteLine($"Order {item.Id} has the trace ID {traceId}");
}
}
});
Example: End when no documents are left
In this example, the worker runs until no new documents remain, which suits ad-hoc, single-use processing where
you need every matching document processed once.
Set CloseWhenNoDocsLeft to true; the worker then throws a SubscriptionClosedException when
it finishes.
// Create the subscription task on the server:
var subscriptionName = store.Subscriptions.Create<Order>(
new SubscriptionCreationOptions<Order>
{
Filter = order => order.Lines.Sum(line => line.PricePerUnit * line.Quantity) > 10000,
Projection = order => new OrderAndCompany
{
OrderId = order.Id,
Company = RavenQuery.Load<Company>(order.Company)
}
});
// Create the subscription worker that will consume the documents:
var highValueOrdersWorker = store.Subscriptions.GetSubscriptionWorker<OrderAndCompany>(
new SubscriptionWorkerOptions(subscriptionName)
{
// Here we set the worker to stop when there are no more documents left to send
// Will throw SubscriptionClosedException when it finishes its job
CloseWhenNoDocsLeft = true
});
try
{
await highValueOrdersWorker.Run(batch =>
{
foreach (var item in batch.Items)
{
SendThankYouNoteToCompany(item.Result); // call your custom method
}
});
}
catch (SubscriptionClosedException)
{
// That's expected, no more documents to process
}
Example: Including documents in the batch
In this example, the subscription sends to the worker every Order and includes in the batch
Product documents referenced in the order.
When the worker accesses an included Product, the product's data has already arrived in the batch,
so the worker does not need to fetch the product from the server.
- Sync
- Async
// Create the subscription task on the server:
var subscriptionName = store.Subscriptions.Create(new SubscriptionCreationOptions()
{
// Include the referenced Product documents for each Order document
Query = @"from Orders include Lines[].Product"
});
// Create the subscription worker that will consume the documents:
var subscriptionWorker = store.Subscriptions.GetSubscriptionWorker<Order>(subscriptionName);
var subscriptionRuntimeTask = subscriptionWorker.Run(batch =>
{
// Open a session using 'batch.OpenSession' to access the Product documents
using (var session = batch.OpenSession())
{
foreach (var order in batch.Items.Select(x => x.Result))
{
foreach (var orderLine in order.Lines)
{
// Calling Load will not generate a request to the server,
// since orderLine.Product was included in the batch
var product = session.Load<Product>(orderLine.Product);
ProcessOrderAndProduct(order, product); // call your custom method
}
}
}
});
// Create the subscription task on the server:
var subscriptionName = await store.Subscriptions.CreateAsync(new SubscriptionCreationOptions()
{
// Include the referenced Product documents for each Order document
Query = @"from Orders include Lines[].Product"
});
// Create the subscription worker that will consume the documents:
var subscriptionWorker = store.Subscriptions.GetSubscriptionWorker<Order>(subscriptionName);
// Pass an async function, so the thread is not blocked while your code awaits the server
var subscriptionRuntimeTask = subscriptionWorker.Run(async batch =>
{
// Open an asynchronous session using 'batch.OpenAsyncSession' to access the Product documents
using (var session = batch.OpenAsyncSession())
{
foreach (var order in batch.Items.Select(x => x.Result))
{
foreach (var orderLine in order.Lines)
{
// Calling LoadAsync will not generate a request to the server,
// since orderLine.Product was included in the batch
var product = await session.LoadAsync<Product>(orderLine.Product);
ProcessOrderAndProduct(order, product); // call your custom method
}
}
}
});
Example: Standby workers on several machines
In this example, the same worker code runs on several machines, all using the WaitForFree strategy.
One worker connects to the subscription, and the other workers wait.
If the connected worker disconnects (e.g., when its machine goes down), one of the waiting workers connects and
continues processing.
Unlike in the primary and secondary workers
example, a worker that reconnects after a failure does not take the connection back, but joins the waiting workers.
var worker = store.Subscriptions.GetSubscriptionWorker<Order>(
new SubscriptionWorkerOptions(subscriptionName)
{
// WaitForFree: wait and take over if the connected worker fails
Strategy = SubscriptionOpeningStrategy.WaitForFree
});
Example: Primary and secondary workers
In this example, the two workers form an active-standby pair: the primary, using TakeOver, establishes the
connection; the secondary, using WaitForFree, waits to take over if the primary fails.
The primary worker:
while (true)
{
// Create a new worker for each attempt: a worker cannot run again once Run was called
var primaryWorker = store.Subscriptions.GetSubscriptionWorker<Order>(
new SubscriptionWorkerOptions(subscriptionName)
{
Strategy = SubscriptionOpeningStrategy.TakeOver
});
try
{
await primaryWorker.Run(x =>
{
// your logic
});
}
catch (Exception)
{
// retry
}
finally
{
primaryWorker.Dispose();
}
}
The secondary worker:
while (true)
{
// Create a new worker for each attempt: a worker cannot run again once Run was called
var secondaryWorker = store.Subscriptions.GetSubscriptionWorker<Order>(
new SubscriptionWorkerOptions(subscriptionName)
{
Strategy = SubscriptionOpeningStrategy.WaitForFree
});
try
{
await secondaryWorker.Run(x =>
{
// your logic
});
}
catch (Exception)
{
// retry
}
finally
{
secondaryWorker.Dispose();
}
}
Syntax
Methods
- GetSubscriptionWorker
- Run
Create a subscription worker through store.Subscriptions.
SubscriptionWorker<dynamic> GetSubscriptionWorker(
string subscriptionName, string database = null);
SubscriptionWorker<dynamic> GetSubscriptionWorker(
SubscriptionWorkerOptions options, string database = null);
SubscriptionWorker<T> GetSubscriptionWorker<T>(
string subscriptionName, string database = null) where T : class;
SubscriptionWorker<T> GetSubscriptionWorker<T>(
SubscriptionWorkerOptions options, string database = null) where T : class;
| Parameter | Type | Description |
|---|---|---|
| subscriptionName | string | The name of the subscription the worker connects to. |
| options | SubscriptionWorkerOptions | Options that affect how the worker interacts with the subscription. They do not change the subscription's own definition. |
| database | string | The database where the subscription task resides. If null, the document store's default database is used. |
| Return value | |
|---|---|
SubscriptionWorker | The created worker. It is idle until you call Run. |
Start the worker's batch processing. Pass the delegate that processes each received batch.
Task Run(Action<SubscriptionBatch<T>> processDocuments,
CancellationToken ct = default(CancellationToken));
Task Run(Func<SubscriptionBatch<T>, Task> processDocuments,
CancellationToken ct = default(CancellationToken));
| Parameter | Type | Description |
|---|---|---|
| processDocuments | Action<SubscriptionBatch<T>> | Delegate for synchronous batch processing. |
| processDocuments | Func<SubscriptionBatch<T>, Task> | Delegate for asynchronous batch processing. |
| ct | CancellationToken | A token used to halt the worker. |
| Return value | |
|---|---|
Task | A task that stays alive while the worker is processing or trying to. If processing is aborted, the task completes with an exception. |
Classes
- SubscriptionWorkerOptions
- SubscriptionOpeningStrategy
When you create a worker using SubscriptionWorkerOptions, the only required property is
SubscriptionName; the rest fall back to their defaults.
public sealed class SubscriptionWorkerOptions
{
public string SubscriptionName { get; }
public int MaxDocsPerBatch { get; set; }
public int SendBufferSizeInBytes { get; set; }
public int ReceiveBufferSizeInBytes { get; set; }
public bool IgnoreSubscriberErrors { get; set; }
public bool CloseWhenNoDocsLeft { get; set; }
public TimeSpan TimeToWaitBeforeConnectionRetry { get; set; }
public TimeSpan ConnectionStreamTimeout { get; set; }
public TimeSpan MaxErroneousPeriod { get; set; }
public SubscriptionOpeningStrategy Strategy { get; set; }
}
| Property | Type | Description |
|---|---|---|
| SubscriptionName | string | The name of the subscription the worker connects to. |
| MaxDocsPerBatch | int | The maximum number of documents the server tries to send in a batch. If it finds fewer, it sends what it has without waiting. Default: 4096. |
| SendBufferSizeInBytes | int | The size of the TCP socket buffer the worker uses to send data. Default: 32,768 bytes (32 KiB). |
| ReceiveBufferSizeInBytes | int | The size of the TCP socket buffer the worker uses to receive data. Default: 32,768 bytes (32 KiB). |
| IgnoreSubscriberErrors | bool | Whether processing continues when your batch-handling code throws. true continues; false (default) aborts. |
| CloseWhenNoDocsLeft | bool | Whether the connection closes when no new documents remain. true processes all available documents and then throws a SubscriptionClosedException (useful for one-time processing); false (default) keeps the worker waiting for new documents. |
| TimeToWaitBeforeConnectionRetry | TimeSpan | The wait before each reconnection attempt. Default: 5 seconds. |
| ConnectionStreamTimeout | TimeSpan | How long the worker waits for data from the server, or for a write to the server to complete, before treating the connection as broken. Default: 30 seconds. Minimum: 15 seconds. |
| MaxErroneousPeriod | TimeSpan | How long the worker may keep failing to reconnect, counted from the first failure since its last successful connection, before the worker stops retrying. Default: 5 minutes. |
| Strategy | SubscriptionOpeningStrategy | How the server handles this worker's connection attempt. Default: OpenIfFree. |
The strategy that decides whether a worker may connect to a subscription. See Worker strategies.
public enum SubscriptionOpeningStrategy
{
// Connect if no other worker is connected
OpenIfFree,
// Take over the connection
TakeOver,
// Wait for the currently connected worker to disconnect
WaitForFree,
// Connect concurrently
Concurrent
}
- SubscriptionBatch<T>
- SubscriptionBatch<T>.Item
The batch passed to your Run delegate (see Running the worker).
| Property | Type | Description |
|---|---|---|
| Items | List<SubscriptionBatch<T>.Item> | The items in the batch. |
| NumberOfItemsInBatch | int | The number of items in the batch. |
| LastSentChangeVectorInBatch | string | The change vector of the last item in the batch. The worker acknowledges the batch to the server with this value, so do not change it. |
| Method | Return value | Description |
|---|---|---|
| OpenSession() | IDocumentSession | Opens a session that tracks the batch's documents and included documents. Projected items and revisions are not tracked (see Processing projected objects). |
| OpenSession(SessionOptions options) | IDocumentSession | Opens a session with the given session options. |
| OpenAsyncSession() | IAsyncDocumentSession | The asynchronous version of OpenSession(). |
| OpenAsyncSession(SessionOptions options) | IAsyncDocumentSession | The asynchronous version of OpenSession(SessionOptions options). |
-
Do not set
DatabaseorRequestExecutorin the session options: the session always uses the subscription's database and the node the worker is connected to. Setting either of them, or a transaction mode other thanSingleNode, throws an exception. -
The session does not fail over to other nodes. If the node the worker is connected to fails while your code uses the session, the session's requests throw an exception, which reaches your batch-processing code (see Errors while processing a batch).
-
You can open only one session per batch. A second call to
OpenSessionorOpenAsyncSessionthrows an exception.
A single item in a subscription batch.
public struct Item
{
public T Result { get; internal set; }
public string ExceptionMessage { get; internal set; }
public string Id { get; internal set; }
public string ChangeVector { get; internal set; }
public bool Projection { get; internal set; }
public bool Revision { get; internal set; }
public BlittableJsonReaderObject RawResult { get; internal set; }
public BlittableJsonReaderObject RawMetadata { get; internal set; }
public IMetadataDictionary Metadata { get; internal set; }
}
| Property | Type | Description |
|---|---|---|
| Result | T | The batch item. If T is BlittableJsonReaderObject, no deserialization takes place. |
| ExceptionMessage | string | The exception message thrown while processing the document on the server side. |
| Id | string | The document ID of the item's underlying document. |
| ChangeVector | string | The change vector of the item's underlying document. |
| Projection | bool | true when the item is a projection produced by the subscription query rather than a full document. |
| Revision | bool | true when the item is a document revision, for a subscription that streams revisions. |
| RawResult | BlittableJsonReaderObject | The item before deserialization to T. |
| RawMetadata | BlittableJsonReaderObject | The item's metadata, as a raw JSON object. |
| Metadata | IMetadataDictionary | The item's metadata, as a dictionary. For an item that holds a document: the document's metadata. For a projected item: the metadata of the projected object. For a revision item: only a few properties RavenDB sets for the item. See Reading document metadata. |
Use this struct only within the subscription's Run delegate. Using it outside that scope may
cause unexpected behavior.
- SubscriptionWorker<T>
The worker returned by GetSubscriptionWorker.
Methods
| Method | Return type | Description |
|---|---|---|
| Dispose() | void | Aborts the worker, waiting for the task returned by Run to finish. |
| DisposeAsync() | ValueTask | The asynchronous version of Dispose(). |
| Dispose(bool waitForSubscriptionTask) | void | Aborts the worker, letting you choose whether to wait for the Run task. |
| DisposeAsync(bool waitForSubscriptionTask) | ValueTask | The asynchronous version of Dispose(bool waitForSubscriptionTask). |
| Run (overloads) | Task | Starts the worker's batch processing. See Run above. |
Events
| Event | Type | Description |
|---|---|---|
| AfterAcknowledgment | AfterAcknowledgmentAction | Fires after the server acknowledges the progress of a processed batch. |
| OnSubscriptionConnectionRetry | Action<Exception> | Fires each time the worker is about to reconnect, after the wait set in TimeToWaitBeforeConnectionRetry.Receives the exception that caused the reconnection. |
| OnUnexpectedSubscriptionError | Action<Exception> | Fires when the worker hits an error it does not recognize, before the worker waits to reconnect. Receives the exception. |
| OnEstablishedSubscriptionConnection | Action | Fires each time the worker connects to the subscription, both the first time and after every reconnection. |
| OnStateChanged | Action< | Fires on every change of the worker's state. Receives the worker and the worker's new status. |
| OnDisposed | Action< | Fires after the worker is disposed. |
AfterAcknowledgmentAction is defined as:
public delegate Task AfterAcknowledgmentAction(SubscriptionBatch<T> batch);
Properties
| Property | Type | Description |
|---|---|---|
| CurrentNodeTag | string | The node tag of the RavenDB server currently handling the subscription. |
| SubscriptionName | string | The name of the subscription being processed. |
| Status | SubscriptionWorkerStatus | The worker's current status (see Status and state changes). |
| WorkerId | string | The worker ID. |
- SubscriptionWorkerStatus
- SubscriptionWorkerState
The worker's status, returned by the worker's Status property and passed to OnStateChanged handlers.
See Status and state changes.
public sealed class SubscriptionWorkerStatus
{
public SubscriptionWorkerState State { get; }
public Exception Exception { get; }
public DateTime SinceUtc { get; }
public DateTime? FailingSinceUtc { get; }
}
| Property | Type | Description |
|---|---|---|
| State | SubscriptionWorkerState | The worker's current state. |
| Exception | Exception | The failure that caused the Retrying or Faulted state, or null in other states.If the worker fails repeatedly, this property holds the latest failure. |
| SinceUtc | DateTime | The time the worker entered the current state. |
| FailingSinceUtc | DateTime? | The time of the first failure since the worker's last successful connection, or null while the worker is connected. |
The stages of a worker's activity. See Status and state changes.
public enum SubscriptionWorkerState
{
// Run has not been called yet
NotStarted,
// Connecting to the subscription, at startup or before a reconnection
Connecting,
// Connected and waiting for the next batch
WaitingForDocuments,
// Processing a batch, until the worker acknowledges the batch to the server
Processing,
// The connection failed, and the worker is waiting to reconnect
Retrying,
// Stopped without reconnecting, and the task returned by Run completed in error
Faulted,
// Disposed, or the cancellation token passed to Run was canceled
Stopped
}