Repository navigation
fix(daemon): close clients on shutdown and after a failed first connect - #52
Merged
Merged
Conversation
disconnectAllAccounts only dropped its reference to each client, so a graceful stop never called destroy(): mtcute didn't save and close the session files, and the next start could begin from stale update state. connectAccount kept the client in a local variable until the connect succeeded, so a failed start(), getMe() or updates loop left it open. connectAccount now tracks the client in the account state right away and releases it in its catch, like attemptReconnect does, and shutdown releases every account through the same releaseClient. releaseClient takes the client out of the account state before it closes it, so the duplicate merge path, a reconnect and shutdown can't close one client twice. The clients close in parallel, so one slow close doesn't use up the shutdown timeout for the others, and a handler removal error no longer skips the close. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…a stop The shutdown bullet and the disconnectAllAccounts JSDoc said that closing the clients makes mtcute save and close the session files, update state included. It doesn't: @mtcute/bun's exit hook already saves and closes every session file when SIGTERM or SIGINT arrives, before the daemon's shutdown runs, and the updates loop saves its state after every batch. Closing a client on shutdown stops its updates loop and closes its Telegram connections. The failed-connect bullet now also names the connection it no longer leaves open. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n a stop mtcute's exit hook closes every session file when SIGTERM or SIGINT arrives, so on a normal stop the daemon's destroy() runs against a closed database. When anything was queued after the signal (pts from an update batch, a peer seen during a sync job), destroy() fails with "Database has closed", and the daemon logged "Failed to close client (shutdown)" as a warning for every busy account on every tg daemon stop. That error only means mtcute got there first, so closeClientSafe now logs it at debug. Other close errors still warn. The live daemon smoke test checks that a normal stop logs no close warning. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What and why
Fixes #34.
Problem. The daemon left Telegram clients open in two paths:
connectAccountkept the new client in a local variable until the connect succeeded. A failedstart(),getMe()orstartUpdatesLoop()left that client, its connection and its session file open until the daemon stopped.disconnectAllAccounts(graceful shutdown:tg daemon stop, SIGTERM, SIGINT) only dropped its reference to each client. It never calleddestroy(), so the updates loops and Telegram connections were left to the process exit.The session files themselves were not at risk:
@mtcute/bun's exit hook already saves and closes every session file when SIGTERM or SIGINT arrives, and the updates loop saves its state after every batch. The issue text assumed otherwise.Fix. Both paths now use the existing
releaseClienthelper (remove handlers, drop the sync worker,closeClientSafe→destroy()), asattemptReconnectalready does:connectAccountputs the client in the account state right after it creates it and releases it in itscatch. The duplicate-account merge path also releases it throughreleaseClient, not a barecloseClientSafe.disconnectAllAccountsreleases every account in parallel, so one slow close doesn't use up the 30 s shutdown timeout for the others.releaseClienttakes the client out of the account state before it closes it. That's why each client closes exactly once: after the merge path, a reconnect or a failed connect, shutdown finds no client left to close. It now also catches a handler-removal error, the defensivetrythe old shutdown loop had, so that error can't skip the close.Quiet stop. Because mtcute's exit hook closes the session files first, the shutdown
destroy()runs against a closed database. When anything was queued after the signal (pts from an update batch, a peer seen by a sync job), it fails with "Database has closed". That only means mtcute got there first, socloseClientSafelogs that error at debug instead of warn; other close errors still warn. No supported mtcute option turns the sqlite driver's hook off. The writes lost in that window are older than this PR and tracked in #56.The issue asked for both paths to go through
closeClientSafe. They do, throughreleaseClient. That helper owns the "take it out of the state, then close it" step, so reusing it keeps the double-close guard in one place. The code diff stays insidesrc/daemon/daemon-accounts.tsand touches no DB access.docs/daemon.md("Error Handling & Resilience") now says the daemon closes a client right after a failed first connect, and that on shutdown it closes every client once, which stops its updates loop and closes its connections, while mtcute saves and closes the session files when the signal arrives.How I checked it
The unit tests in
src/__tests__/daemon-accounts.connect.test.tsuse the mocked mtcute client. Seven of them fail without the change:connectAccountcloses the client whenstart,getMeor the updates loop fails:destroy()is called once, the handlers are gone and the state has no client. A later shutdown doesn't call it again.disconnectAllAccountscloses every client once on shutdown: two connected accounts plus one whose connect failed. Eachdestroy()is called once, and a second shutdown call closes nothing.disconnectAllAccountsstill closes the other clients when onedestroy()throws.destroy()is called exactly once, including after shutdown.The exit-hook behaviour was reproduced offline with mtcute 0.32.6 and a temp session file: after a SIGTERM,
destroy()succeeds when nothing was queued and throws "Database has closed" when a write was queued after the signal.The live daemon smoke test (
src/__integration__/telegram.integration.test.ts) now asserts that the daemon's stderr has noFailed to close clientline aftertg daemon stop. It passed against the real API with a copy of the test session.Commands:
bun run check: cleanbun run test: 1561 pass (cache-db-lock.test.tsfailed once in one run and passed on rerun; it doesn't touch the daemon)bun run test:e2e: 193 passbun run test:integration -t "daemon connects": 1 passTests pass locally and use made-up data only
README, docs and affected demos follow the product content standard
Title follows the repo's commit style: Conventional Commits (
feat: …,fix: …) unlessAGENTS.mdsays otherwise🤖 Generated with Claude Code