Skip to content

Support IList<ReadOnlyMemory<byte>> SocketAsyncEventArgs #49941

Open

Description

@davidfowl

Background and Motivation

Doing some profiling writing large payloads via Kestrel, about 1.2 % of the overall time is spent converting from ReadOnlySequence<byte> to a List<ArraySegment<byte>> for the eventual call to the underlying socket API that takes an array of pointers to buffers. Most of the time is spent calling into MemoryMarshal.TryGetArray to get an ArraySegment<byte> from the Memory<byte> most of which is a pointless conversion (which mostly defeats the purpose of use passing a pre-pinned memory handle to the networking stack).

Proposed API

namespace System.Net.Sockets
{
    public class SocketAsyncEventArgs
    {
+    public IList<ReadOnlyMemory<byte>>? MemoryList { get; set; }
    }
}

Usage Examples

private void SetBufferList(in ReadOnlySequence<byte> buffer)
{
    if (_bufferList == null)
    {
        _bufferList = new List<ReadOnlyMemory<byte>>();
    }

    foreach (ReadOnlyMemory<byte> b in buffer)
    {
        _bufferList.Add(b);
    }

    // The act of setting this list, sets the buffers in the internal buffer list
    MemoryList = _bufferList;
}

Risks

More ways of doing the same thing. When to choose MemoryList vs BufferList. Do they overwrite each other? etc.

