Skip to content

Close the gateway connection when the login is redirected - #193

Open
TokiTori wants to merge 1 commit into
elixir-ecto:masterfrom
TokiTori:fix/close-redirect-gateway-socket
Open

TokiTori wants to merge 1 commit into
elixir-ecto:masterfrom
TokiTori:fix/close-redirect-gateway-socket

Conversation

@TokiTori

@TokiTori TokiTori commented Nov 2, 2026

Copy link
Copy Markdown

Problem

When Azure SQL redirects the login to another node (routing ENVCHANGE in the LOGINACK, the default for clients inside Azure), tds opens a new connection to the redirect target but never closes the connection to the gateway.

Some time later the gateway closes that abandoned connection. With TLS, the Tds.Tls process that owns the socket then stops with :tcp_closed:

[error] GenServer #PID<0.7100.0> terminating
** (stop) :tcp_closed
Last message: {:tcp_closed, #Port<0.25745>}
State: %Tds.Tls{socket: #Port<0.25745>, ssl_opts: [verify: :verify_none, active: false, cb_info: {Tds.Tls, :tcp, :tcp_closed, :tcp_error}], owner_pid: #PID<0.7103.0>, handshake?: false, buffer: nil}

Tds.Tls is started with GenServer.start_link/3 from the connection process, which does not trap exits, so the abnormal exit silently takes down the connection that is happily using the new socket. The pool reconnects, gets redirected again, leaks the gateway socket again, and the cycle repeats.

In my production logs this happens every 98–120 seconds, around the clock: about 34 times an hour, each time dropping a healthy pooled connection (and any query running on it).

Fix

Close the gateway socket in the redirect clause of Tds.Protocol.message(:login, msg_loginack(redirect: …), s) before connecting to the redirect target. A socket closed locally does not deliver :tcp_closed to its owner, so Tds.Tls no longer stops and the connection survives.

Tests

Added test/login_redirect_gateway_socket_test.exs: a local listener plays the gateway, the login is redirected to a closed port, and the test asserts the gateway connection is closed on both ends. It needs no SQL Server; it fails on master and passes with the fix. It uses a plain TCP socket; the TLS path goes through the same mod.close/1.

Notes

  • After the close, the Tds.Tls process of the gateway socket stays idle until the connection process exits, the same as after disconnect/2 today.
  • This touches the same clause as Return login error instead of crashing on failed redirect #192 (returning a failed redirect as {:error, error, state}); whichever is merged second needs a trivial rebase.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant