diff --git a/README.md b/README.md index 9941a8c4..85abb034 100644 --- a/README.md +++ b/README.md @@ -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. + ### Blob auto-purge infrastructure integration The optional service contract is maintained in diff --git a/src/Client/AzureManaged/DurableTaskSchedulerClientExtensions.cs b/src/Client/AzureManaged/DurableTaskSchedulerClientExtensions.cs index bbb3a63d..4a88ad78 100644 --- a/src/Client/AzureManaged/DurableTaskSchedulerClientExtensions.cs +++ b/src/Client/AzureManaged/DurableTaskSchedulerClientExtensions.cs @@ -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(source.CreateChannel, LazyThreadSafetyMode.PublicationOnly)).Value; diff --git a/src/Client/AzureManaged/DurableTaskSchedulerClientOptions.cs b/src/Client/AzureManaged/DurableTaskSchedulerClientOptions.cs index 623bdc67..9a3f2311 100644 --- a/src/Client/AzureManaged/DurableTaskSchedulerClientOptions.cs +++ b/src/Client/AzureManaged/DurableTaskSchedulerClientOptions.cs @@ -64,6 +64,16 @@ public string ResourceId /// public bool AllowInsecureCredentials { get; set; } + /// + /// Gets or sets the maximum size, in bytes, of each outgoing gRPC message. Defaults to 4 MiB (4,194,304 bytes). + /// + /// + /// Set to a positive value or to disable the SDK send limit. + /// This setting does not change the scheduler's limits. + /// + [Range(1, int.MaxValue)] + public int? MaxSendMessageSize { get; set; } = GrpcMessageSizeDefaults.MaxSendMessageSize; + /// /// Gets or sets the options that determine how and when calls made to the scheduler will be retried. /// @@ -205,6 +215,7 @@ this.Credential is not null Credentials = ChannelCredentials.Create(channelCreds, managedBackendCreds), UnsafeUseInsecureChannelCallCredentials = this.AllowInsecureCredentials, ServiceConfig = serviceConfig, + MaxSendMessageSize = this.MaxSendMessageSize, }); } diff --git a/src/Shared/AzureManaged/GrpcMessageSizeDefaults.cs b/src/Shared/AzureManaged/GrpcMessageSizeDefaults.cs new file mode 100644 index 00000000..e451b49f --- /dev/null +++ b/src/Shared/AzureManaged/GrpcMessageSizeDefaults.cs @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.DurableTask; + +/// +/// Default gRPC message size limits for Durable Task Scheduler channels. +/// +internal static class GrpcMessageSizeDefaults +{ + /// + /// The maximum outgoing message size in bytes, matching the scheduler's default receive limit. + /// + public const int MaxSendMessageSize = 4 * 1024 * 1024; +} diff --git a/src/Worker/AzureManaged/DurableTaskSchedulerWorkerExtensions.cs b/src/Worker/AzureManaged/DurableTaskSchedulerWorkerExtensions.cs index 9376979d..7ade4b7e 100644 --- a/src/Worker/AzureManaged/DurableTaskSchedulerWorkerExtensions.cs +++ b/src/Worker/AzureManaged/DurableTaskSchedulerWorkerExtensions.cs @@ -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) diff --git a/src/Worker/AzureManaged/DurableTaskSchedulerWorkerOptions.cs b/src/Worker/AzureManaged/DurableTaskSchedulerWorkerOptions.cs index 3285624c..44bc623b 100644 --- a/src/Worker/AzureManaged/DurableTaskSchedulerWorkerOptions.cs +++ b/src/Worker/AzureManaged/DurableTaskSchedulerWorkerOptions.cs @@ -70,6 +70,16 @@ public string ResourceId /// public bool AllowInsecureCredentials { get; set; } + /// + /// Gets or sets the maximum size, in bytes, of each outgoing gRPC message. Defaults to 4 MiB (4,194,304 bytes). + /// + /// + /// Set to a positive value or to disable the SDK send limit. + /// This setting does not change the scheduler's limits. + /// + [Range(1, int.MaxValue)] + public int? MaxSendMessageSize { get; set; } = GrpcMessageSizeDefaults.MaxSendMessageSize; + /// /// Creates a new instance of from a connection string. /// @@ -155,6 +165,7 @@ this.Credential is not null Credentials = ChannelCredentials.Create(channelCreds, managedBackendCreds), UnsafeUseInsecureChannelCallCredentials = this.AllowInsecureCredentials, ServiceConfig = GrpcRetryPolicyDefaults.DefaultServiceConfig, + MaxSendMessageSize = this.MaxSendMessageSize, }); } diff --git a/test/Grpc.IntegrationTests/DtsGrpcSendLimitTests.cs b/test/Grpc.IntegrationTests/DtsGrpcSendLimitTests.cs new file mode 100644 index 00000000..984c414c --- /dev/null +++ b/test/Grpc.IntegrationTests/DtsGrpcSendLimitTests.cs @@ -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; + +/// +/// Verifies outgoing message size limits on Durable Task Scheduler channels. +/// +public class DtsGrpcSendLimitTests +{ + const int DefaultLimit = 4 * 1024 * 1024; + const int RaisedLimit = 5 * 1024 * 1024; + + /// + /// Verifies the exact size boundary and applies an override to the same named scheduler. + /// + [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(); + }) + .Configure(app => + { + app.UseRouting(); + app.UseEndpoints(endpoints => endpoints.MapGrpcService()); + })) + .Build(); + await host.StartAsync(timeout.Token); + CountingSidecar sidecar = host.Services.GetRequiredService(); + string endpoint = Assert.Single(host.Services.GetRequiredService() + .Features.Get()!.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( + 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>().TryRemove(Options.DefaultName) + : provider.GetRequiredService>().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( + 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); + } + + /// + /// Verifies that options validation rejects invalid limits. + /// + [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(() => GetChannel(provider, useWorker)); + Assert.Contains("MaxSendMessageSize", error.Message); + } + + static void RegisterScheduler(ServiceCollection services, bool useWorker, string endpoint, Func 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>().Create(Options.DefaultName).Channel! + : provider.GetRequiredService>().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); + + /// + public override Task RaiseEvent(P.RaiseEventRequest request, ServerCallContext context) + { + Interlocked.Increment(ref this.received); + return Task.FromResult(new P.RaiseEventResponse()); + } + } +}