Activity

  1. added
    api-suggestion
    on Mar 20, 2021
  2. ghost added
    untriaged
    on Mar 20, 2021
  3. geoffkizer commented on Mar 23, 2021

    @geoffkizer
    Contributor

    I agree, this would be a good thing to do. Main difficulty is what you highlighted above:

    More ways of doing the same thing. When to choose MemoryList vs BufferList. Do they overwrite each other? etc.

    The other consideration here is, we want this to work seamlessly with NetworkStream, so whatever way we choose to expose this in SAEA and other socket APIs will effectively commit us to the same approach in Stream etc. So we need to design this in concert with #25344.

    Also note, ReadOnlyMemory only covers send cases; presumably we want to support receive here as well. Which complicates things further.

  4. geoffkizer commented on Mar 23, 2021

    @geoffkizer
    Contributor

    All that said: Can we improve the cost of MemoryMarshal.TryGetArray? That seems really high for what should be a very common operation.

  5. davidfowl commented on Mar 23, 2021

    @davidfowl
    MemberAuthor

    BTW this all came up because I'm looking at this dotnet/aspnetcore#31110

    The other consideration here is, we want this to work seamlessly with NetworkStream, so whatever way we choose to expose this in SAEA and other socket APIs will effectively commit us to the same approach in Stream etc. So we need to design this in concert with #25344.

    Are you saying we should use the same types on both? I agree. I wouldn't gate one of the other but they can be designed together.

    Also note, ReadOnlyMemory only covers send cases; presumably we want to support receive here as well. Which complicates things further.

    Good point. I think multi-buffer sends are 90% and multi buffer receives are 10% (I pulled those numbers out of thin air btw).

    All that said: Can we improve the cost of MemoryMarshal.TryGetArray? That seems really high for what should be a very common operation.

    No idea. @GrabYourPitchforks? The other issue is that Kestrel uses 4K buffers so we end up doing this lots of time doing these on individual 4K chunks.

  6. davidfowl commented on Mar 23, 2021

    @davidfowl
    MemberAuthor

    BTW there's a bunch of other overhead I hit as well. I filed the issue for the easy one so far.

  7. geoffkizer commented on Mar 23, 2021

    @geoffkizer
    Contributor

    Are you saying we should use the same types on both? I agree.

    Yes. E.g. is it IList or IReadOnlyList? We need to use exactly the same types here across Socket/Stream or we could accidentally cause ourselves a lot of pain.

    I wouldn't gate one of the other but they can be designed together.

    Yeah, we could choose to implement this in parts in different ways, we just need to feel confident that the design works in all cases.

  8. geoffkizer commented on Mar 23, 2021

    @geoffkizer
    Contributor

    BTW there's a bunch of other overhead I hit as well.

    Please file it all :)

  9. 29 remaining items

  10. antonfirsov commented on Mar 29, 2021

    @antonfirsov
    Contributor

    I wonder if it would make more sense to just allow you to reuse Socket instances, which would mean you'd reuse the cached SAEAs and PreallocatedOverlapped and other things too.

    I guess this would mean designing new Dispose / Close API-s to which allow avoiding the disposal of cached SAEA-s, so socket.AcceptAsync(System.Net.Sockets.Socket? acceptSocket) can reuse them? This looks exposing implementation details, I think extending SocketAsyncEventArgs is still a (way much) lesser evil.

  11. karelz commented on Apr 20, 2021

    @karelz
    Member

    Triage: We should keep discussing final design for post-6.0. It is reasonable for .NET 7.

  12. added
    tenet-performance
    and removed
    untriaged
    on Apr 20, 2021
  13. added this to the Future milestone on Apr 20, 2021
  14. pepone commented on Jun 18, 2021

    @pepone
    Contributor

    Would you consider using the same API already used for QuicStream

    public ValueTask WriteAsync(ReadOnlyMemory<ReadOnlyMemory<byte>> buffers, CancellationToken cancellationToken = default) => _provider.WriteAsync(buffers, cancellationToken);

    This would make it simpler to support TCP and Quick with the same code.

  15. davidfowl commented on Jul 29, 2023

    @davidfowl
    MemberAuthor

    Now that we have in-line arrays I wonder if these should be span based APIs.

  16. stephentoub commented on Jul 29, 2023

    @stephentoub
    Member

    Now that we have in-line arrays I wonder if these should be span based APIs.

    Which specifically? Async and span don't mix well.

  17. davidfowl commented on Jul 30, 2023

    @davidfowl
    MemberAuthor

    It wouldn’t work for SocketAsyncEventArgs but IIRC the underlying methods don’t need to pin the array passed in, They are usually copied.

    I know the lowest API we have is SAEA so this approach doesn’t flow through Socket.SendAsync in a clean way…

  18. stephentoub commented on Jul 30, 2023

    @stephentoub
    Member

    It wouldn’t work for SocketAsyncEventArgs but IIRC the underlying methods don’t need to pin the array passed in, They are usually copied.

    I know the lowest API we have is SAEA so this approach doesn’t flow through Socket.SendAsync in a clean way…

    I'm still not understanding. Can you sketch what it is you're envisioning? If the operation can't complete immediately and fully, such that the operation needs to pend and try again later, the relevant data or buffers still needs to be available.

    Do you just mean an API like SendAsync(ReadOnlySpan<ReadOnlyMemory<byte>> and it would copy that span to its own possibly-pooled heap object?

  19. davidfowl commented on Jul 30, 2023

    @davidfowl
    MemberAuthor

    I was thinking about how we end up calling these APIs:

    I'm still not understanding. Can you sketch what it is you're envisioning? If the operation can't complete immediately and fully, such that the operation needs to pend and try again later, the relevant data or buffers still needs to be available.

    The buffers themselves are pinned for the lifetime of the async operation but the holder array just needs to be pinned for the length of the synchronous call.

    Do you just mean an API like SendAsync(ReadOnlySpan<ReadOnlyMemory> and it would copy that span to its own possibly-pooled heap object?

    Yes exactly. We would flow this span all the way down to the OS API calls then translate it into the relevant Span<WSABuffer/IOVector>.

    This doesn't gel with the current SAEA BufferList property, and I haven't thought through how to flow it from the user code down to the OS API.

    Contrived example:

    using System.Net;
    using System.Net.Sockets;
    using System.Runtime.CompilerServices;
    
    var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
    socket.Bind(new IPEndPoint(IPAddress.Loopback, 5000));
    socket.Listen();
    
    var client = socket.Accept();
    
    var buffers = new Buffers();
    buffers[0] = GetHeaders();
    buffers[1] = GetBody();
    
    await client.SendAsync(buffers);
    
    ReadOnlyMemory<byte> GetHeaders() => default;
    ReadOnlyMemory<byte> GetBody() => default;
    
    [InlineArray(2)]
    struct Buffers
    {
        private ReadOnlyMemory<byte> _buffers;
    }
    
    static class Extensions
    {
        public static ValueTask<int> SendAsync(this Socket socket, ReadOnlySpan<ReadOnlyMemory<byte>> buffers) => default;
    }
  20. stephentoub commented on Jul 30, 2023

    @stephentoub
    Member

    Do you just mean an API like SendAsync(ReadOnlySpan and it would copy that span to its own possibly-pooled heap object?

    Yes exactly. We would flow this span all the way down to the OS API calls then translate it into the relevant Span<WSABuffer/IOVector>.

    Just to be extra clear, though, it's not just about pinning. The list of buffers needs to be available asynchronously from the current stack if the operation doesn't complete synchronously, which means copying it somewhere.

  21. davidfowl commented on Jul 30, 2023

    @davidfowl
    MemberAuthor

    Just to be extra clear, though, it's not just about pinning. The list of buffers needs to be available asynchronously from the current stack if the operation doesn't complete synchronously, which means copying it somewhere.

    Are you talking about the Linux case where we queue the operation? Or do you mean in both cases?

  22. stephentoub commented on Jul 30, 2023

    @stephentoub
    Member

    Are you talking about the Linux case where we queue the operation?

    I'm talking about the non-Windows case where if the native call on the non-blocking socket returns EAGAIN / EWOULDBLOCK, we wait on an epoll / kqueue and try again when notified that we can make forward progress with the operation.

  23. davidfowl commented on Jul 30, 2023

    @davidfowl
    MemberAuthor

    I see, yes that makes sense. It would force us to copy the array in that case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-System.Net.Socketstenet-performance

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions