Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions benchmarks/Relayer.Benchmarks/NativeSendBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using BenchmarkDotNet.Attributes;

namespace Relayer.Benchmarks;

/// <summary>Compares a preconfigured native send callback with direct native callback invocation.</summary>
[MemoryDiagnoser]
public class NativeSendBenchmarks
{
private readonly NativeOutgoing _native = new();
private Action<NativeOutgoing> _configure = null!;
private OutgoingMessage _outgoing;

[GlobalSetup]
public void Setup()
{
_configure = static native => native.Value = 42;
var options = new SendOptions().ConfigureNative(_configure);
_outgoing = new OutgoingMessage("orders", ReadOnlyMemory<byte>.Empty, options: options);
}

[Benchmark(Baseline = true)]
public int NativeCallback()
{
_configure(_native);
return _native.Value;
}

[Benchmark]
public int OutgoingNativeCallback()
{
_outgoing.ApplyNative(_native);
return _native.Value;
}

public sealed class NativeOutgoing
{
public int Value { get; set; }
}
}
27 changes: 27 additions & 0 deletions docs/sending.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Send transport contract

`ITransport.SendAsync(OutgoingMessage, CancellationToken)` and `SendBatchAsync(ReadOnlyMemory<OutgoingMessage>, CancellationToken)` are the common native send seam. Routing chooses the named transport before invoking these methods. The same shape serves direct sends, outbox dispatch, scheduled copies, and dead-letter copies. Transport adapters preserve native delivery, ordering, and batching semantics; batch completion does not promise atomic delivery.

The core serializes the body and resolves headers, ordering, and scheduling before invoking a transport. `OutgoingMessage.Headers` is borrowed memory containing named `WireString` values. It includes the stable CloudEvents attributes and creation context written using the [envelope primitives](envelopes.md). Each name is already mapped to the selected transport's binary-mode binding. An adapter maps those values to its native header/property representation without rebuilding the envelope or changing the original creation context.

```csharp
// Body and headers are already serialized/resolved by the core.
var outgoing = new OutgoingMessage(
destination: "orders.placed",
body: body,
headers: headers,
orderingKey: customerId,
deliverAt: scheduledTime,
options: sendOptions);
await transport.SendAsync(outgoing, cancellationToken);
```

The body, header entries, header value buffers, batch array, and native options must remain alive and unchanged until the send completes, including faulted or cancelled completion. A transport must finish using that memory before completion; it cannot return early while a native operation still uses the buffers. The caller can then return pooled storage. An outbox copies the body and headers into durable storage before enlistment completes; dispatch reconstructs the same send shape from the persisted fields. The transport name belongs to routing/outbox storage rather than the message passed to an already selected transport.

`options` carries only the native callbacks at this seam. The caller has already resolved `SendOptions.Headers`, `OrderingKey`, and `DeliverAt` into the other arguments. Options are borrowed, so callers must not mutate them during a send.

A transport constructs its outgoing native object, maps body/headers/ordering/scheduling, then calls `outgoing.ApplyNative(native)` immediately before handing it to the native client. `ApplyNative<TNative>` uses the transport's declared native outgoing type. Callbacks accepting that type or a base type run in registration order. An incompatible callback throws an actionable error instead of being dropped. Callbacks are stored directly, without wrapping closures, reflection, or dynamic invocation.

Before persisting or enlisting a message, outbox integrations call `outgoing.ValidateForOutbox()`. A send containing native callbacks fails because delegates cannot be persisted; portable headers, ordering, and scheduling remain available. Detecting an active transaction and choosing enlistment instead of direct sending belongs to the scoped sender/outbox integration.

This contract does not implement routing, serialization, outbox storage, timeout policy, or native transport adapters. Those components build on this seam. Adapters must observe the cancellation token supplied by the caller.
70 changes: 70 additions & 0 deletions src/Relayer/Sending/OutgoingMessage.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
namespace Relayer;

