Browse Source

Use deprecated unit_time, milli_seconds, to support otp-18, return back {error, Reason} from gen_tcp:recv rather than badmatch

Enid Gjoleka 5 years ago
parent
commit
50f0c4e134
2 changed files with 10 additions and 14 deletions
  1. 2 2
      README.md
  2. 8 12
      src/commands/epgsql_cmd_connect.erl

+ 2 - 2
README.md

@@ -97,8 +97,8 @@ Only `host` and `username` are mandatory, but most likely you would need `databa
 - `password` - DB user password. It might be provided as string / binary or as a fun that returns
    string / binary. Internally, plain password is wrapped to anonymous fun before it is sent to connection
    process, so, if `connect` command crashes, plain password will not appear in crash logs.
-- `{timeout, TimeoutMs}` parameter will trigger an `{error, timeout}` result when the
-   socket fails to connect within `TimeoutMs` milliseconds.
+- `timeout` parameter will trigger an `{error, timeout}` result when the
+   socket fails to connect within provided milliseconds.
 - `ssl` if set to `true`, perform an attempt to connect in ssl mode, but continue unencrypted
   if encryption isn't supported by server. if set to `required` connection will fail if encryption
   is not available.

+ 8 - 12
src/commands/epgsql_cmd_connect.erl

@@ -124,9 +124,8 @@ maybe_ssl(S, false, _, PgSock, _Deadline) ->
 maybe_ssl(S, Flag, Opts, PgSock, Deadline) ->
     ok = gen_tcp:send(S, <<8:?int32, 80877103:?int32>>),
     Timeout0 = timeout(Deadline),
-    {ok, <<Code>>} = gen_tcp:recv(S, 1, Timeout0),
-    case Code of
-        $S  ->
+    case gen_tcp:recv(S, 1, Timeout0) of
+        {ok, <<$S>>}  ->
             SslOpts = maps:get(ssl_opts, Opts, []),
             Timeout = timeout(Deadline),
             case ssl:connect(S, SslOpts, Timeout) of
@@ -136,13 +135,15 @@ maybe_ssl(S, Flag, Opts, PgSock, Deadline) ->
                     Err = {ssl_negotiation_failed, Reason},
                     {error, Err}
             end;
-        $N ->
+        {ok, <<$N>>} ->
             case Flag of
                 true ->
                     epgsql_sock:set_net_socket(gen_tcp, S, PgSock);
                 required ->
                     {error, ssl_not_available}
-            end
+            end;
+        {error, Reason} ->
+            {error, Reason}
     end.
 
 %% Auth sub-protocol
@@ -280,12 +281,7 @@ hex(Bin) ->
     <<<<(HChar(H)), (HChar(L))>> || <<H:4, L:4>> <= Bin>>.
 
 deadline(Timeout) ->
-    erlang:monotonic_time(millisecond) + Timeout.
+    erlang:monotonic_time(milli_seconds) + Timeout.
 
 timeout(Deadline) ->
-    case (Deadline - erlang:monotonic_time(millisecond)) of
-        NewDeadline when NewDeadline < 0 ->
-            0;
-        Val ->
-            Val
-    end.
+    erlang:max(0, Deadline - erlang:monotonic_time(milli_seconds)).