Repository navigation
fix(db): share one connection pool across the panel's API routers - #121
Merged
Merged
Conversation
Что: - `apps/dokploy/server/db/index.ts` больше не создаёт свой пул postgres.js, а переэкспортирует общий клиент из `@dokploy/server/db`. - Тест `__test__/db/app-db-module.test.ts` проверяет, что оба модуля отдают один и тот же клиент. Зачем: - Роутеры `tag`, `network` и `libsql` брали базу из `@/server/db`. В production этот модуль создавал второй пул до 10 соединений рядом с общим, поэтому панель держала до 20 соединений к Postgres вместо 10. Общий модуль уже кеширует клиент в `globalThis`, чтобы на процесс был один пул. - На изолированном стенде под нагрузкой соединений стало 10 вместо 20, память процессов Postgres снизилась со 107 до 91 МБ. Риски: - Роутеры `tag`, `network` и `libsql` теперь делят пул с остальными; лимит в 10 соединений на процесс тот же, что у остальной панели. Скорость API на стенде не изменилась. Проверки: - Команды и результаты: `vitest run __test__/db/app-db-module.test.ts __test__/tag` проходит, новый тест на коде без правки падает; полный `vitest run`: 4293 прошли, 5 упали в `vector-validate.test.ts` (на Mac Colima не монтирует временную папку `docker run`, без правки так же); `tsc --noEmit` в `apps/dokploy` и `packages/server` без ошибок; `biome check` без замечаний. Стенд: нативный arm64-образ этой ветки против образа `AgentHits-Dev` того же коммита в Docker-in-Docker, сценарий из входа, страниц, нагрузки на API, деплоев, логов, терминалов и 120 одновременных запросов к `tag.all` и `project.all`. - Ограничения: стенд на Mac, а не на сервере. What: - `apps/dokploy/server/db/index.ts` no longer creates its own postgres.js pool; it re-exports the shared client from `@dokploy/server/db`. - The test `__test__/db/app-db-module.test.ts` checks that both modules return the same client. Why: - The `tag`, `network` and `libsql` routers took the database from `@/server/db`. In production that module created a second pool of up to 10 connections next to the shared one, so the panel held up to 20 Postgres connections instead of 10. The shared module already caches the client on `globalThis` to keep one pool per process. - On the isolated bench, connections under load went from 20 to 10 and Postgres process memory from 107 to 91 MB. Risks: - The `tag`, `network` and `libsql` routers now share the pool with the rest; the limit of 10 connections per process is the same as for the rest of the panel. API speed on the bench did not change. Checks: - Commands and results: `vitest run __test__/db/app-db-module.test.ts __test__/tag` passes, the new test fails without the change; full `vitest run`: 4293 passed, 5 failed in `vector-validate.test.ts` (Colima on the Mac does not mount the `docker run` temp folder, same without the change); `tsc --noEmit` in `apps/dokploy` and `packages/server` clean; `biome check` clean. Bench: a native arm64 image of this branch against an `AgentHits-Dev` image of the same commit in Docker-in-Docker, a scenario of sign-in, pages, API load, deploys, logs, terminals and 120 concurrent `tag.all` and `project.all` requests. - Limitations: the bench runs on a Mac, not the server. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.
Зачем
Роутеры
tag,networkиlibsqlберут базу из@/server/db. В production этот модуль создавал собственный пул postgres.js до 10 соединений, рядом с общим пулом из@dokploy/server/db. В итоге панель держала до 20 соединений к Postgres вместо 10.tag.allвызывается на странице проектов, так что второй пул открывался почти сразу. Общий модуль уже кеширует клиента вglobalThis, чтобы в процессе был один пул; модуль приложения этот кеш в production не использовал.Что изменилось
apps/dokploy/server/db/index.tsпереэкспортируетdb,dbUrl,andиeqиз@dokploy/server/db, а не создаёт свой пул. Импорты в роутерах и моки в тестах не меняются.apps/dokploy/__test__/db/app-db-module.test.tsпроверяет, что оба модуля отдают один и тот же клиент.Проверки
vitestнового теста и тестов роутераtag: проходят. Новый тест на коде без правки падает.vitest: 4293 прошли, 5 упали вvector-validate.test.ts. Они падают и без правки: на Mac Colima не монтирует временную папку дляdocker run.tsc --noEmitвapps/dokployиpackages/serverиbiome checkпроходят без ошибок.AgentHits-Devтого же коммита.tag.allиproject.allи две минуты простоя. В таблице медиана по прогонам.Память Postgres падает меньше, чем вдвое, потому что каждое соединение кеширует подготовленные запросы: когда соединений меньше, каждое обслуживает больше разных запросов.
Сценарий: вход; пять страниц панели; 10 запросов
project.allподряд; 1000 запросов к API по 10 одновременно и 200 к странице проектов по 5; проект; деплой Compose со сборкой и живым логом; логи и терминал контейнера; деплой из образа; добавление сервера и SSH-терминал.С соседним PR про закрытие простаивающих соединений эффекты складываются: под нагрузкой 10 соединений и 88 МиБ, после простоя одно соединение и 15 МиБ.
Что проверить вручную на dev
🤖 Generated with Claude Code