/// <summary>A serialized send shared by direct sends, outbox dispatch, scheduled copies, and dead-letter copies.</summary>
/// <remarks>
/// Body, header entries, header value memory, and native options are borrowed. The caller must keep them alive
/// and unchanged until the transport's send completes, including faulted or cancelled completion. A transport
/// must not retain them after completion. An outbox must copy body and headers into durable storage before
/// enlistment completes. Headers include the original CloudEvents attributes and creation context; dispatch
/// must preserve them rather than generating another identity or capturing the dispatcher's trace context.
/// </remarks>
public readonly struct OutgoingMessage
{
private readonly SendOptions? _options;

/// <summary>Creates a send without copying its body, headers, or native options.</summary>
/// <param name="destination">The native destination on the selected named transport.</param>
/// <param name="body">The serialized body.</param>
/// <param name="headers">Resolved native header names and values, including envelope attributes.</param>
/// <param name="orderingKey">The resolved native ordering key, or null for an unordered send.</param>
/// <param name="deliverAt">The resolved earliest delivery time, or null for immediate delivery.</param>
/// <param name="options">
/// Native callbacks only. Portable headers, ordering, and scheduling must already be resolved into the other arguments.
/// </param>
public OutgoingMessage(string destination, ReadOnlyMemory<byte> body,
ReadOnlyMemory<KeyValuePair<string, WireString>> headers = default,
string? orderingKey = null, DateTimeOffset? deliverAt = null, SendOptions? options = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(destination);
Destination = destination;
Body = body;
Headers = headers;
OrderingKey = orderingKey;
DeliverAt = deliverAt;
_options = options;
}

/// <summary>The native destination on the selected named transport.</summary>
public string Destination { get; }

/// <summary>The serialized body, borrowed until send completion.</summary>
public ReadOnlyMemory<byte> Body { get; }

/// <summary>Resolved native header names and values, borrowed until send completion.</summary>
public ReadOnlyMemory<KeyValuePair<string, WireString>> Headers { get; }

/// <summary>The native ordering key, or null when none is specified.</summary>
public string? OrderingKey { get; }

/// <summary>The earliest delivery time, or null for immediate delivery.</summary>
public DateTimeOffset? DeliverAt { get; }

/// <summary>Applies callbacks to the native outgoing object immediately before sending.</summary>
public void ApplyNative<TNative>(TNative nativeMessage) where TNative : class
{
ArgumentNullException.ThrowIfNull(nativeMessage);
_options?.ApplyNative(nativeMessage);
}

/// <summary>Rejects non-persistable native callbacks. Call before enlisting this message in an outbox.</summary>
/// <exception cref="InvalidOperationException">Native callbacks cannot be persisted.</exception>
public void ValidateForOutbox()
{
if (_options is { HasNativeConfigurators: true })
{
throw new InvalidOperationException(
"Native configurators cannot be persisted in the outbox. " +
"Use portable headers, ordering, or scheduling options, or send outside the active outbox transaction.");
}
}
}
32 changes: 17 additions & 15 deletions src/Relayer/Sending/SendOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ namespace Relayer;
/// <summary>Per-send options.</summary>
public sealed class SendOptions
{
private List<Action<object>>? _nativeConfigurators;
private List<Delegate>? _nativeConfigurators;

/// <summary>Additional headers to write to the native message.</summary>
public Dictionary<string, string> Headers { get; } = [];
Expand All @@ -14,29 +14,24 @@ public sealed class SendOptions
/// <summary>Overrides the route's ordering key (Kafka key, ASB session ID, SQS message group ID).</summary>
public string? OrderingKey { get; set; }

/// <summary>Whether this send contains native callbacks, which cannot be persisted in an outbox.</summary>
public bool HasNativeConfigurators => _nativeConfigurators is { Count: > 0 };

/// <summary>
/// Customises the native outgoing message just before it is handed to the client.
/// The send fails if the route's native outgoing type is not <typeparamref name="TNative"/>,
/// The send fails if a callback cannot accept the route's native outgoing type,
/// rather than silently ignoring the configuration.
/// </summary>
public SendOptions ConfigureNative<TNative>(Action<TNative> configure) where TNative : class
{
ArgumentNullException.ThrowIfNull(configure);
(_nativeConfigurators ??= []).Add(native =>
{
if (native is not TNative typed)
{
throw new InvalidOperationException(
$"Native configuration expects {typeof(TNative).Name}, but the route's transport produces {native.GetType().Name}.");
}

configure(typed);
});
(_nativeConfigurators ??= []).Add(configure);
return this;
}

/// <summary>Applies native configurators. Called by transports.</summary>
public void ApplyNative(object nativeMessage)
/// <summary>Applies native callbacks in registration order. Called by transports with their native outgoing type.</summary>
/// <remarks>No wrapping closure, reflection, or dynamic invocation is used.</remarks>
public void ApplyNative<TNative>(TNative nativeMessage) where TNative : class
{
ArgumentNullException.ThrowIfNull(nativeMessage);

Expand All @@ -45,8 +40,15 @@ public void ApplyNative(object nativeMessage)
return;
}

foreach (var configure in _nativeConfigurators)
foreach (var callback in _nativeConfigurators)
{
if (callback is not Action<TNative> configure)
{
throw new InvalidOperationException(
"Native configuration does not match the route's native outgoing type. " +
"Register ConfigureNative<TNative> with a callback that accepts the transport's native outgoing type.");
}

configure(nativeMessage);
}
}
Expand Down
15 changes: 15 additions & 0 deletions src/Relayer/Transports/ITransport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,21 @@ public interface ITransport : IAsyncDisposable
/// <summary>The native capabilities of this transport.</summary>
TransportCapabilities Capabilities { get; }

