Sync with H.Necessaire: Requests, Daemons and Processors

Move entity changes between nodes with SyncRequests, a processing daemon, and your own sync processors.

Applies to H.Necessaire 4.0.5.

H.Necessaire's sync system moves entity changes from one node to another (a client to a server, a device to a backend) without the sender waiting on the receiver. The unit of work is a SyncRequest: a JSON snapshot of one entity plus a status. This article covers the contracts, the receiving side that ships with the Runtime, and how to add a processor for your own entity type.

Install

dotnet add package H.Necessaire.Runtime

The model

class SyncRequest : IStringIdentity
{
    string ID  => $"{PayloadType}_{PayloadIdentifier}";
    string PayloadType        // the entity's type name
    string PayloadIdentifier  // the entity's ID
    string Payload            // JSON snapshot
    SyncStatus SyncStatus     // defaults to NotSynced
    DateTime HappenedAt
    OperationContext OperationContext
}

enum SyncStatus { Inexistent = -1, NotSynced = 0, DeletedAndNotSynced = 1, Synced = 1000, DeletedAndSynced = 1001 }

Because the request's ID is derived from the entity's type and identifier, there is at most one pending request per entity. If an entity changes twice before the receiver gets to it, the newer request replaces the older one when saved.

The sending side: contracts

interface ImSyncable { }                       // marker for entities that can be synced

interface ImASyncRegistry                       // tracks sync state per entity, for one receiver
{
    SyncNode ReceiverNode { get; }
    Task<SyncStatus> StatusFor(string entityType, string entityIdentifier);
    Task SetStatusFor(string entityType, string entityIdentifier, SyncStatus syncStatus);
    Task<string[]> GetEntitiesToSync(string entityType, int maxBatchSize = 100);
}

interface ImASyncer<TEntity, TId> : ImASyncer where TEntity : ImSyncable
{
    Task<ImASyncRegistry[]> GetRegistriesToSyncWith();
    Task Save(TEntity entity);
    Task Delete(TId id);
}

SyncerBase<TEntity, TId> implements the bookkeeping: its Save marks the entity NotSynced in every registered ImASyncRegistry, and Delete marks it DeletedAndNotSynced. You supply the loading and ID parts:

public class OrderSyncer : SyncerBase<Order, Guid>
{
    protected override Task<Order> Load(Guid id) => repository.LoadAsync(id);
    protected override Guid GetIdFor(Order entity) => entity.ID;
    protected override Guid ParseId(string entityId) => Guid.Parse(entityId);
}

A SyncNode describes the receiver (Uri plus SyncRequestRelativeUri). The core defines the registry contract; it is up to your app (or another package) to provide the implementation that remembers statuses and pushes pending entities to the node.

The receiving side

With the ASP.NET Core integration, SyncController exposes the use case at POST /api/Sync/Sync, taking an array of SyncRequest and returning an OperationResult<SyncResponse>[], one per request. For each request, SyncUseCase:

  • stamps the request's OperationContext with details of the caller (IP address, user agent, host, origin and so on, taken from the current HTTP context),
  • saves it through ImAStorageService<string, SyncRequest>,
  • appends an audit entry (see the auditing article),
  • and answers with a response that says Synced (or the not-synced status if saving failed). “Synced” here means received; processing happens afterwards.

Processing: the daemon and processors

SyncRequestProcessingDaemon polls the stored requests that are still NotSynced or DeletedAndNotSynced, and for each one asks the ImASyncRequestProcessorFactory for the first processor whose IsEligibleFor returns true. It runs every 30 seconds in release builds of the library (5 seconds in debug builds).

  • Success: the daemon audits the removal and deletes the request.
  • Failure, or no specific processor: the request is exiled. The built-in catch-all processor saves an ExiledSyncRequest (the request plus the failing result) so nothing is lost, audits it, and the request leaves the queue.

To handle your own entity, derive from SyncRequestProcessorBase<TEntity>. It is eligible for requests whose PayloadType equals the entity's type name, deserializes the JSON payload for you, and turns exceptions into failed results:

public class OrderProcessor : SyncRequestProcessorBase<Order>
{
    ImAStorageService<Guid, Order> orders;

    public override void ReferDependencies(ImADependencyProvider dependencyProvider)
    {
        base.ReferDependencies(dependencyProvider);
        orders = dependencyProvider.Get<ImAStorageService<Guid, Order>>();
    }

    protected override Task<OperationResult> ProcessPayload(Order payload, SyncRequest syncRequest)
        => orders.Save(payload);
}

deps.Register<OrderProcessor>(() => new OrderProcessor());

For deleted entities (DeletedAndNotSynced) the base class passes the payload through even if it is empty (you may get default), so check syncRequest.SyncStatus when deleting. For any other request, an empty or unparseable payload is a failure and the request is exiled. The Runtime ships processors of its own for ConsumerIdentity and LogEntry payloads.

Processors must be registered in the dependency registry: the factory discovers processor types in your assemblies and resolves each one from the registry.

Starting the daemon

H.Necessaire.Runtime.Integration.DotNet provides SyncRequestProcessingHostedServiceDaemon, an IHostedService wrapper. Register it, and with the ASP.NET Core integration the host starts and stops it for you (registered hosted services are forwarded to the host):

registry.Register<SyncRequestProcessingHostedServiceDaemon>(() => new SyncRequestProcessingHostedServiceDaemon());

Outside a host, resolve SyncRequestProcessingDaemon and call Start() yourself.

What you need registered

  • RuntimeDependencyGroup (it registers the sync use case, daemon and processor factory),
  • storage for SyncRequest and ExiledSyncRequest and an ImAnAuditingService (the Runtime includes file-system defaults; the database providers supply their own),
  • your processors.