Technical Reference

SDK guide 4: Acting on a partner's notification from your business application

Step by step, with C# code: listen for the notifications a partner sends, ask the partner's API for what changed, apply the answer in your own context, and deal with repeats, retries and dead letters.

This is the third job: a trading partner tells Archr.Hermod that something has changed, and your application asks the partner's papiNet API for it. Archr.Hermod receives the notification and puts it on a message-queue topic; your application makes the call itself, in its own context, and applies the answer in the same place. Why it is built that way is in Notifications: thin events with CloudEvents. This guide is the application's side, step by step. Read guide 1 for the messages and guide 3 for calling a partner, which this uses.

The notification adapter is in the C# SDK, and uses Kafka. Java, TypeScript and Python do not have it yet; any language can do the job from the messages alone, see step 9.

1. Set up the receiver in Archr.Hermod

Notifications are off until an administrator switches them on (Programmability > Settings). In Programmability > CloudEvents add a receiver for the partner: the topic its events are put on (the one your application will read), the senders and event types it accepts, and a key for the partner (shown once). Give the partner the address of the receiver and the key. The send button on the receiver's row puts a test notification on its topic, so you can see it arrive before the partner sends one.

2. Add the SDK

Nothing new: Hermod.PapiNet.HostAdapter holds the notification adapter beside the adapter and the client (see guide 2 and 3 for adding it and for .NET Framework). You need a PapinetClient too, because the handler uses it to ask the partner's API.

3. Listen to the topic

C#
public static PapinetNotificationAdapter ListenForNotifications(KafkaPapinetSettings kafka, PapinetClient client, IDeliveryNoteStore notes, IPapinetLog log)
{
    var options = new PapinetNotificationAdapterOptions
    {
        DefaultPartner = "BAFOR",                   // the API partner these notifications are about, as named in Archr.Hermod's API Partners
    };
    options.Topics.Add("papinet.events.in");        // the Topic of the receiver in Archr.Hermod's Admin pages (Programmability > CloudEvents)

    var notifications = PapinetNotificationAdapter.ForKafka(kafka, client, options, log);
    notifications.On("com.example.delivery-note.*", (n, ct) => HandleDeliveryNote(n, notes, ct));
    notifications.Start();                          // returns at once; listening happens in the background
    return notifications;                           // await notifications.StopAsync() when the application stops
}

4. Write a handler

C#
public static async Task<NotificationResult> HandleDeliveryNote(Notification n, IDeliveryNoteStore notes, CancellationToken ct)
{
    // A thin event says what changed (here the subject is the delivery note's id); the data is asked for.
    var call = await n.Call(Operations.GetLogisticsDeliveryNotesLogisticsDeliveryNoteId)
        .PathParameter("logisticsDeliveryNoteId", n.Event.Subject)
        .IdempotencyKey(n.Event.Id)                 // the partner can tell a repeat from a new call
        .ExecuteAsync<LogisticsDeliveryNoteById>(ct);

    if (!call.Succeeded) return n.Failed(call);     // tried again if it may work next time, set aside if it never will

    notes.Apply(call.Body);                         // the answer is applied here, in the application's own context
    return n.Done();
}

The handler gets a Notification: the event, the API partner, and Call, which is the client of guide 3 already pointed at that partner. What the event says (here, the subject is the id of the delivery note) is mapped to a call by your code, and the answer is applied by your code, so the handler can use everything your application knows: what it already has, which company the data belongs to, how far it has got. A handler that changes data must be safe to run twice (see step 7); giving the call the event's id as IdempotencyKey lets the partner tell a repeat from a new request.

5. Read the event

C#
public static string Describe(Notification n)
{
    var e = n.Event;
    var text = e.Type                               // what happened, in the words you and the partner agreed
        + " about " + e.Subject                     // what it happened to
        + " at " + e.Time                           // when the partner says it happened (a DateTimeOffset?)
        + ", let in by " + e.Receiver               // the receiver in Archr.Hermod that accepted it: written by Archr.Hermod, not by the sender
        + " for partner " + n.Partner;
    if (e.HasData) text += ": " + e.DataText;       // a thin event has no data; otherwise e.DataJson and e.ReadData<T>() read it
    if (e.DataRef != null) text += " (data at " + e.DataRef + ")";
    return text;
}

Notifications arrive as CloudEvents. The data, if the sender put any in, is there as it arrived (DataText, DataJson, ReadData<T>()); a thin event has none, and that is the usual case. Binary and structured CloudEvents are both read.

6. Say what becomes of it