/// <summary>Sends a serialized message using the native client.</summary>
/// <remarks>
/// Observe cancellation and preserve native delivery semantics. Apply the message's native callbacks immediately
/// before sending. Borrowed body, headers, and options remain valid until completion and must not be retained afterward.
/// </remarks>
ValueTask SendAsync(OutgoingMessage message, CancellationToken cancellationToken);

/// <summary>Sends a batch using the native client's batching and ordering semantics.</summary>
/// <remarks>
/// Observe cancellation. Apply each message's native callbacks before sending. The batch memory and each message's
/// borrowed storage remain valid until completion and must not be retained afterward. Completion does not imply
/// atomicity: a native batch failure or cancellation can leave some messages delivered.
/// </remarks>
ValueTask SendBatchAsync(ReadOnlyMemory<OutgoingMessage> messages, CancellationToken cancellationToken);

/// <summary>Connects and starts consumers.</summary>
Task StartAsync(CancellationToken cancellationToken);

Expand Down
2 changes: 1 addition & 1 deletion tests/Relayer.Tests/ConfigurationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public async Task Native_configuration_for_the_wrong_transport_type_throws()

await Assert.That(() => options.ApplyNative(new object()))
.Throws<InvalidOperationException>()
.WithMessageContaining(nameof(StringBuilderStandIn));
.WithMessageContaining("native outgoing type");
}

[Test]
Expand Down
148 changes: 148 additions & 0 deletions tests/Relayer.Tests/SendTransportTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
namespace Relayer.Tests;

