Repository navigation
refactor: database startup/migrations + matrix tests for sqlite, mysql & postgres - #2858
Conversation
📝 WalkthroughWalkthroughReplaces ad-hoc DataSourceOptions extension helpers with a centralized DataSourceOptionsBuilder, removes standalone entities/subscribers option modules, updates Config types to use TypeORM DataSourceOptions, integrates the builder across DatabaseModule, migration CLI, and tests, and expands CI to run a DB driver matrix. Changes
Sequence Diagram(s)sequenceDiagram
participant Env as Environment
participant Config as Config (DI)
participant Builder as DataSourceOptionsBuilder
participant DBModule as DatabaseModule
participant CLI as Migration CLI
Env->>Config: provide DB env vars
Config->>Builder: buildWithEnv() or buildWith(config.db)
Builder->>Builder: normalize(options) (validate type, inject entities/subscribers, set migrations)
Builder-->>DBModule: DataSourceOptions
DBModule->>DBModule: initialize DataSource
DBModule->>DBModule: run migrations / setup
CLI->>Builder: buildWith(per-connection options) for migrations
Builder-->>CLI: DataSourceOptions for migration run
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (5)
packages/server-core/src/adapters/database/data-source/options/module.ts (2)
84-90: Inconsistent error type:Errorhere vsAuthupErrorinbuildWithEnv.Line 71 throws
AuthupErrorfor missing env config, but line 89 throws a plainErrorfor unsupported DB type. UseAuthupErrorconsistently so callers can rely on a single error hierarchy.Proposed fix
- throw new Error(`The database type ${options.type} is not supported.`); + throw new AuthupError(`The database type ${options.type} is not supported.`);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/server-core/src/adapters/database/data-source/options/module.ts` around lines 84 - 90, The check in the database options validation throws a plain Error when options.type is unsupported, creating an inconsistent error hierarchy with buildWithEnv which throws AuthupError; change the throw to construct and throw an AuthupError (preserving the same message text) so callers get a consistent error type. Update the branch that currently throws `new Error(\`The database type ${options.type} is not supported.\`)` to instead throw an `AuthupError` with that message (locate the logic around options.type in the same module and keep buildWithEnv behavior unchanged).
92-97: Misleadingas string[]casts on entity/subscriber spreads.
options.entitiesandoptions.subscriberscan contain class constructors, entity schemas, or strings. Casting tostring[]is inaccurate and suppresses type-checking. Since the spread works regardless of element types, a broader type assertion (or simply removing the cast) would be more correct.Proposed fix
- ...(options.entities ? options.entities : []) as string[], + ...(options.entities ? options.entities : []),- ...(options.subscribers || []) as string[], + ...(options.subscribers || []),Also applies to: 137-139
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/server-core/src/adapters/database/data-source/options/module.ts` around lines 92 - 97, The spread casts (options.entities and options.subscribers) are incorrectly asserted as string[] which hides valid constructor/schema types; update the merges in the options object where KeyEntity and KeySubscriber are appended to remove the misleading "as string[]" casts and instead spread the original arrays with a broader/accurate type (e.g., no cast or cast to unknown[]/EntityTarget<any>[]), i.e., replace "(options.entities ? options.entities : []) as string[]" and the similar subscribers cast with a neutral/accurate type or no cast at all so the arrays can contain strings, classes, or schemas; apply the same change to the subscribers merge where KeySubscriber is appended.packages/server-core/src/cli/commands/migration.ts (1)
103-120: Hardcoded local database credentials for migration generation.These credentials (
start123) are only used in theGENERATEpath for local migration file generation, so this isn't a production security concern. Consider documenting (e.g., in a comment or README) that these assume a local Docker Compose or similar setup, so new contributors know what's expected.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/server-core/src/cli/commands/migration.ts` around lines 103 - 120, The hardcoded DataSourceOptions array named "connections" used in the GENERATE migration path contains local credentials (password: start123); add a brief comment above the connections declaration explaining these are intended defaults for local development (e.g., local Docker Compose or dev DB) and instruct contributors how to override them (via env vars or local config) or point to README setup steps; alternatively mention that production runs must not use these values.packages/server-core/src/app/modules/config/types.ts (1)
16-48: Type widened from specific DB option types to genericDataSourceOptions.This trades compile-time safety for simplicity. Previously, assigning e.g.
{ type: 'oracle', ... }toconfig.dbwould be a type error; now it compiles and only fails at runtime inDataSourceOptionsBuilder.normalize(). The runtime checks are in place, so this is acceptable, but worth noting for anyone relying on IDE autocompletion for DB-specific options (e.g.,connectorPackagefor MySQL won't be suggested).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/server-core/src/app/modules/config/types.ts` around lines 16 - 48, The Config.type change widened the db field from DB-specific option types to generic DataSourceOptions causing loss of compile-time validation and IDE autocompletion; to address this, either narrow the type back to a union of the specific TypeORM driver option interfaces or add a discriminated wrapper and runtime validator: update the export type Config to use a union of driver-specific option types (or a { type: string; options: DataSourceOptions } wrapper) and ensure DataSourceOptionsBuilder.normalize() is called/typed to validate/convert at initialization (referencing Config and DataSourceOptionsBuilder.normalize) so consumers get proper typing or explicit runtime validation.packages/server-core/src/app/modules/database/module.ts (1)
115-121: Redundant supported-type validation.
DataSourceOptionsBuilder.normalize()already throws if the type is notmysql,postgres, orbetter-sqlite3(line 89 ofoptions/module.ts). TheisDatabaseTypeSupportedcheck here will never fail becausenormalize()has already run. You could remove it, or if you prefer belt-and-suspenders, at least consolidate the error messages.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/server-core/src/app/modules/database/module.ts` around lines 115 - 121, The initial type validation using isDatabaseTypeSupported is redundant because DataSourceOptionsBuilder.normalize() already enforces allowed types; remove the if block that throws AuthupError for isDatabaseTypeSupported (the one referencing options.type) and keep only the environment-specific check isDatabaseTypeSupportedForEnvironment(options.type, config.env) that throws AuthupError when the chosen type isn’t allowed for the current environment. Ensure references to DataSourceOptionsBuilder.normalize(), isDatabaseTypeSupported, isDatabaseTypeSupportedForEnvironment, and AuthupError are updated/cleaned so no dead code or duplicated messages remain.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/server-core/src/app/modules/database/module.ts`:
- Around line 104-113: The null-check and unreachable branch should be removed:
since optionsBuilder.buildWith(...) and optionsBuilder.buildWithEnv() either
return DataSourceOptions or throw, delete the if (!options) throw new
AuthupError(...) guard and simplify the logic; also decide whether config.db is
optional—either remove the else branch and always call
this.optionsBuilder.buildWith(config.db) (if config.db is non-optional) or make
config.db optional in Config and keep the fallback to
this.optionsBuilder.buildWithEnv(); update references to options,
this.optionsBuilder.buildWith, this.optionsBuilder.buildWithEnv, and AuthupError
accordingly.
---
Nitpick comments:
In `@packages/server-core/src/adapters/database/data-source/options/module.ts`:
- Around line 84-90: The check in the database options validation throws a plain
Error when options.type is unsupported, creating an inconsistent error hierarchy
with buildWithEnv which throws AuthupError; change the throw to construct and
throw an AuthupError (preserving the same message text) so callers get a
consistent error type. Update the branch that currently throws `new Error(\`The
database type ${options.type} is not supported.\`)` to instead throw an
`AuthupError` with that message (locate the logic around options.type in the
same module and keep buildWithEnv behavior unchanged).
- Around line 92-97: The spread casts (options.entities and options.subscribers)
are incorrectly asserted as string[] which hides valid constructor/schema types;
update the merges in the options object where KeyEntity and KeySubscriber are
appended to remove the misleading "as string[]" casts and instead spread the
original arrays with a broader/accurate type (e.g., no cast or cast to
unknown[]/EntityTarget<any>[]), i.e., replace "(options.entities ?
options.entities : []) as string[]" and the similar subscribers cast with a
neutral/accurate type or no cast at all so the arrays can contain strings,
classes, or schemas; apply the same change to the subscribers merge where
KeySubscriber is appended.
In `@packages/server-core/src/app/modules/config/types.ts`:
- Around line 16-48: The Config.type change widened the db field from
DB-specific option types to generic DataSourceOptions causing loss of
compile-time validation and IDE autocompletion; to address this, either narrow
the type back to a union of the specific TypeORM driver option interfaces or add
a discriminated wrapper and runtime validator: update the export type Config to
use a union of driver-specific option types (or a { type: string; options:
DataSourceOptions } wrapper) and ensure DataSourceOptionsBuilder.normalize() is
called/typed to validate/convert at initialization (referencing Config and
DataSourceOptionsBuilder.normalize) so consumers get proper typing or explicit
runtime validation.
In `@packages/server-core/src/app/modules/database/module.ts`:
- Around line 115-121: The initial type validation using isDatabaseTypeSupported
is redundant because DataSourceOptionsBuilder.normalize() already enforces
allowed types; remove the if block that throws AuthupError for
isDatabaseTypeSupported (the one referencing options.type) and keep only the
environment-specific check isDatabaseTypeSupportedForEnvironment(options.type,
config.env) that throws AuthupError when the chosen type isn’t allowed for the
current environment. Ensure references to DataSourceOptionsBuilder.normalize(),
isDatabaseTypeSupported, isDatabaseTypeSupportedForEnvironment, and AuthupError
are updated/cleaned so no dead code or duplicated messages remain.
In `@packages/server-core/src/cli/commands/migration.ts`:
- Around line 103-120: The hardcoded DataSourceOptions array named "connections"
used in the GENERATE migration path contains local credentials (password:
start123); add a brief comment above the connections declaration explaining
these are intended defaults for local development (e.g., local Docker Compose or
dev DB) and instruct contributors how to override them (via env vars or local
config) or point to README setup steps; alternatively mention that production
runs must not use these values.
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
packages/server-core/src/app/modules/database/module.ts (1)
101-101:buildDataSourceOptionsisasyncwith noawait.All operations inside (
buildWith/buildWithEnv,safeResolve,Object.assign) are synchronous. Theasynckeyword is unnecessary and misleads readers into thinking there's async I/O here.♻️ Proposed change
- protected async buildDataSourceOptions(container: IDIContainer) : Promise<DataSourceOptions> { + protected buildDataSourceOptions(container: IDIContainer) : DataSourceOptions {The call site on line 49 can drop its
awaitas well:- const options = await this.buildDataSourceOptions(container); + const options = this.buildDataSourceOptions(container);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/server-core/src/app/modules/database/module.ts` at line 101, Remove the unnecessary async from buildDataSourceOptions (rename signature to protected buildDataSourceOptions(container: IDIContainer): DataSourceOptions) because buildWith/buildWithEnv, safeResolve and Object.assign are all synchronous; update the function body to return the constructed DataSourceOptions directly and adjust any caller that currently does await buildDataSourceOptions(...) to drop the await so it uses the returned DataSourceOptions synchronously (preserve types and behavior)..github/workflows/main.yml (1)
82-110: Both MySQL and Postgres services start for every matrix job, includingsqlite.Services are job-level, not matrix-conditional, so the sqlite run always spins up two unused database containers. Consider using
include/excludematrix rules or moving services into separate jobs per DB type to avoid wasted CI minutes.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.github/workflows/main.yml around lines 82 - 110, The CI currently defines a single job with a matrix db: [mysql, postgres, sqlite] and job-level services (mysql, postgres) so all services start for every matrix variant; fix by making services conditional per DB: either replace the simple matrix with strategy.matrix.include entries for each DB value and attach only the matching service definitions to each include (referencing the matrix values like db: mysql/postgres/sqlite), or split into separate jobs (e.g., jobs.mysql, jobs.postgres, jobs.sqlite) and move the mysql/postgres service blocks into their corresponding job definitions so only the needed containers start for the matching db matrix value.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In @.github/workflows/main.yml:
- Around line 93-97: The health check command in the options block uses the
wrong password (-proot); update the --health-cmd value so mysqladmin pings with
the actual MYSQL_ROOT_PASSWORD (start123) — e.g., replace -proot with -pstart123
or interpolate the env var (MYSQL_ROOT_PASSWORD) into the --health-cmd string so
the health check can authenticate and succeed.
In `@packages/server-core/src/adapters/database/data-source/options/module.ts`:
- Line 96: Remove the incorrect "as string[]" assertions on the spread of
options.entities and options.subscribers (the spread expressions using
...(options.entities ? options.entities : []) and ...(options.subscribers ?
options.subscribers : [])); these arrays are typed as (string | Function |
EntitySchema<any>)[] so the cast is misleading—delete the "as string[]" casts
(or replace with the correct union type only if you must cast) and let
TypeScript infer the proper array element type from the original options.*
properties.
- Around line 67-75: buildWithEnv() fails in CI because
readDataSourceOptionsFromEnv() expects TYPEORM_* vars while CI sets DB_*; update
buildWithEnv to handle both by first calling readDataSourceOptionsFromEnv() and,
if it returns null, construct DataSourceOptions from DB_* env vars (DB_TYPE,
DB_HOST, DB_PORT, DB_USERNAME, DB_PASSWORD, DB_DATABASE) and then pass the
resulting options into this.normalize(), or alternatively call
this.buildWith(options) with the constructed options; reference the
buildWithEnv, readDataSourceOptionsFromEnv, normalize, and buildWith symbols
when making the change.
---
Duplicate comments:
In `@packages/server-core/src/app/modules/database/module.ts`:
- Around line 104-109: The local variable options is declared as
DataSourceOptions | undefined but both branches always assign it, so remove the
unnecessary union to avoid misleading callers; change the declaration of options
to DataSourceOptions (not DataSourceOptions | undefined) and keep the existing
conditional that assigns via this.optionsBuilder.buildWith(config.db) or
this.optionsBuilder.buildWithEnv(), referencing the options variable and the
methods buildWith and buildWithEnv on optionsBuilder.
---
Nitpick comments:
In @.github/workflows/main.yml:
- Around line 82-110: The CI currently defines a single job with a matrix db:
[mysql, postgres, sqlite] and job-level services (mysql, postgres) so all
services start for every matrix variant; fix by making services conditional per
DB: either replace the simple matrix with strategy.matrix.include entries for
each DB value and attach only the matching service definitions to each include
(referencing the matrix values like db: mysql/postgres/sqlite), or split into
separate jobs (e.g., jobs.mysql, jobs.postgres, jobs.sqlite) and move the
mysql/postgres service blocks into their corresponding job definitions so only
the needed containers start for the matching db matrix value.
In `@packages/server-core/src/app/modules/database/module.ts`:
- Line 101: Remove the unnecessary async from buildDataSourceOptions (rename
signature to protected buildDataSourceOptions(container: IDIContainer):
DataSourceOptions) because buildWith/buildWithEnv, safeResolve and Object.assign
are all synchronous; update the function body to return the constructed
DataSourceOptions directly and adjust any caller that currently does await
buildDataSourceOptions(...) to drop the await so it uses the returned
DataSourceOptions synchronously (preserve types and behavior).
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
packages/server-core/test/unit/http/controllers/entities/user.spec.ts (1)
40-47: Loosened assertion reduces test reliability — consider a relative count check instead.Changing from an exact count to
toBeGreaterThanOrEqual(2)accommodates variable seed data across database drivers, but silently swallows test-pollution scenarios (leaked state from other runs, over-seeding, etc.). A self-contained relative check is environment-agnostic and tight:♻️ Proposed refactor for a tighter, environment-agnostic assertion
- it('should read collection', async () => { - const response = await suite.client - .user - .getMany(); - - expect(response.data).toBeDefined(); - expect(response.data.length).toBeGreaterThanOrEqual(2); - }); + let baseUserCount = 0; + + it('should read collection baseline', async () => { + // Capture pre-existing count before any user is created by this suite + // (this block can be merged into beforeAll if preferred) + }); + + it('should read collection', async () => { + const response = await suite.client + .user + .getMany(); + + expect(response.data).toBeDefined(); + // details.id is set by the "should create resource" test + expect(response.data.some((u) => u.id === details.id)).toBe(true); + });Alternatively, if the pre-existing count is stable per environment, snapshot it in
beforeAlland assertcount === snapshot + 1after the create test. Either approach avoids the open-ended lower-bound.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/server-core/test/unit/http/controllers/entities/user.spec.ts` around lines 40 - 47, The test "should read collection" currently asserts a loose lower bound with expect(response.data.length).toBeGreaterThanOrEqual(2), which can hide polluted state; capture a baseline count in beforeAll (e.g., store initialCount from suite.client.user.getMany()), then in this test compare response.data.length against that snapshot (either expect(length).toBe(initialCount) for a pure read or expect(length).toBe(initialCount + 1) if this runs after a create test), updating the test that calls suite.client.user.getMany() to use the stored initialCount variable for a deterministic, environment-agnostic assertion..github/workflows/main.yml (2)
82-84: Considerfail-fast: falseon the matrix.Without it, the default
fail-fast: truemeans a failure in themysqlrun will immediately cancel the in-flightpostgresandsqliteruns, losing their diagnostic output. Since the purpose of the matrix is independent per-driver coverage,fail-fast: falseis the more useful default.♻️ Proposed refactor
strategy: + fail-fast: false matrix: db: [ mysql, postgres, sqlite ]🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.github/workflows/main.yml around lines 82 - 84, The matrix configuration currently uses the default fail-fast behavior; update the GitHub Actions matrix under the strategy block (the matrix: and db: entries) to set fail-fast: false so that a failure in one job (e.g., mysql) does not cancel the other parallel runs (postgres, sqlite); add the fail-fast: false key directly under strategy to preserve independent diagnostics for each db matrix run.
86-110: MySQL and PostgreSQL services spin up even for thesqlitematrix run.GitHub Actions does not support conditional services, so both containers always start regardless of the matrix value. For the
sqliterun this is pure overhead — two heavy DB containers that must pass their health checks before the step sequence begins. A common mitigation is to split into separate jobs or use a separatesqlite-only job that does not declare these services.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.github/workflows/main.yml around lines 86 - 110, The CI workflow currently starts mysql and postgres services for every matrix run (services: mysql and services: postgres), which wastes resources for the sqlite matrix; fix this by splitting the workflow into two jobs: one job (e.g., a dedicated "sqlite" job) that runs the sqlite matrix variant and does not declare services, and another job (e.g., "db-matrix") that runs the mysql/postgres matrix variants and keeps the services: mysql and services: postgres declarations; update the workflow matrix to target the appropriate job or use separate job-level matrices instead of a single matrix that includes sqlite alongside DB-backed variants so the mysql/postgres containers are not started for sqlite runs.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In @.github/workflows/main.yml:
- Around line 101-104: The PostgreSQL service environment only sets
POSTGRES_PASSWORD and needs POSTGRES_DB to create the "app" database referenced
by DB_DATABASE=app; update the env block for the Postgres service to include
POSTGRES_DB: app (and optionally POSTGRES_USER if you want a non-default user)
so the container initializes with the app database and DB_DATABASE resolves
correctly.
- Around line 89-92: The MySQL service environment only sets MYSQL_ROOT_PASSWORD
so the official mysql:9 image won't create the 'app' DB used by tests; add
MYSQL_DATABASE: app to the service env (alongside MYSQL_ROOT_PASSWORD) so the
'app' database is created and matches DB_DATABASE=app in the workflow matrix,
ensuring migrations/connections succeed when using the mysql matrix run.
---
Nitpick comments:
In @.github/workflows/main.yml:
- Around line 82-84: The matrix configuration currently uses the default
fail-fast behavior; update the GitHub Actions matrix under the strategy block
(the matrix: and db: entries) to set fail-fast: false so that a failure in one
job (e.g., mysql) does not cancel the other parallel runs (postgres, sqlite);
add the fail-fast: false key directly under strategy to preserve independent
diagnostics for each db matrix run.
- Around line 86-110: The CI workflow currently starts mysql and postgres
services for every matrix run (services: mysql and services: postgres), which
wastes resources for the sqlite matrix; fix this by splitting the workflow into
two jobs: one job (e.g., a dedicated "sqlite" job) that runs the sqlite matrix
variant and does not declare services, and another job (e.g., "db-matrix") that
runs the mysql/postgres matrix variants and keeps the services: mysql and
services: postgres declarations; update the workflow matrix to target the
appropriate job or use separate job-level matrices instead of a single matrix
that includes sqlite alongside DB-backed variants so the mysql/postgres
containers are not started for sqlite runs.
In `@packages/server-core/test/unit/http/controllers/entities/user.spec.ts`:
- Around line 40-47: The test "should read collection" currently asserts a loose
lower bound with expect(response.data.length).toBeGreaterThanOrEqual(2), which
can hide polluted state; capture a baseline count in beforeAll (e.g., store
initialCount from suite.client.user.getMany()), then in this test compare
response.data.length against that snapshot (either
expect(length).toBe(initialCount) for a pure read or
expect(length).toBe(initialCount + 1) if this runs after a create test),
updating the test that calls suite.client.user.getMany() to use the stored
initialCount variable for a deterministic, environment-agnostic assertion.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
.github/workflows/main.yml (1)
82-84: Consider settingfail-fast: falsefor the DB matrix.With the default
fail-fast: true, a failure in themysqlleg (e.g., the still-unresolvedMYSQL_DATABASEissue below) will cancel thepostgresandsqliteruns, leaving their results unknown.♻️ Suggested change
strategy: + fail-fast: false matrix: db: [ mysql, postgres, sqlite ]🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.github/workflows/main.yml around lines 82 - 84, The workflow's matrix strategy currently may cancel other DB runs on first failure; update the GitHub Actions job strategy to set fail-fast: false under the same strategy block that defines matrix and db (look for "strategy", "matrix", and "db" in the diff) so that failures in one matrix leg (e.g., mysql) do not cancel postgres or sqlite runs; add fail-fast: false as a sibling to matrix within the strategy block.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/server-core/src/app/modules/database/module.ts`:
- Around line 113-118: The current conditional around Config.db is dead because
Config.db is typed as required; fix by either making Config.db optional (change
the type to db?: DataSourceOptions and keep the existing if/else so
optionsBuilder.buildWithEnv() can be used when db is absent) or remove the
conditional and always call options = this.optionsBuilder.buildWith(config.db)
(dropping buildWithEnv usage); update any related types/usages of Config.db and
remove unreachable code branches accordingly, referencing Config.db,
optionsBuilder.buildWith, and optionsBuilder.buildWithEnv in module.ts.
In `@packages/server-core/test/setup.ts`:
- Around line 43-51: The test setup starts a TestDatabaseModuleBase via
database.start(ci) but never tears it down, leaving the TypeORM DataSource alive
and hanging CI; fix by promoting the DependencyContainer instance (ci) and the
TestDatabaseModuleBase instance (database) to module-level variables so the
existing teardown can call database.stop(ci), and update DatabaseModule.stop
(the module's stop method) to call the underlying dataSource.destroy() (or call
DataSource.destroy()) to fully close the connection pool during teardown.
---
Duplicate comments:
In @.github/workflows/main.yml:
- Around line 89-92: Add the missing MYSQL_DATABASE environment variable to the
MySQL service configuration so the container auto-creates the required "app"
database; update the env block (where MYSQL_ROOT_PASSWORD is set) to include
MYSQL_DATABASE: app to match the tests' DB_DATABASE=app expectation and prevent
the mysql:9 matrix job from failing.
---
Nitpick comments:
In @.github/workflows/main.yml:
- Around line 82-84: The workflow's matrix strategy currently may cancel other
DB runs on first failure; update the GitHub Actions job strategy to set
fail-fast: false under the same strategy block that defines matrix and db (look
for "strategy", "matrix", and "db" in the diff) so that failures in one matrix
leg (e.g., mysql) do not cancel postgres or sqlite runs; add fail-fast: false as
a sibling to matrix within the strategy block.
| const ci = new DependencyContainer(); | ||
| const config = new ConfigModule(); | ||
| await config.start(ci); | ||
|
|
||
| const logger = new LoggerModule(); | ||
| await logger.start(ci); | ||
|
|
||
| const database = new TestDatabaseModuleBase(); | ||
| await database.start(ci); |
There was a problem hiding this comment.
Module bootstrap order is correct, but the database is never torn down.
database.start(ci) initializes a TypeORM DataSource (which holds an active connection pool for MySQL/PostgreSQL), but neither database.stop(ci) nor dataSource.destroy() is called in teardown. For the mysql/postgres matrix legs, this leaves live connection-pool handles open, which can prevent the Node.js process from exiting cleanly after tests complete and cause CI job hangs.
DatabaseModule.stop() also needs to call dataSource.destroy() for the teardown to be effective; flag that companion change as well.
🐛 Proposed fix
Promote ci and database to module-level so teardown can reach them:
+import type { IDIContainer } from '../src/core/index.ts';
+import type { DatabaseModule } from '../src/app/modules/database/module.ts';
import 'reflect-metadata';
...
+let globalCi: IDIContainer;
+let globalDatabase: DatabaseModule;
async function setup(project: TestProject) {
...
- const ci = new DependencyContainer();
+ globalCi = new DependencyContainer();
- const config = new ConfigModule();
+ const config = new ConfigModule();
- await config.start(ci);
+ await config.start(globalCi);
- const logger = new LoggerModule();
+ const logger = new LoggerModule();
- await logger.start(ci);
+ await logger.start(globalCi);
- const database = new TestDatabaseModuleBase();
+ globalDatabase = new TestDatabaseModuleBase();
- await database.start(ci);
+ await globalDatabase.start(globalCi);
}
async function teardown() {
await globalThis.OPENLDAP_CONTAINER.stop();
+ if (globalDatabase) {
+ await globalDatabase.stop(globalCi);
+ }
}Also update DatabaseModule.stop() to destroy the DataSource:
async stop(container: IDIContainer): Promise<void> {
+ const dataSource = container.resolve<DataSource>(DatabaseInjectionKey.DataSource);
+ if (dataSource?.isInitialized) {
+ await dataSource.destroy();
+ }
container.unregister(DatabaseInjectionKey.DataSource);
unsetDataSource();
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/server-core/test/setup.ts` around lines 43 - 51, The test setup
starts a TestDatabaseModuleBase via database.start(ci) but never tears it down,
leaving the TypeORM DataSource alive and hanging CI; fix by promoting the
DependencyContainer instance (ci) and the TestDatabaseModuleBase instance
(database) to module-level variables so the existing teardown can call
database.stop(ci), and update DatabaseModule.stop (the module's stop method) to
call the underlying dataSource.destroy() (or call DataSource.destroy()) to fully
close the connection pool during teardown.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/server-core/test/unit/http/controllers/entities/policy/module.spec.ts (1)
70-81: Assertion is slightly over-loosened for this specific case.The group policy is created with exactly 1 child via a UUID-keyed ID (
ids[2]), so the filterparent_id: ids[2]will always return exactly 1 result — there's no driver-seeding variability here.toEqual(1)would remain precise and still pass.toBeGreaterThanOrEqual(1)is consistent with the PR-wide pattern but silently allows duplicate child insertion to go undetected.Consider keeping
toEqual(1)here to preserve the tighter signal.🔧 Suggested revert for precision
- expect(response.data.length).toBeGreaterThanOrEqual(1); + expect(response.data.length).toEqual(1);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/server-core/test/unit/http/controllers/entities/policy/module.spec.ts` around lines 70 - 81, The assertion in the test that reads child policies is too loose: in the test where suite.client.policy.getMany is called with filters { parent_id: ids[2] } the created group policy has exactly one child, so replace the length check expect(response.data.length).toBeGreaterThanOrEqual(1) with a strict equality expect(response.data.length).toEqual(1) to catch accidental duplicate insertions; update the assertion in the spec that contains the it('should read child policies'...) block accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In
`@packages/server-core/test/unit/http/controllers/entities/policy/module.spec.ts`:
- Around line 70-81: The assertion in the test that reads child policies is too
loose: in the test where suite.client.policy.getMany is called with filters {
parent_id: ids[2] } the created group policy has exactly one child, so replace
the length check expect(response.data.length).toBeGreaterThanOrEqual(1) with a
strict equality expect(response.data.length).toEqual(1) to catch accidental
duplicate insertions; update the assertion in the spec that contains the
it('should read child policies'...) block accordingly.
|
@coderabbitai resume |
✅ Actions performedReviews resumed. |
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (6)
packages/server-core/test/unit/http/controllers/entities/robot.spec.ts (1)
114-120: EnsurenextNameis different from the originalname.If both generated names match, this can become a no-op rename and weaken the test intent.
Suggested hardening
- const { name: nextName } = createFakeRobot(); + let { name: nextName } = createFakeRobot(); + if (nextName === name) { + nextName = `${name}-updated`; + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/server-core/test/unit/http/controllers/entities/robot.spec.ts` around lines 114 - 120, The test may generate the same value for nextName as the original name (via createFakeRobot()), turning the call to suite.client.robot.createOrUpdate(name, { name: nextName }) into a no-op; update the test to guarantee a different name before calling createOrUpdate by either calling createFakeRobot until nextName !== name, or by using a helper to generate a unique/modified name (e.g., append a suffix) so nextName is distinct from the original name variable.packages/server-core/test/unit/http/controllers/entities/realm.spec.ts (1)
81-101: Realm created in thecreateOrUpdateblock is never cleaned up.The realm mutated across lines 84–96 (first named
name, then renamed tonextName) is not deleted at the end of the test. If the database persists across runs, orphaned rows accumulate and could cause count-sensitive assertions in other suites to drift. The existingtoBeGreaterThanOrEqualguard reduces the immediate impact, but an explicit teardown would be more robust.🛡️ Suggested cleanup at the end of the test
expect(response.name).toEqual(nextName); expect(response.id).toEqual(id); + + await suite.client.realm.delete(id); });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/server-core/test/unit/http/controllers/entities/realm.spec.ts` around lines 81 - 101, The test creates a Realm via suite.client.realm.createOrUpdate (variables name, nextName and response.id) but never deletes it; wrap the create/update logic in a try/finally and in the finally call the Realm deletion endpoint (e.g., suite.client.realm.delete(response.id) or suite.client.realm.delete(id)) to remove the created record, ensuring you reference the id captured from the first response (id) or the final response.id so the resource is cleaned up even if assertions fail.packages/server-core/src/app/module.ts (1)
15-23:modulesispublic readonlyyet mutated byaddModule/addModules.TypeScript's
readonlyonly prevents reassignment, not mutation viapush. This can be confusing — callers can also directlypushontothis.modulesfrom outside the class, bypassingaddModule. Consider marking itprivate(orprotected) with a public getter returning aReadonlyArray<Module>, so mutation is channeled through the explicit API.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/server-core/src/app/module.ts` around lines 15 - 23, The modules field is declared public readonly but still mutable via push and external callers can mutate it; change the visibility of the modules property (e.g., make it private or protected) and expose a public getter that returns a ReadonlyArray<Module> so external code cannot push into it; update the constructor to assign to the new private field and keep addModule/addModules as the only mutating API (refer to the modules property, constructor, addModule and addModules methods to locate the code to change).packages/server-core/test/unit/modules/provisioning.spec.ts (1)
42-44: Onlydatabaseis stopped inafterAll; other modules are not torn down.
config,logger, andcacheare started inbeforeAllbut never stopped. If any of these hold resources (e.g., cache connections), they may leak between test suites. Consider stopping them in reverse order — mirroring theApplication.stop()pattern — or confirm they are no-ops on stop.♻️ Suggested teardown
afterAll(async () => { await database.stop(di); + await cache.stop(di); + await logger.stop(di); + await config.stop(di); });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/server-core/test/unit/modules/provisioning.spec.ts` around lines 42 - 44, afterAll currently only awaits database.stop(di) while config, logger, and cache started in beforeAll are never stopped; update the afterAll teardown to stop these modules in reverse order (e.g., await cache.stop(di), await logger.stop(di), await config.stop(di)) before/after awaiting database.stop(di) to mirror Application.stop() behavior, and ensure each stop call is awaited and errors are propagated or logged so resources aren't leaked between tests.packages/server-core/src/app/modules/provisioning/sources/composite/module.ts (1)
26-26: UseforEachinstead ofmapfor side-effect-only iteration.
sourcesData.map(...)discards the return value; this signals an intent to transform rather than iterate.forEachcommunicates the side-effect nature more clearly.♻️ Suggested fix
- sourcesData.map((sourceData) => this.merge(output, sourceData)); + sourcesData.forEach((sourceData) => this.merge(output, sourceData));🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/server-core/src/app/modules/provisioning/sources/composite/module.ts` at line 26, Replace the side-effect iteration that currently uses sourcesData.map(...) with a forEach to communicate intent: locate the call where sourcesData.map((sourceData) => this.merge(output, sourceData)); and change it to use sourcesData.forEach((sourceData) => this.merge(output, sourceData));—keep the same variables (sourcesData, output) and method (this.merge) so behavior is unchanged but iteration intent is correct.packages/server-core/test/app/database.ts (1)
53-55: Match the method signature to make the intentional no-op explicit.
TestDatabaseModule.setup()overrides the base method signature(container: IDIContainer, options: DataSourceOptions)by accepting zero parameters. While this works at runtime (extra arguments are simply ignored), the signature mismatch obscures that this override intentionally skips setup behavior. The asymmetry with themigrate()method—which does accept parameters—adds to the confusion.Suggested refactor (same behavior, clearer intent)
export class TestDatabaseModule extends TestDatabaseModuleBase { - protected async setup(): Promise<void> { - // dont do anything :) + protected async setup(_container: IDIContainer, _options: DataSourceOptions): Promise<void> { + // intentionally no-op in this subclass }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/server-core/test/app/database.ts` around lines 53 - 55, Change TestDatabaseModule.setup to match the base signature by declaring setup(container: IDIContainer, options: DataSourceOptions): Promise<void> and keep it a no-op; to make the intent explicit, either prefix unused parameters with an underscore (e.g., _container, _options) or reference them in a noop comment so linters/type-checkers see they are intentionally unused. This keeps the override signature consistent with migrate() and clearly documents that setup is intentionally skipped.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/server-core/package.json`:
- Around line 25-26: Update the npm scripts "test:mysql" and "test:psql" to set
NODE_ENV=test before running vitest so they use the same environment semantics
as the "test" script; modify the command lines for the scripts named test:mysql
and test:psql to prefix the existing cross-env variables with NODE_ENV=test
(ensuring the environment is applied for DB config resolution) and keep the rest
of the arguments (DB_TYPE, DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE and
the vitest config) unchanged.
In `@packages/server-core/src/app/modules/database/module.ts`:
- Around line 61-65: The current startup sets global bindings via
setDataSource(...) and setDataSourceSync(...) before awaiting
this.migrate(container, dataSource), so if migrate throws the global bindings
remain and the local dataSource isn't cleaned up; update the method to either
(A) call await this.migrate(container, dataSource) before setDataSource(...) /
setDataSourceSync(...), or (B) wrap the migrate call in try/catch/finally where
on error you close/cleanup the provided dataSource and unset the globals (undo
setDataSource / setDataSourceSync), ensuring any open connection is closed and
globals are not left bound; refer to the functions setDataSource,
setDataSourceSync, migrate and the dataSource variable to locate where to add
the guard/cleanup logic.
In `@packages/server-core/src/app/modules/provisioning/synchronizer/base.ts`:
- Around line 11-13: synchronizeMany currently uses Promise.all which fail-fast
on the first rejection; decide whether you want all-or-nothing or partial
successes and implement accordingly: if you want partial success with error
collection, replace Promise.all(input.map(...)) with
Promise.allSettled(input.map((entity) => this.synchronize(entity))) then return
the fulfilled values and aggregate the rejected reasons into a single Error (or
return both results and errors) so callers can see which entities failed; if you
intend all-or-nothing, keep Promise.all but wrap errors to add contextual info
(e.g., include the entity's unique identifier) before rethrowing or add a
comment documenting the intentional fail-fast behavior.
In `@packages/server-core/src/app/modules/provisioning/types.ts`:
- Around line 9-12: Update FileProvisioningSource to match the new
IProvisioningSource.load signature by adding the container parameter: change the
method signature of FileProvisioningSource.load(...) to accept (container:
IDIContainer): Promise<RootProvisioningEntity>, and then update any internal
usages to use the passed-in IDIContainer (mirroring how
DefaultProvisioningSource and CompositeProvisioningSource use the container).
Ensure imports include IDIContainer and that callers constructing or invoking
FileProvisioningSource.load pass the container where required.
In
`@packages/server-core/test/unit/http/controllers/entities/permission/module.spec.ts`:
- Around line 140-145: The test can generate nextName equal to name causing the
second PUT (suite.client.permission.createOrUpdate) to not exercise the rename
path; change how nextName is produced (from createFakePermission() or afterward)
to deterministically differ from name — e.g., append or prepend a fixed suffix
or regenerate until nextName !== name — and use that distinct value when calling
createOrUpdate so the update/rename branch is always executed.
In
`@packages/server-core/test/unit/http/controllers/entities/user-attribute.spec.ts`:
- Around line 25-31: The test titled "should create, read, update, delete
resource" only calls suite.client.userAttribute.create and asserts the created
fields; update the test to exercise the full CRUD flow by (1) calling
suite.client.userAttribute.getOne(response.id) and asserting the returned fields
match the created attribute, (2) calling
suite.client.userAttribute.update(response.id, { name: newName, value: newValue
}) and asserting the response contains the updated values, and (3) calling
suite.client.userAttribute.delete(response.id) then asserting a subsequent
suite.client.userAttribute.getOne(response.id) returns not found or throws as
expected; use the existing createFakeUserAttribute() to seed data and reference
response.id for read/update/delete.
In `@packages/server-core/test/unit/modules/provisioning.spec.ts`:
- Around line 46-48: The FileProvisioningSource.load method signature doesn't
match IProvisioningSource; change FileProvisioningSource.load to accept a single
parameter (container: IDIContainer) even if unused, update any calls in tests or
other code (e.g., the test in provisioning.spec.ts that calls new
FileProvisioningSource(...).load()) to pass the container where required or pass
a dummy container, and ensure the class declaration and its implementation
(FileProvisioningSource.load) and any references conform to the interface so the
type checker no longer reports a mismatch.
In `@packages/server-core/test/utils/domains/index.ts`:
- Line 16: Summary: The export line uses an explicit ".ts" extension which is
inconsistent with other re-exports; remove the extension to match module
resolution conventions. Edit the export statement that currently reads "export *
from './user-attribute.ts';" and change it to "export * from
'./user-attribute';" so it matches the rest of the file’s re-exports and avoids
possible resolution issues when moduleResolution changes; ensure no other lines
in the same file use explicit ".ts" extensions.
---
Nitpick comments:
In `@packages/server-core/src/app/module.ts`:
- Around line 15-23: The modules field is declared public readonly but still
mutable via push and external callers can mutate it; change the visibility of
the modules property (e.g., make it private or protected) and expose a public
getter that returns a ReadonlyArray<Module> so external code cannot push into
it; update the constructor to assign to the new private field and keep
addModule/addModules as the only mutating API (refer to the modules property,
constructor, addModule and addModules methods to locate the code to change).
In
`@packages/server-core/src/app/modules/provisioning/sources/composite/module.ts`:
- Line 26: Replace the side-effect iteration that currently uses
sourcesData.map(...) with a forEach to communicate intent: locate the call where
sourcesData.map((sourceData) => this.merge(output, sourceData)); and change it
to use sourcesData.forEach((sourceData) => this.merge(output, sourceData));—keep
the same variables (sourcesData, output) and method (this.merge) so behavior is
unchanged but iteration intent is correct.
In `@packages/server-core/test/app/database.ts`:
- Around line 53-55: Change TestDatabaseModule.setup to match the base signature
by declaring setup(container: IDIContainer, options: DataSourceOptions):
Promise<void> and keep it a no-op; to make the intent explicit, either prefix
unused parameters with an underscore (e.g., _container, _options) or reference
them in a noop comment so linters/type-checkers see they are intentionally
unused. This keeps the override signature consistent with migrate() and clearly
documents that setup is intentionally skipped.
In `@packages/server-core/test/unit/http/controllers/entities/realm.spec.ts`:
- Around line 81-101: The test creates a Realm via
suite.client.realm.createOrUpdate (variables name, nextName and response.id) but
never deletes it; wrap the create/update logic in a try/finally and in the
finally call the Realm deletion endpoint (e.g.,
suite.client.realm.delete(response.id) or suite.client.realm.delete(id)) to
remove the created record, ensuring you reference the id captured from the first
response (id) or the final response.id so the resource is cleaned up even if
assertions fail.
In `@packages/server-core/test/unit/http/controllers/entities/robot.spec.ts`:
- Around line 114-120: The test may generate the same value for nextName as the
original name (via createFakeRobot()), turning the call to
suite.client.robot.createOrUpdate(name, { name: nextName }) into a no-op; update
the test to guarantee a different name before calling createOrUpdate by either
calling createFakeRobot until nextName !== name, or by using a helper to
generate a unique/modified name (e.g., append a suffix) so nextName is distinct
from the original name variable.
In `@packages/server-core/test/unit/modules/provisioning.spec.ts`:
- Around line 42-44: afterAll currently only awaits database.stop(di) while
config, logger, and cache started in beforeAll are never stopped; update the
afterAll teardown to stop these modules in reverse order (e.g., await
cache.stop(di), await logger.stop(di), await config.stop(di)) before/after
awaiting database.stop(di) to mirror Application.stop() behavior, and ensure
each stop call is awaited and errors are propagated or logged so resources
aren't leaked between tests.
ℹ️ Review info
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (34)
.github/workflows/main.ymlpackages/core-kit/src/domains/permission/validator.tspackages/kit/src/index.tspackages/kit/src/wait.tspackages/server-core/package.jsonpackages/server-core/src/adapters/database/data-source/singleton.tspackages/server-core/src/app/factory.tspackages/server-core/src/app/module.tspackages/server-core/src/app/modules/config/normalize.tspackages/server-core/src/app/modules/config/types.tspackages/server-core/src/app/modules/database/module.tspackages/server-core/src/app/modules/provisioning/module.tspackages/server-core/src/app/modules/provisioning/sources/composite/module.tspackages/server-core/src/app/modules/provisioning/sources/default/module.tspackages/server-core/src/app/modules/provisioning/synchronizer/base.tspackages/server-core/src/app/modules/provisioning/synchronizer/role/module.tspackages/server-core/src/app/modules/provisioning/types.tspackages/server-core/src/cli/commands/migration.tspackages/server-core/src/utils/error.tspackages/server-core/test/app/database.tspackages/server-core/test/app/factory.tspackages/server-core/test/setup.tspackages/server-core/test/unit/http/controllers/entities/client.spec.tspackages/server-core/test/unit/http/controllers/entities/permission/module.spec.tspackages/server-core/test/unit/http/controllers/entities/realm.spec.tspackages/server-core/test/unit/http/controllers/entities/robot.spec.tspackages/server-core/test/unit/http/controllers/entities/role.spec.tspackages/server-core/test/unit/http/controllers/entities/scope.spec.tspackages/server-core/test/unit/http/controllers/entities/user-attribute.spec.tspackages/server-core/test/unit/http/controllers/workflows/register.spec.tspackages/server-core/test/unit/http/controllers/workflows/token/grant-password-ldap.spec.tspackages/server-core/test/unit/modules/provisioning.spec.tspackages/server-core/test/utils/domains/index.tspackages/server-core/test/utils/domains/user-attribute.ts
💤 Files with no reviewable changes (1)
- packages/server-core/src/app/modules/config/normalize.ts
✅ Files skipped from review due to trivial changes (1)
- packages/server-core/src/app/modules/provisioning/module.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/server-core/test/setup.ts
- packages/server-core/test/unit/http/controllers/entities/role.spec.ts
- .github/workflows/main.yml
resolves #2857
Summary by CodeRabbit