C#
public static NotificationResult Decide(Notification n)
{
    if (!Guid.TryParse(n.Event.Subject, out _))
        return n.Park("The subject is not a delivery note id: " + n.Event.Subject);   // can never work: set aside, with the reason, for a person

    if (n.Event.Type.EndsWith(".deleted", StringComparison.Ordinal))
        return n.Skip("A deletion is not acted on.");                                   // nothing to do: acknowledged and remembered

    if (n.Attempt == 1)
        return n.RetryLater("Apollo is closing the period.", TimeSpan.FromSeconds(30)); // call the handler again after this long

    return n.Done();
}
The handler returnsWhat the adapter does
n.Done()The event is dealt with: it is acknowledged on the topic and remembered, so a second delivery of it is not handled.
n.Skip(reason)Nothing to do for it. The same as done, with the reason in the log.
n.RetryLater(reason, delay)Call the handler again after the delay (the adapter's own growing wait if none is given), up to the attempt limit (3 by default); then the event is parked.
n.Park(reason)It cannot work as it is: put it on the dead-letter topic with the reason, for a person to look at.
n.Failed(call)For a call that did not succeed: retry what may work next time, park what never will. Retried: Archr.Hermod could not reach the partner or it did not answer in time, or the partner answered 404 (its own data may not be there yet), 408, 425, 429 or 5xx. Parked: Archr.Hermod refused the call (an unknown or switched-off partner, an operation that is not permitted), any other 4xx, and an answer that does not match what papiNet describes.
throwsTreated as a retry. A handler that runs longer than two minutes is cancelled, and that counts as a failed attempt.

7. Repeats, retries and dead letters

C#
// Remembers the events dealt with in Apollo's own database, so that a repeat after a restart is not handled again.
public sealed class DatabaseDeduplicator : INotificationDeduplicator
{
    private readonly IEventLedger ledger;

    public DatabaseDeduplicator(IEventLedger ledger) => this.ledger = ledger;

    // False when the key is there already: the event was dealt with, or is being handled now. (A claim that a crashed process left behind has to expire, or the event is never handled.)
    public Task<bool> TryClaimAsync(string key, CancellationToken ct) => ledger.TryInsertAsync(key, ct);

    public Task CompleteAsync(string key, CancellationToken ct) => ledger.MarkDoneAsync(key, ct);

    // It was not dealt with (parked, or the application is stopping): it can be claimed again.
    public Task ReleaseAsync(string key, CancellationToken ct) => ledger.DeleteAsync(key, ct);
}

8. Watch it, and try it

C#
public static void Watch(PapinetNotificationAdapter notifications, IPapinetLog log)
{
    // For the application's own log and metrics: what became of each message.
    notifications.Handled += info =>
        log.Write(PapinetLogLevel.Information, info.Outcome + " " + info.Event + " after " + info.Attempts + " attempt(s)" + (info.Reason == null ? string.Empty : ": " + info.Reason));

    // For a health page.
    var status = notifications.GetStatus();
    log.Write(PapinetLogLevel.Information, status.State + ": " + status.Done + " done, " + status.Duplicates + " repeats, " + status.Retried + " retries, " + status.Parked + " parked");
}

Handled is raised for each message with what became of it (Done, Skipped, Duplicate, Test, Unhandled, Parked or Invalid), for your log and your metrics; GetStatus has the counters for a health page.

Without a broker, a unit test builds the adapter on a stand-in transport and feeds it the message Archr.Hermod's receiver would put on the topic. The SDK has TestEvents (the messages), FakeOutboundHub (the partner's answers, one after another if you want the first call to fail) and FakeNotificationTransport (it keeps the dead letters):

C#
public static async Task<string> TestTheHandler(IDeliveryNoteStore notes, string noteId)
{
    // The partner's answer is stood in for, and no broker is needed.
    var hub = new FakeOutboundHub().Delivered(Operations.GetLogisticsDeliveryNotesLogisticsDeliveryNoteId, 200, new LogisticsDeliveryNoteById { Number = "LDN12345" });
    var options = new PapinetNotificationAdapterOptions { DefaultPartner = "BAFOR" };
    options.Topics.Add("papinet.events.in");

    using (var adapter = new PapinetNotificationAdapter(new FakeNotificationTransport(), new PapinetClient(hub), options))
    {
        adapter.On("com.example.delivery-note.*", (n, ct) => HandleDeliveryNote(n, notes, ct));

        // The message Archr.Hermod's receiver would put on the topic.
        await adapter.HandleAsync(TestEvents.Binary("papinet.events.in", "com.example.delivery-note.updated", subject: noteId), CancellationToken.None);
    }

    // What the handler asked of the partner, to check against what the event said: the partner, the operation and the document.
    var asked = hub.Requests.Single();
    return asked.Partner + " " + asked.Operation + " " + asked.PathParameters["logisticsDeliveryNoteId"];
}

End to end, the send button of step 1 puts a test notification on the topic. The adapter recognises it, logs that the queue and the adapter work, and does not give it to a handler (set HandleTestEvents to hear it in a handler too). The sample application in the SDK pack, examples/NotificationSample.cs, is a complete .NET Framework 4.8 application that does all of this: Hermod.PapiNet.HostAdapter.Sample.exe notify <brokers> <topic> <partner>.

9. From another language

The notification is an ordinary Kafka message, so a consumer in any language can read it. Archr.Hermod puts each event on the receiver's topic in the CloudEvents binary form: the data, if there is any, is the message body, and the attributes are headers.

The headers of a notification on Kafka
ce_specversion: 1.0
ce_id: 7c1e0b5a-3f0c-4d2a-9d55-2b7f6a1e9c10
ce_source: https://partner.example.com/events
ce_type: com.example.delivery-note.updated
ce_subject: fc190dd0-d239-40db-8196-ea72ae5b4841
ce_time: 2026-11-20T09:15:00.000Z
ce_hermodreceiver: bafor-events

What to know

← Back to the technical reference