public class SendTransportTests
{
[Test]
public async Task Applies_native_callbacks_in_registration_order_without_a_wrapper()
{
var options = new SendOptions()
.ConfigureNative<NativeMessage>(static native => native.Value = 2)
.ConfigureNative<NativeMessage>(static native => native.Value *= 3);
var native = new NativeMessage();

options.ApplyNative(native);

await Assert.That(options.HasNativeConfigurators).IsTrue();
await Assert.That(native.Value).IsEqualTo(6);
}

[Test]
public async Task Native_callback_for_a_base_type_applies_to_derived_native_messages()
{
var options = new SendOptions().ConfigureNative<NativeMessage>(static native => native.Value = 7);
var native = new DerivedNativeMessage();

options.ApplyNative(native);

await Assert.That(native.Value).IsEqualTo(7);
}

[Test]
public async Task Mismatched_native_callback_fails_instead_of_being_ignored()
{
var options = new SendOptions().ConfigureNative<NativeMessage>(static _ => { });

await Assert.That(() => options.ApplyNative(new object()))
.Throws<InvalidOperationException>()
.WithMessageContaining("native outgoing type");
}

[Test]
public async Task Null_native_message_and_callback_are_rejected()
{
var options = new SendOptions();

await Assert.That(() => options.ConfigureNative<NativeMessage>(null!)).Throws<ArgumentNullException>();
await Assert.That(() => options.ApplyNative<NativeMessage>(null!)).Throws<ArgumentNullException>();
}

[Test]
public async Task Outgoing_message_borrows_body_and_headers_and_preserves_delivery_fields()
{
byte[] body = [1, 2, 3];
KeyValuePair<string, WireString>[] headers =
[
new("ce_id", new WireString("019a3c1b-97c0-7000-8000-000000000001")),
new("ce_type", new WireString("tests.order;v=2")),
new("traceparent", new WireString("00-0123456789abcdef0123456789abcdef-0123456789abcdef-01"))
];
var deliverAt = DateTimeOffset.UtcNow.AddMinutes(5);
var outgoing = new OutgoingMessage("orders", body, headers, "customer-1", deliverAt);

await Assert.That(outgoing.Destination).IsEqualTo("orders");
await Assert.That(outgoing.Body.Equals(body.AsMemory())).IsTrue();
await Assert.That(outgoing.Headers.Equals(headers.AsMemory())).IsTrue();
await Assert.That(outgoing.OrderingKey).IsEqualTo("customer-1");
await Assert.That(outgoing.DeliverAt).IsEqualTo(deliverAt);
await Assert.That(outgoing.Headers.Span[0].Value.Text).IsEqualTo(headers[0].Value.Text);
outgoing.ValidateForOutbox();
}

[Test]
public async Task Outgoing_message_applies_native_callbacks_but_rejects_outbox_enlistment()
{
var options = new SendOptions().ConfigureNative<NativeMessage>(static native => native.Value = 42);
var outgoing = new OutgoingMessage("orders", ReadOnlyMemory<byte>.Empty, options: options);
var native = new NativeMessage();

outgoing.ApplyNative(native);

await Assert.That(native.Value).IsEqualTo(42);
await Assert.That(() => outgoing.ValidateForOutbox())
.Throws<InvalidOperationException>()
.WithMessageContaining("cannot be persisted");
}

[Test]
public async Task Portable_options_can_be_enlisted_and_empty_native_configuration_is_a_no_op()
{
var options = new SendOptions { OrderingKey = "customer-1", DeliverAt = DateTimeOffset.UtcNow };
options.Headers.Add("tenant", "tenant-1");
var outgoing = new OutgoingMessage("orders", ReadOnlyMemory<byte>.Empty, options: options);

outgoing.ValidateForOutbox();
outgoing.ApplyNative(new NativeMessage());

await Assert.That(options.HasNativeConfigurators).IsFalse();
await Assert.That(outgoing.Headers.IsEmpty).IsTrue();
}

[Test]
public async Task Empty_destination_is_rejected()
{
await Assert.That(() => new OutgoingMessage(" ", ReadOnlyMemory<byte>.Empty))
.Throws<ArgumentException>();
}

[Test]
public async Task Applying_preconfigured_native_callbacks_allocates_zero_bytes()
{
var options = new SendOptions().ConfigureNative<NativeMessage>(static native => native.Value = 42);
var outgoing = new OutgoingMessage("orders", ReadOnlyMemory<byte>.Empty, options: options);
var native = new NativeMessage();
for (var i = 0; i < 1000; i++)
{
outgoing.ApplyNative(native);
}

var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 1000; i++)
{
outgoing.ApplyNative(native);
}
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;

await Assert.That(allocated).IsEqualTo(0L);
await Assert.That(native.Value).IsEqualTo(42);
}

[Test]
public async Task Outgoing_message_without_options_applies_no_native_callback()
{
var outgoing = new OutgoingMessage("orders", ReadOnlyMemory<byte>.Empty);
var native = new NativeMessage { Value = 7 };

outgoing.ApplyNative(native);
outgoing.ValidateForOutbox();

await Assert.That(native.Value).IsEqualTo(7);
await Assert.That(() => outgoing.ApplyNative<NativeMessage>(null!)).Throws<ArgumentNullException>();
}

private class NativeMessage
{
public int Value { get; set; }
}

private sealed class DerivedNativeMessage : NativeMessage;
}
Loading