Skip to content

Frontend timeouts for async methods #607

Closed

Description

@roji

Npgsql performs frontend (i.e. socket) timeouts, in case the connection is dropped while waiting for a response (half-open connection). However, socket timeouts are only applied to synchronous operations (https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.receivetimeout(v=vs.110).aspx).

It's not 100% clear whether frontend timeouts should be implemented for async operations as well. The old-style async methods such as BeginExecuteAsync very explicitly ignore CommandTimeout (https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtimeout(v=vs.110).aspx). On the other hand, the docs for the .NET 4.5 ExecuteReaderAsync states that The cancellation token can be used to request that the operation be abandoned before the command timeout elapses, implying that the command timeout is respected.

Note that async operations already have backend timeouts just like sync operations.

Activity

  1. added this to the milestone on May 14, 2015
  2. roji commented on Apr 20, 2016

    @roji
    MemberAuthor

    Added info: a test with SqlClient shows clearly that the old {Begin,End}Execute* methods ignore CommandTimeout while the modern ExecuteAsync methods do enforce it.

  3. roji commented on Apr 24, 2016

    @roji
    MemberAuthor

    More added info: it seems that NetworkStream does not support timeouts or cancellation tokens, so it doesn't seem like this is implementable... I wonder what exactly SqlClient does.

  4. Emill commented on Apr 24, 2016

    @Emill
    Contributor

    SqlClient uses some other native stuff than a normal Socket...

  5. roji commented on Apr 24, 2016

    @roji
    MemberAuthor

    You mean even for TCP connections to SqlServer? Could be...

  6. roji commented on Apr 24, 2016

    @roji
    MemberAuthor

    Bah... I guess this is also why they can implements timeouts without breaking the connection... Not fair :)

  7. removed this from the milestone on Apr 24, 2016
  8. LHCGreg commented on Aug 10, 2017

    @LHCGreg

    @roji This is still an outstanding issue right?

        using Dapper;
        
        private static async Task Test()
        {
            try
            {
                using (Npgsql.NpgsqlConnection conn = new Npgsql.NpgsqlConnection("Server=localhost;Port=5432;User Id=my_user;Password=testpw;Database=animerecs_small;Timeout=5;Command Timeout=3"))
                {
                    Console.WriteLine("Connecting to PostgreSQL.");
                    await conn.OpenAsync().ConfigureAwait(false);
                    Console.WriteLine("Connected to PostgreSQL.");
                    Console.WriteLine("Sleeping...");
                    await conn.ExecuteAsync("SELECT pg_sleep(10)").ConfigureAwait(false); // does not throw
                    //conn.Execute("SELECT pg_sleep(10)"); // throws exception due to timeout
                    Console.WriteLine("Done sleeping");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    

    I tried to do a timeout "manually" using a cancellation token and that resulted in a PostgresException "57014: canceling statement due to user request" instead of the OperationCanceledException/TaskCanceledException I was expecting. I guess if there was a broken network connection it would not work because it would be trying to communicate with the server?

        using Dapper;
    
        private static async Task Test()
        {
            try
            {
                using (Npgsql.NpgsqlConnection conn = new Npgsql.NpgsqlConnection("Server=localhost;Port=5432;User Id=my_user;Password=my_password;Database=my_database;Timeout=5;Command Timeout=3"))
                {
                    Console.WriteLine("Connecting to PostgreSQL.");
                    await conn.OpenAsync().ConfigureAwait(false);
                    Console.WriteLine("Connected to PostgreSQL.");
                    Console.WriteLine("Sleeping...");
    
                    using (CancellationTokenSource timeout = new CancellationTokenSource(TimeSpan.FromSeconds(3)))
                    {
                        CommandDefinition cmd = new CommandDefinition("SELECT pg_sleep(120)", commandTimeout: 10000, cancellationToken: timeout.Token);
                        try
                        {
                            await conn.ExecuteAsync(cmd).ConfigureAwait(false);
                        }
                        catch (OperationCanceledException ex)
                        {
                            // This is not entered, the exception is a PostgresException
                            if (timeout.IsCancellationRequested)
                            {
                                Console.WriteLine("Timed out");
                            }
                            else
                            {
                                throw;
                            }
                        }
                        Console.WriteLine("Done sleeping");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    
  9. roji commented on Aug 11, 2017

    @roji
    MemberAuthor

    @LHCGreg yes, this is still an outstanding issue - frontend (i.e. socket) timeouts for async methods isn't supported. And yes, a backend timeout (which is what you triggered with the cancellation token) will not have any effect in case of loss of network connectivity. Unfortunately this is the result of a lack of support in .NET - NetworkStream does not honor socket timeout, nor does it support cancellation.

    The only possibility here is for Npgsql to close the socket - this would "cancel" the operation but also close the connection. In theory we could hook up the cancellation token to do this.

  10. LHCGreg commented on Aug 13, 2017

    @LHCGreg

    @roji I was just asking because this issue is marked as closed. I found a few similar issues: #633, #1265, #1344, #1567.

    In my particular case I am connecting to a database on localhost and have no plans to ever separate the app from the DB, so I guess backend timeouts are good enough for me - the OS should cause socket exceptions to occur if the other side of the connection dies, so I don't have to worry about operations waiting forever.

  11. changed the title [-]Frontend timeouts for async methods?[/-] [+]Frontend timeouts for async methods[/+] on Oct 14, 2019
  12. added this to the Backlog milestone on Oct 14, 2019
  13. reopened this on Oct 14, 2019
  14. roji commented on Oct 14, 2019

    @roji
    MemberAuthor
  15. freerider7777 commented on Mar 27, 2020

    @freerider7777

    Waiting for the fix!
    We have faced the problem (and spent a lot of time to find it) that async methods (ToListAsync for example) don't throw the exception on timeout - just hang (if there is a problem in database and the query takes long time).
    After googling and searching through the code we've found:

                // TODO: Socket.ReceiveTimeout doesn't work for async.
    

    in NpgsqlConnector :)
    https://github.com/npgsql/npgsql/blob/572918fc3a94cf201ba947dac341d1a1de38f7b9/src/Npgsql/NpgsqlConnector.cs

  16. roji commented on Mar 27, 2020

    @roji
    MemberAuthor

    Yeah, we should definitely do this at some point. If someone wants to take a stab at this, please do so.

  17. modified the milestones: Backlog, 5.0 on Jun 24, 2020
  18. YohDeadfall commented on Jun 24, 2020

    @YohDeadfall
    Contributor

    @vonzshik I need your comment here to assign the issue.

  19. vonzshik commented on Jun 24, 2020

    @vonzshik
    Contributor

    @YohDeadfall I'm here

  20. added a commit that references this issue on Aug 15, 2020
    801638e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions