Skip to content
Closed
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
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,23 @@ For runnable DTS emulator examples that demonstrate versioning, see the [WorkerV

The [on-demand sandbox activities sample](samples/on-demand-sandbox/README.md) shows how to declare selected activities for Durable Task Scheduler (DTS)-managed on-demand sandbox execution and build the remote worker container image separately from the declarer app.

### gRPC send limit

The DTS .NET client and worker reject outgoing gRPC messages larger than 4 MiB
(4,194,304 bytes) locally. The limit applies to each serialized message, not
to the total size of a stream. To change the limit, set `MaxSendMessageSize` in
the `UseDurableTaskScheduler` options callback for the client or worker:

```csharp
builder.UseDurableTaskScheduler(connectionString,
options => options.MaxSendMessageSize = 2 * 1024 * 1024);
```

Use a positive byte count, or set `MaxSendMessageSize` to `null` to restore the
previous behavior of sending without an SDK cap. Raising or disabling the cap
does not change the scheduler's limits, including the 3.9 MiB limit for work-item
completion requests.
Comment on lines +217 to +218

### Blob auto-purge infrastructure integration

The optional service contract is maintained in
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ public void Configure(string? name, GrpcDurableTaskClientOptions options)
string retryOptionsKey = source.RetryOptions != null
? $"{source.RetryOptions.MaxRetries}|{source.RetryOptions.InitialBackoffMs}|{source.RetryOptions.MaxBackoffMs}|{source.RetryOptions.BackoffMultiplier}|{(source.RetryOptions.RetryableStatusCodes != null ? string.Join(",", source.RetryOptions.RetryableStatusCodes) : string.Empty)}"
: "null";
string cacheKey = $"{optionsName}\u001F{source.EndpointAddress}\u001F{source.TaskHubName}\u001F{source.ResourceId}\u001F{credentialType}\u001F{source.AllowInsecureCredentials}\u001F{retryOptionsKey}";
string cacheKey = $"{optionsName}\u001F{source.EndpointAddress}\u001F{source.TaskHubName}\u001F{source.ResourceId}\u001F{credentialType}\u001F{source.AllowInsecureCredentials}\u001F{retryOptionsKey}\u001F{source.MaxSendMessageSize}";
options.Channel = this.channels.GetOrAdd(
cacheKey,
_ => new Lazy<GrpcChannel>(source.CreateChannel, LazyThreadSafetyMode.PublicationOnly)).Value;
Expand Down
11 changes: 11 additions & 0 deletions src/Client/AzureManaged/DurableTaskSchedulerClientOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,16 @@ public string ResourceId
/// </summary>
public bool AllowInsecureCredentials { get; set; }

/// <summary>
/// Gets or sets the maximum size, in bytes, of each outgoing gRPC message. Defaults to 4 MiB (4,194,304 bytes).
/// </summary>
/// <remarks>
/// Set to a positive value or <see langword="null"/> to disable the SDK send limit.
/// This setting does not change the scheduler's limits.
/// </remarks>
[Range(1, int.MaxValue)]
public int? MaxSendMessageSize { get; set; } = GrpcMessageSizeDefaults.MaxSendMessageSize;

/// <summary>
/// Gets or sets the options that determine how and when calls made to the scheduler will be retried.
/// </summary>
Expand Down Expand Up @@ -205,6 +215,7 @@ this.Credential is not null
Credentials = ChannelCredentials.Create(channelCreds, managedBackendCreds),
UnsafeUseInsecureChannelCallCredentials = this.AllowInsecureCredentials,
ServiceConfig = serviceConfig,
MaxSendMessageSize = this.MaxSendMessageSize,
});
}

Expand Down
15 changes: 15 additions & 0 deletions src/Shared/AzureManaged/GrpcMessageSizeDefaults.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

namespace Microsoft.DurableTask;

/// <summary>
/// Default gRPC message size limits for Durable Task Scheduler channels.
/// </summary>
internal static class GrpcMessageSizeDefaults
{
/// <summary>
/// The maximum outgoing message size in bytes, matching the scheduler's default receive limit.
/// </summary>
public const int MaxSendMessageSize = 4 * 1024 * 1024;
}
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ public void Configure(string? name, GrpcDurableTaskWorkerOptions options)
// but separate channels are created when any relevant property changes.
// Use a delimiter character (\u001F) that will not appear in typical endpoint URIs.
string credentialType = source.Credential?.GetType().FullName ?? "null";
string cacheKey = $"{optionsName}\u001F{source.EndpointAddress}\u001F{source.TaskHubName}\u001F{source.ResourceId}\u001F{credentialType}\u001F{source.AllowInsecureCredentials}\u001F{source.WorkerId}";
string cacheKey = $"{optionsName}\u001F{source.EndpointAddress}\u001F{source.TaskHubName}\u001F{source.ResourceId}\u001F{credentialType}\u001F{source.AllowInsecureCredentials}\u001F{source.WorkerId}\u001F{source.MaxSendMessageSize}";
GrpcChannel? newChannel = null;
bool disposeNewChannel = false;
lock (this.syncRoot)
Expand Down
11 changes: 11 additions & 0 deletions src/Worker/AzureManaged/DurableTaskSchedulerWorkerOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,16 @@ public string ResourceId
/// </summary>
public bool AllowInsecureCredentials { get; set; }

/// <summary>
/// Gets or sets the maximum size, in bytes, of each outgoing gRPC message. Defaults to 4 MiB (4,194,304 bytes).
/// </summary>
/// <remarks>
/// Set to a positive value or <see langword="null"/> to disable the SDK send limit.
/// This setting does not change the scheduler's limits.
/// </remarks>
[Range(1, int.MaxValue)]
public int? MaxSendMessageSize { get; set; } = GrpcMessageSizeDefaults.MaxSendMessageSize;

/// <summary>
/// Creates a new instance of <see cref="DurableTaskSchedulerWorkerOptions"/> from a connection string.
/// </summary>
Expand Down Expand Up @@ -155,6 +165,7 @@ this.Credential is not null
Credentials = ChannelCredentials.Create(channelCreds, managedBackendCreds),
UnsafeUseInsecureChannelCallCredentials = this.AllowInsecureCredentials,
ServiceConfig = GrpcRetryPolicyDefaults.DefaultServiceConfig,
MaxSendMessageSize = this.MaxSendMessageSize,
});
}

Expand Down
171 changes: 171 additions & 0 deletions test/Grpc.IntegrationTests/DtsGrpcSendLimitTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System.Net;
using Grpc.Core;
using Grpc.Net.Client;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.DurableTask.Client;
using Microsoft.DurableTask.Client.AzureManaged;
using Microsoft.DurableTask.Client.Grpc;
using Microsoft.DurableTask.Worker;
using Microsoft.DurableTask.Worker.AzureManaged;
using Microsoft.DurableTask.Worker.Grpc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using P = Microsoft.DurableTask.Protobuf;

namespace Microsoft.DurableTask.Grpc.Tests;

/// <summary>
/// Verifies outgoing message size limits on Durable Task Scheduler channels.
/// </summary>
public class DtsGrpcSendLimitTests
{
const int DefaultLimit = 4 * 1024 * 1024;
const int RaisedLimit = 5 * 1024 * 1024;

/// <summary>
/// Verifies the exact size boundary and applies an override to the same named scheduler.
/// </summary>
[Theory]
[InlineData(false, RaisedLimit)]
[InlineData(true, RaisedLimit)]
[InlineData(false, null)]
[InlineData(true, null)]
public async Task DtsChannel_EnforcesDefaultAndHonorsOverrideAsync(bool useWorker, int? overrideLimit)
{
// Arrange
using CancellationTokenSource timeout = new(TimeSpan.FromSeconds(30));
using IHost host = Host.CreateDefaultBuilder()
.ConfigureLogging(logging => logging.ClearProviders())
.ConfigureWebHostDefaults(web => web
.UseKestrel(options => options.Listen(IPAddress.Loopback, 0, endpoint => endpoint.Protocols = HttpProtocols.Http2))
.ConfigureServices(services =>
{
services.AddGrpc(options => options.MaxReceiveMessageSize = RaisedLimit + 1);
services.AddSingleton<CountingSidecar>();
})
.Configure(app =>
{
app.UseRouting();
app.UseEndpoints(endpoints => endpoints.MapGrpcService<CountingSidecar>());
}))
.Build();
await host.StartAsync(timeout.Token);
CountingSidecar sidecar = host.Services.GetRequiredService<CountingSidecar>();
string endpoint = Assert.Single(host.Services.GetRequiredService<IServer>()
.Features.Get<IServerAddressesFeature>()!.Addresses);

ServiceCollection services = new();
bool useOverride = false;
RegisterScheduler(services, useWorker, endpoint, currentLimit => useOverride ? overrideLimit : currentLimit);
await using ServiceProvider provider = services.BuildServiceProvider();
GrpcChannel initialChannel = GetChannel(provider, useWorker);
P.TaskHubSidecarService.TaskHubSidecarServiceClient initialClient = new(initialChannel);

// Act and assert
await initialClient.RaiseEventAsync(CreateRequest(DefaultLimit), cancellationToken: timeout.Token);
RpcException error = await Assert.ThrowsAsync<RpcException>(
async () => await initialClient.RaiseEventAsync(CreateRequest(DefaultLimit + 1), cancellationToken: timeout.Token));
Assert.Equal(StatusCode.ResourceExhausted, error.StatusCode);
Assert.Equal(1, sidecar.Received);

// Rebuild the scheduler options for the same name so only the send limit changes the channel cache key.
useOverride = true;
Assert.True(useWorker
? provider.GetRequiredService<IOptionsMonitorCache<DurableTaskSchedulerWorkerOptions>>().TryRemove(Options.DefaultName)
: provider.GetRequiredService<IOptionsMonitorCache<DurableTaskSchedulerClientOptions>>().TryRemove(Options.DefaultName));

GrpcChannel updatedChannel = GetChannel(provider, useWorker);
Assert.NotSame(initialChannel, updatedChannel);
Assert.Same(updatedChannel, GetChannel(provider, useWorker));
P.TaskHubSidecarService.TaskHubSidecarServiceClient updatedClient = new(updatedChannel);
await updatedClient.RaiseEventAsync(CreateRequest(RaisedLimit), cancellationToken: timeout.Token);
if (overrideLimit.HasValue)
{
error = await Assert.ThrowsAsync<RpcException>(
async () => await updatedClient.RaiseEventAsync(CreateRequest(RaisedLimit + 1), cancellationToken: timeout.Token));
Assert.Equal(StatusCode.ResourceExhausted, error.StatusCode);
Assert.Equal(2, sidecar.Received);
}
else
{
await updatedClient.RaiseEventAsync(CreateRequest(RaisedLimit + 1), cancellationToken: timeout.Token);
Assert.Equal(3, sidecar.Received);
}

await host.StopAsync(timeout.Token);
}

/// <summary>
/// Verifies that options validation rejects invalid limits.
/// </summary>
[Theory]
[InlineData(false, 0)]
[InlineData(false, -1)]
[InlineData(true, 0)]
[InlineData(true, -1)]
public async Task DtsChannel_RejectsNonpositiveLimitAsync(bool useWorker, int limit)
{
// Arrange
ServiceCollection services = new();
RegisterScheduler(services, useWorker, "http://localhost", _ => limit);
await using ServiceProvider provider = services.BuildServiceProvider();

// Act and assert
OptionsValidationException error = Assert.Throws<OptionsValidationException>(() => GetChannel(provider, useWorker));
Assert.Contains("MaxSendMessageSize", error.Message);
}

static void RegisterScheduler(ServiceCollection services, bool useWorker, string endpoint, Func<int?, int?> configureLimit)
{
string connectionString = $"Endpoint={endpoint};TaskHub=test;Authentication=None";
if (useWorker)
{
services.AddDurableTaskWorker(builder => builder.UseDurableTaskScheduler(connectionString, options =>
{
options.WorkerId = "test";
options.MaxSendMessageSize = configureLimit(options.MaxSendMessageSize);
}));
}
else
{
services.AddDurableTaskClient(builder => builder.UseDurableTaskScheduler(connectionString,
options => options.MaxSendMessageSize = configureLimit(options.MaxSendMessageSize)));
}
}

static GrpcChannel GetChannel(IServiceProvider provider, bool useWorker) => useWorker
? provider.GetRequiredService<IOptionsFactory<GrpcDurableTaskWorkerOptions>>().Create(Options.DefaultName).Channel!
: provider.GetRequiredService<IOptionsFactory<GrpcDurableTaskClientOptions>>().Create(Options.DefaultName).Channel!;

static P.RaiseEventRequest CreateRequest(int size)
{
P.RaiseEventRequest request = new() { InstanceId = "test", Name = "event", Input = new string('x', size) };
int overhead = request.CalculateSize() - size;
request.Input = request.Input[..(size - overhead)];
Assert.Equal(size, request.CalculateSize());
return request;
}

sealed class CountingSidecar : P.TaskHubSidecarService.TaskHubSidecarServiceBase
{
int received;

public int Received => Volatile.Read(ref this.received);

/// <inheritdoc />
public override Task<P.RaiseEventResponse> RaiseEvent(P.RaiseEventRequest request, ServerCallContext context)
{
Interlocked.Increment(ref this.received);
return Task.FromResult(new P.RaiseEventResponse());
}
}
}
Loading