Skip to content

refactor: add module dependency graph with topological sort to server-core application - #2908

Merged
tada5hi merged 30 commits into
masterfrom
2907-app
Mar 14, 2026
Merged

tada5hi merged 30 commits into
masterfrom
2907-app

Conversation

@tada5hi

@tada5hi tada5hi commented Mar 14, 2026 •

Copy link
Copy Markdown
Collaborator

resolves #2907

Summary by CodeRabbit

  • Refactor

    • Startup now computes module start/stop order from declared dependencies and errors on cycles.
    • App construction switched to a fluent ApplicationBuilder pattern used across CLI, tests, and factories.
  • New Features

    • Modules expose identity and dependency metadata; centralized module-name constants added.
    • Database module accepts lifecycle hooks for build/setup/migrate.
    • Test HTTP helper provides an in-process client.
  • Bug Fixes

    • CLI migration/reset flows now start required services before operations.

@coderabbitai

coderabbitai Bot commented Mar 14, 2026 •

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Application now stores modules in a protected Map and computes a dependency-aware startup order via a new resolveOrder (topological sort with cycle detection). Modules expose name/dependsOn metadata. An ApplicationBuilder with fluent withX() methods was added and used across CLI, factory, and tests to construct Applications.

Changes

Cohort / File(s) Summary
Core application storage & control
apps/server-core/src/app/module.ts
Replaced public modules: Module[] with protected modules: Map<string, Module>, added protected startOrder: Module[], and introduced protected resolveOrder(): Module[] to compute topological start order with cycle detection; start/stop now use resolved order.
Builder, factory & app index
apps/server-core/src/app/builder.ts, apps/server-core/src/app/factory.ts, apps/server-core/src/app/index.ts
Added ApplicationBuilder with fluent withX() methods and default factories; switched application creation to builder-based construction and re-exported builder from app index; factory now returns builder-built Application.
Module naming, types & constants
apps/server-core/src/app/modules/constants.ts, apps/server-core/src/app/modules/index.ts, apps/server-core/src/app/modules/types.ts
Added ModuleName constants, re-exported them, and extended Module interface with readonly name: string and optional readonly dependsOn?: string[].
Module metadata updates
apps/server-core/src/app/modules/.../module.ts
apps/server-core/src/app/modules/config/module.ts, .../logger/module.ts, .../cache/module.ts, .../mail/module.ts, .../vault/module.ts, .../runtime/module.ts, .../swagger/module.ts, .../database/module.ts, .../provisioning/module.ts, .../ldap/module.ts, .../authentication/module.ts, .../identity/module.ts, .../oauth2/module.ts, .../components/module.ts, .../http/module.ts
Many modules now expose name and dependsOn readonly properties initialized in constructors to declare dependency edges; DatabaseModule gained DatabaseModuleOptions and optional lifecycle hooks (prepareBuild/setup/migrate). Runtime behavior largely unchanged.
CLI commands
apps/server-core/src/cli/commands/*.ts
migration.ts, healthcheck.ts, reset.ts, swagger.ts
CLI commands switched from direct Application/ConfigModule usage to building apps via ApplicationBuilder().with...().build(); migration.ts refactored to use builder and modular migration helper flows.
Tests & test helpers
apps/server-core/test/*
test/app/factory.ts, test/setup.ts, test/app/database.ts, test/app/http.ts, test/app/module.ts, test/app/index.ts, test/unit/modules/provisioning.spec.ts
Test harness migrated to ApplicationBuilder usage; TestDatabaseModule classes replaced with factory functions (createTestDatabaseModuleForSetup/ForSuite); TestHTTPApplication added (HTTP client helper); TestApplication removed in-process client. Test exports and builders updated accordingly.
Misc (automation doc)
.claude/skills/investigate-pr-comments/SKILL.md
Updated workflow to resolve fixed GitHub threads and adjusted dry-run behavior; added reporting step.

Sequence Diagram

sequenceDiagram
    participant CLI as CLI / Command
    participant Builder as ApplicationBuilder
    participant App as Application
    participant Map as Modules Map
    participant Resolver as resolveOrder()
    participant Module as Module Instance

    CLI->>Builder: configure modules (withX... .build())
    Builder->>App: instantiate App & call addModule(name, module)
    App->>Map: store module by name
    CLI->>App: app.start()
    App->>Resolver: resolveOrder()
    Resolver->>Map: read modules (name, dependsOn)
    Resolver->>Resolver: build dependency graph & topo sort
    alt cycle detected
        Resolver-->>App: throw AuthupError (cycle)
    else
        Resolver-->>App: return startOrder
        loop for each module in startOrder
            App->>Module: module.start(container)
        end
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐇 I hop from name to depends, a tidy map I store,
I sort the tangled branches till each module's ready to roar.
If circles sneak and tangle, I thump and cry "Nope!" —
Then line them up and whisper: start, my friends, in hope.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Linked Issues check ❓ Inconclusive Linked issue #2907 provides no meaningful requirements or acceptance criteria—only a blank feature request template. Unable to validate against specific coding requirements. Refer to issue #2907 for detailed requirements or feature specifications that should guide the implementation.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'refactor: add module dependency graph with topological sort to server-core application' accurately describes the main change: introducing dependency graph management and topological sorting for modules.
Out of Scope Changes check ✅ Passed Changes comprehensively implement the intended refactoring: module dependency metadata, topological sorting, ApplicationBuilder pattern, and test infrastructure updates. All modifications directly support dependency graph functionality.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 2907-app
📝 Coding Plan
  • Generate coding plan for human review comments

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@tada5hi tada5hi changed the title 2907 app refactor: add module dependency graph with topological sort to server-core application Mar 14, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/server-core/src/app/modules/http/module.ts (1)

81-83: ⚠️ Potential issue | 🔴 Critical

stop() is effectively disabled because this.instance is never assigned.

Line 91 exits when this.instance is unset, but Lines 81-83 only register server in the container. Without assigning this.instance in start(), the HTTP server cannot be closed during shutdown/restart.

🐛 Proposed fix
         container.register(HTTPInjectionKey.Server, {
             useValue: server,
         });
+        this.instance = server;

Also applies to: 90-96

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/app/modules/http/module.ts` around lines 81 - 83, The
HTTP server instance is registered in the container but never assigned to the
class field, so stop() exits early because this.instance is unset; in start()
assign the created server to this.instance (e.g., this.instance = server) after
creating/registering it (the block that currently calls
container.register(HTTPInjectionKey.Server, { useValue: server })) so that
stop() can access and close the server; ensure the same this.instance is the
value used by stop()'s close logic and remove any early-return paths that check
the wrong variable.
🧹 Nitpick comments (3)
apps/server-core/src/cli/commands/migration.ts (1)

50-51: Use ModuleName constants for consistency with other modules.

The inline module descriptor uses string literals 'config' and 'logger' in the dependsOn array, while all other modules in the codebase use ModuleName.CONFIG and ModuleName.LOGGER. Since ModuleName is already available from the existing import from '../../app/index.ts', using the constants would improve consistency and maintainability.

♻️ Suggested change
+import { ModuleName } from '../../app/index.ts';
                 {
                     name: 'migration',
-                    dependsOn: ['config', 'logger'],
+                    dependsOn: [ModuleName.CONFIG, ModuleName.LOGGER],
                     async start(container: IDIContainer): Promise<void> {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/cli/commands/migration.ts` around lines 50 - 51, The
dependsOn array for the inline module descriptor (the module with name
'migration') uses string literals 'config' and 'logger' — replace those with the
ModuleName constants (ModuleName.CONFIG and ModuleName.LOGGER) imported from
'../../app/index.ts' to match project convention; update the dependsOn entry for
the migration module so it references ModuleName.CONFIG and ModuleName.LOGGER
instead of string literals.
apps/server-core/src/app/module.ts (2)

34-36: Consider detecting duplicate module names.

If two modules share the same name, the second silently overwrites the first. This could mask configuration errors.

🛡️ Proposed fix to detect duplicates
 addModule(module: Module): void {
+    if (this.modules.has(module.name)) {
+        throw new AuthupError(`Duplicate module name: ${module.name}`);
+    }
     this.modules.set(module.name, module);
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/app/module.ts` around lines 34 - 36, The addModule
method currently overwrites existing entries when a Module with the same name is
added; update addModule (the addModule(module: Module): void implementation that
writes to this.modules) to first detect duplicates by checking
this.modules.has(module.name) and then handle it (throw a descriptive Error or
log and return) instead of unconditionally calling this.modules.set; include the
module.name and possibly the existing module object in the error/log message to
aid debugging.

29-29: Address static analysis warning about forEach callbacks.

Biome flags these callbacks for implicitly returning a value. While functionally correct (returning void), explicit braces clarify intent.

♻️ Proposed fix
-        modules.forEach((module) => this.addModule(module));
+        modules.forEach((module) => { this.addModule(module); });
     addModules(modules: Module[]): void {
-        modules.forEach((module) => this.addModule(module));
+        modules.forEach((module) => { this.addModule(module); });
     }

Also applies to: 38-40

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/app/module.ts` at line 29, The forEach callbacks
implicitly return a value and trigger static-analysis warnings; change the arrow
callbacks to use explicit block bodies so they return void — e.g., replace uses
of modules.forEach((module) => this.addModule(module)) with a block-bodied
callback modules.forEach((module) => { this.addModule(module); }); do the same
for the other forEach occurrences in this file that call this.addModule (and any
analogous forEach -> methodCall patterns).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/server-core/src/app/module.ts`:
- Around line 81-84: The loop that checks module.dependsOn currently ignores
missing dependencies by returning when registered.has(dep) is false; change this
to surface the problem early for the module (either throw a ValidationError or
emit a clear warning) so missing dependencies are not silently
skipped—specifically update the logic around module.dependsOn and
registered.has(dep) (the block that currently does "if (!registered.has(dep)) {
return; }") to instead either throw a descriptive error (e.g., include
module.name and the missing dep) or call the application's logger to warn, so
callers like HTTPModule that later call container.resolve(LoggerInjectionKey)
will fail fast with a helpful message.

In `@apps/server-core/src/app/modules/oauth2/module.ts`:
- Around line 53-56: The module constructor for OAuth2Module currently sets
this.dependsOn to [ModuleName.DATABASE, ModuleName.CACHE, ModuleName.CONFIG] but
omits ModuleName.IDENTITY; update the constructor (the dependsOn assignment in
OAuth2Module) to include ModuleName.IDENTITY so that IdentityModule starts
before OAuth2Module and the start() resolution of IIdentityResolver via
IdentityInjectionKey.Resolver succeeds at runtime.

---

Outside diff comments:
In `@apps/server-core/src/app/modules/http/module.ts`:
- Around line 81-83: The HTTP server instance is registered in the container but
never assigned to the class field, so stop() exits early because this.instance
is unset; in start() assign the created server to this.instance (e.g.,
this.instance = server) after creating/registering it (the block that currently
calls container.register(HTTPInjectionKey.Server, { useValue: server })) so that
stop() can access and close the server; ensure the same this.instance is the
value used by stop()'s close logic and remove any early-return paths that check
the wrong variable.

---

Nitpick comments:
In `@apps/server-core/src/app/module.ts`:
- Around line 34-36: The addModule method currently overwrites existing entries
when a Module with the same name is added; update addModule (the
addModule(module: Module): void implementation that writes to this.modules) to
first detect duplicates by checking this.modules.has(module.name) and then
handle it (throw a descriptive Error or log and return) instead of
unconditionally calling this.modules.set; include the module.name and possibly
the existing module object in the error/log message to aid debugging.
- Line 29: The forEach callbacks implicitly return a value and trigger
static-analysis warnings; change the arrow callbacks to use explicit block
bodies so they return void — e.g., replace uses of modules.forEach((module) =>
this.addModule(module)) with a block-bodied callback modules.forEach((module) =>
{ this.addModule(module); }); do the same for the other forEach occurrences in
this file that call this.addModule (and any analogous forEach -> methodCall
patterns).

In `@apps/server-core/src/cli/commands/migration.ts`:
- Around line 50-51: The dependsOn array for the inline module descriptor (the
module with name 'migration') uses string literals 'config' and 'logger' —
replace those with the ModuleName constants (ModuleName.CONFIG and
ModuleName.LOGGER) imported from '../../app/index.ts' to match project
convention; update the dependsOn entry for the migration module so it references
ModuleName.CONFIG and ModuleName.LOGGER instead of string literals.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c462150b-341a-472c-984a-0ba211dedadd

📥 Commits

Reviewing files that changed from the base of the PR and between 50037cb and e9c9970.

📒 Files selected for processing (20)
  • apps/server-core/src/app/module.ts
  • apps/server-core/src/app/modules/authentication/module.ts
  • apps/server-core/src/app/modules/cache/module.ts
  • apps/server-core/src/app/modules/components/module.ts
  • apps/server-core/src/app/modules/config/module.ts
  • apps/server-core/src/app/modules/constants.ts
  • apps/server-core/src/app/modules/database/module.ts
  • apps/server-core/src/app/modules/http/module.ts
  • apps/server-core/src/app/modules/identity/module.ts
  • apps/server-core/src/app/modules/index.ts
  • apps/server-core/src/app/modules/ldap/module.ts
  • apps/server-core/src/app/modules/logger/module.ts
  • apps/server-core/src/app/modules/mail/module.ts
  • apps/server-core/src/app/modules/oauth2/module.ts
  • apps/server-core/src/app/modules/provisioning/module.ts
  • apps/server-core/src/app/modules/runtime/module.ts
  • apps/server-core/src/app/modules/swagger/module.ts
  • apps/server-core/src/app/modules/types.ts
  • apps/server-core/src/app/modules/vault/module.ts
  • apps/server-core/src/cli/commands/migration.ts

Comment on lines +81 to +84
module.dependsOn.forEach((dep) => {
if (!registered.has(dep)) {
return;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check if any modules have dependencies on modules not defined in ModuleName constants
# This helps verify if silent ignore is safe

# Find all ModuleName constant values
echo "=== Defined ModuleName constants ==="
ast-grep --pattern 'ModuleName = {
  $$$
}'

echo ""
echo "=== Module dependsOn declarations ==="
rg -n "dependsOn.*=" --glob "*.ts" -A3 | head -80

Repository: authup/authup

Length of output: 4968


🏁 Script executed:

#!/bin/bash
# Find ModuleName definition
echo "=== ModuleName definition ==="
rg -n "ModuleName" --glob "*.ts" | grep -E "(enum|const|type).*ModuleName" | head -20

echo ""
echo "=== Full module.ts context around resolveOrder ==="
cat -n apps/server-core/src/app/module.ts | head -120

Repository: authup/authup

Length of output: 4514


🏁 Script executed:

#!/bin/bash
# Check ModuleName constants
echo "=== ModuleName constants ==="
cat -n apps/server-core/src/app/modules/constants.ts

echo ""
echo "=== How Application is initialized - search for addModule/addModules calls ==="
rg -n "addModule|new Application" --glob "*.ts" -B2 -A2 | head -100

Repository: authup/authup

Length of output: 3362


🏁 Script executed:

#!/bin/bash
# Check full Application factory
echo "=== Full factory.ts ==="
cat -n apps/server-core/src/app/factory.ts

echo ""
echo "=== Check if there are tests for module resolution ==="
find . -name "*.spec.ts" -o -name "*.test.ts" | xargs grep -l "resolveOrder\|circular\|dependsOn" 2>/dev/null | head -10

Repository: authup/authup

Length of output: 1687


🏁 Script executed:

#!/bin/bash
# Check how HTTPModule uses its dependencies
echo "=== HTTPModule implementation ==="
cat -n apps/server-core/src/app/modules/http/module.ts | head -60

echo ""
echo "=== Check if there's any documentation or comments about optional dependencies ==="
grep -r "optional\|depend\|miss" apps/server-core/src/app/module.ts -B2 -A2

echo ""
echo "=== Check actual dependency usage in start methods ==="
rg -A20 "async start.*container" apps/server-core/src/app/modules/cache/module.ts

Repository: authup/authup

Length of output: 3706


Fail fast or emit a warning for unregistered module dependencies.

When a module declares a dependency that isn't registered in the application, the dependency edge is silently skipped (lines 82-84). The module will still start, but if it tries to resolve its missing dependency from the container, it will fail at runtime with a confusing error. For example, HTTPModule depends on LOGGER but will crash when container.resolve(LoggerInjectionKey) is called if LOGGER wasn't registered. This silent failure masks configuration errors. Modules should either fail validation early or emit a clear warning if declared dependencies are missing.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/app/module.ts` around lines 81 - 84, The loop that
checks module.dependsOn currently ignores missing dependencies by returning when
registered.has(dep) is false; change this to surface the problem early for the
module (either throw a ValidationError or emit a clear warning) so missing
dependencies are not silently skipped—specifically update the logic around
module.dependsOn and registered.has(dep) (the block that currently does "if
(!registered.has(dep)) { return; }") to instead either throw a descriptive error
(e.g., include module.name and the missing dep) or call the application's logger
to warn, so callers like HTTPModule that later call
container.resolve(LoggerInjectionKey) will fail fast with a helpful message.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/server-core/src/app/builder.ts`:
- Around line 54-56: The constructor currently creates an empty Map so untouched
module slots are missing when build() iterates only this.slots; update the
ApplicationBuilder constructor (or the build logic) to ensure all known/default
slots are present before build runs—either prepopulate this.slots with entries
for each module key (the same keys that factory.ts expects) or change build() to
iterate a static list of module keys and read overrides from this.slots;
reference ApplicationBuilder.constructor, this.slots, build(), and any withXxx
methods (e.g., withDatabase) so that an explicit false/override only replaces
that slot and untouched modules keep their default implementations.
- Around line 122-145: Split the current generic build method into two overloads
to prevent callers from asserting a concrete Application type when they call
build() with no args: add an overload build<T extends
Application>(ApplicationClass: new (modules?: Module[]) => T): T and a no-arg
overload build(): Application, then keep a single implementation (non-generic)
build(ApplicationClass?: new (modules?: Module[]) => Application): Application
that constructs modules the same way and returns new ApplicationClass(modules)
when provided or new Application(modules) otherwise; update the existing build
method in builder.ts (the build function and references to ApplicationClass,
Module, defaultFactories, and this.slots) to match this overload pattern so the
zero-arg path typesafe-returns Application.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: df7e5119-483e-4a12-8966-c0aa3d768d74

📥 Commits

Reviewing files that changed from the base of the PR and between e9c9970 and be2b850.

📒 Files selected for processing (3)
  • apps/server-core/src/app/builder.ts
  • apps/server-core/src/app/factory.ts
  • apps/server-core/src/app/index.ts

Comment on lines +54 to +56
constructor() {
this.slots = new Map();
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

The builder starts empty, so untouched modules are never defaulted.

build() only walks this.slots. With an empty constructor, new ApplicationBuilder().build() returns an empty app, and a partial override like .withDatabase(false).build() drops every untouched module as well. The current apps/server-core/src/app/factory.ts:15-33 path only works because it touches every slot first.

Suggested fix
     constructor() {
-        this.slots = new Map();
+        this.slots = new Map(
+            Object.keys(defaultFactories).map((name) => [name, undefined]),
+        );
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/app/builder.ts` around lines 54 - 56, The constructor
currently creates an empty Map so untouched module slots are missing when
build() iterates only this.slots; update the ApplicationBuilder constructor (or
the build logic) to ensure all known/default slots are present before build
runs—either prepopulate this.slots with entries for each module key (the same
keys that factory.ts expects) or change build() to iterate a static list of
module keys and read overrides from this.slots; reference
ApplicationBuilder.constructor, this.slots, build(), and any withXxx methods
(e.g., withDatabase) so that an explicit false/override only replaces that slot
and untouched modules keep their default implementations.

Comment thread apps/server-core/src/app/builder.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
apps/server-core/test/setup.ts (1)

25-32: Prefer constructing the bootstrap app inside setup().

Application keeps mutable container and startup state, so sharing one module-level instance makes repeated setup runs depend on the previous run's state. Building a fresh app inside setup() keeps test bootstrap isolated.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/setup.ts` around lines 25 - 32, The module-level
ApplicationBuilder instance should be created inside the exported setup()
function to avoid sharing mutable Application state across test runs; move the
current ApplicationBuilder chain (the code that constructs app with
ApplicationBuilder().withConfig().withLogger().withDatabase(new
TestDatabaseModuleBase()).withProvisioning(new ProvisionerModule([ new
DefaultProvisioningSource() ])).build()) into the body of setup(), create a
fresh local app there, use that app for whatever initialization/setup/teardown
setup() performs, and remove the module-level app variable so each call to
setup() constructs and returns an isolated Application instance.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/server-core/src/cli/commands/migration.ts`:
- Around line 112-145: The code currently uses a hard-coded connections array
and unconditionally calls dropDatabase/createDatabase, which can delete
unrelated local DBs; replace the fixed connections with the environment-aware
builder (use optionsBuilder.buildWithEnv() or read config.db) so you generate
migration targets from the configured deployment, and add a safety guard around
destructive operations (do not call dropDatabase/createDatabase unless a
deliberate CLI flag is provided, e.g. --force or an explicit --target that
matches the resolved DataSourceOptions.type); update the loop that uses
connections, directoryPath and calls dropDatabase/createDatabase so it iterates
only over environment-configured targets and checks the new confirmation flag
before calling dropDatabase/createDatabase.
- Around line 93-107: The DataSource creation/usage blocks must guarantee
cleanup: wrap each new DataSource(...) flow (the one that calls initialize()
then undoLastMigration()/showMigrations()/runMigrations(), and the second
instance inside the loop) in a try/finally so destroy() always runs;
specifically call await dataSource.initialize() inside the try and put await
dataSource.destroy() inside the finally, leaving the migration calls
(undoLastMigration, showMigrations, runMigrations) inside the try body so any
thrown errors still trigger destroy().

In `@apps/server-core/src/cli/commands/reset.ts`:
- Around line 24-25: The reset command calls Application.reset() but that method
is currently empty (Application.reset in module.ts) so the CLI reports success
without changing state; implement Application.reset to perform the actual
teardown/reset work (for example iterate registered modules and invoke their
reset/cleanup methods or call the same logic used by Application.stop/teardown),
and ensure the CLI path in reset.ts (where app.start() and app.reset() are
called) only returns success if Application.reset completes without error;
update Application.reset to throw on failure or return a meaningful result so
reset.ts can detect and surface errors.

---

Nitpick comments:
In `@apps/server-core/test/setup.ts`:
- Around line 25-32: The module-level ApplicationBuilder instance should be
created inside the exported setup() function to avoid sharing mutable
Application state across test runs; move the current ApplicationBuilder chain
(the code that constructs app with
ApplicationBuilder().withConfig().withLogger().withDatabase(new
TestDatabaseModuleBase()).withProvisioning(new ProvisionerModule([ new
DefaultProvisioningSource() ])).build()) into the body of setup(), create a
fresh local app there, use that app for whatever initialization/setup/teardown
setup() performs, and remove the module-level app variable so each call to
setup() constructs and returns an isolated Application instance.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 492ca919-6e9a-4a10-af00-c7a29b9cfd95

📥 Commits

Reviewing files that changed from the base of the PR and between be2b850 and 4afe07a.

📒 Files selected for processing (6)
  • apps/server-core/src/cli/commands/healthcheck.ts
  • apps/server-core/src/cli/commands/migration.ts
  • apps/server-core/src/cli/commands/reset.ts
  • apps/server-core/src/cli/commands/swagger.ts
  • apps/server-core/test/app/factory.ts
  • apps/server-core/test/setup.ts

Comment on lines +112 to +145
const connections : DataSourceOptions[] = [
{
type: 'postgres',
database: 'migrations',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'start123',
},
{
type: 'mysql',
database: 'migrations',
host: 'localhost',
port: 3306,
username: 'root',
password: 'start123',
},
];

const baseDirectory = transformFilePath(
path.join(CODE_PATH, 'adapters', 'database', 'migrations'),
'./src',
'./dist',
);

const timestamp = Date.now();

for (let i = 0; i < connections.length; i++) {
const dataSourceOptions = optionsBuilder.buildWith(connections[i]);
const directoryPath = path.join(baseDirectory, dataSourceOptions.type);

await dropDatabase({ options: dataSourceOptions });
await createDatabase({ options: dataSourceOptions, synchronize: false });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

migration generate can drop unrelated local databases.

This branch bypasses config.db / buildWithEnv() and unconditionally calls dropDatabase() for fixed localhost Postgres/MySQL targets named migrations. Running the generic generate command on a developer machine can therefore delete existing local data and generate against a schema that does not match the configured deployment.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/cli/commands/migration.ts` around lines 112 - 145, The
code currently uses a hard-coded connections array and unconditionally calls
dropDatabase/createDatabase, which can delete unrelated local DBs; replace the
fixed connections with the environment-aware builder (use
optionsBuilder.buildWithEnv() or read config.db) so you generate migration
targets from the configured deployment, and add a safety guard around
destructive operations (do not call dropDatabase/createDatabase unless a
deliberate CLI flag is provided, e.g. --force or an explicit --target that
matches the resolved DataSourceOptions.type); update the loop that uses
connections, directoryPath and calls dropDatabase/createDatabase so it iterates
only over environment-configured targets and checks the new confirmation flag
before calling dropDatabase/createDatabase.

Comment on lines +24 to 25
await app.start();
await app.reset();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

reset still reports success without actually resetting anything.

Application.reset() is currently empty in apps/server-core/src/app/module.ts:58-60, so this path now boots the registered modules and exits 0 without changing state. That makes the command misleading and can trigger startup side effects on what looks like a reset run.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/cli/commands/reset.ts` around lines 24 - 25, The reset
command calls Application.reset() but that method is currently empty
(Application.reset in module.ts) so the CLI reports success without changing
state; implement Application.reset to perform the actual teardown/reset work
(for example iterate registered modules and invoke their reset/cleanup methods
or call the same logic used by Application.stop/teardown), and ensure the CLI
path in reset.ts (where app.start() and app.reset() are called) only returns
success if Application.reset completes without error; update Application.reset
to throw on failure or return a meaningful result so reset.ts can detect and
surface errors.

@tada5hi

tada5hi commented Mar 14, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Mar 14, 2026

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/server-core/test/setup.ts (1)

45-53: ⚠️ Potential issue | 🟠 Major

Clean up the LDAP container on bootstrap failures.

If app.start() or app.stop() throws after Line 45, this function exits with the freshly started container still running. That leaves orphaned Docker containers behind on failed setup paths and can make later CI runs flaky.

Suggested failure-path cleanup
     const container = await containerConfig.start();
+    let initialized = false;

-    project.provide('OPENLDAP_CONTAINER_HOST', container.getHost());
-    project.provide('OPENLDAP_CONTAINER_PORT', container.getFirstMappedPort());
-
-    globalThis.OPENLDAP_CONTAINER = container;
-
-    await app.start();
-    await app.stop();
+    try {
+        project.provide('OPENLDAP_CONTAINER_HOST', container.getHost());
+        project.provide('OPENLDAP_CONTAINER_PORT', container.getFirstMappedPort());
+
+        globalThis.OPENLDAP_CONTAINER = container;
+
+        await app.start();
+        await app.stop();
+        initialized = true;
+    } finally {
+        if (!initialized) {
+            await container.stop().catch(() => undefined);
+        }
+    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/setup.ts` around lines 45 - 53, The bootstrap can leave
the LDAP container running if app.start() or app.stop() throws; wrap the
sequence after containerConfig.start() in a try/finally so the container is
always cleaned up on failure: after calling containerConfig.start() and
assigning project.provide(...) and globalThis.OPENLDAP_CONTAINER, run
app.start()/app.stop() inside a try block and in the finally ensure the
container is stopped/removed (call the container instance stop/remove methods or
container.stop()) and clear globalThis.OPENLDAP_CONTAINER so no orphaned
containers remain; reference containerConfig.start(),
globalThis.OPENLDAP_CONTAINER, and app.start()/app.stop() to locate where to add
the try/finally cleanup.
apps/server-core/test/app/factory.ts (1)

20-24: ⚠️ Potential issue | 🔴 Critical

The factory does not consume the injected OpenLDAP endpoint coordinates.

setup.ts lines 47-48 publish OPENLDAP_CONTAINER_HOST and OPENLDAP_CONTAINER_PORT via Vitest's provided context, but buildTestConfig() reads only from process.env through predefined keys in ConfigEnvironmentVariableName. There are no LDAP-related environment variable keys defined in that enum, and the provided context is never synced to process.env. Consequently, .withLdap() at line 48 will initialize with default/stale LDAP settings, not the dynamically provisioned container endpoint.

Either sync the provided values to process.env (with appropriate key names) before calling createTestApplication(), or add an explicit override mechanism to the factory to consume the provided context.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/app/factory.ts` around lines 20 - 24, buildTestConfig()
currently only reads process.env via ConfigEnvironmentVariableName and therefore
ignores the Vitest-provided OPENLDAP_CONTAINER_HOST/OPENLDAP_CONTAINER_PORT
published in setup.ts, causing .withLdap() to use stale defaults; fix by either
(A) syncing the Vitest context values to process.env under the expected keys
before calling createTestApplication() (ensure the keys match
ConfigEnvironmentVariableName), or (B) extend buildTestConfig() to accept an
optional override object (e.g., ldapHost, ldapPort) and apply those values when
normalizing the config so that .withLdap() receives the dynamically provisioned
endpoint; update the test setup to pass the context through the chosen route.
♻️ Duplicate comments (2)
apps/server-core/src/cli/commands/migration.ts (2)

67-83: ⚠️ Potential issue | 🟠 Major

Move initialize() inside try so cleanup is guaranteed.

Line 71 and Line 124 call initialize() before the guarded block. If initialization throws, destroy() is skipped. Keep both initialize() and migration operations inside try, and call destroy() in finally only when initialized.

🔧 Proposed fix
 const dataSource = new DataSource({...});
-await dataSource.initialize();
-
 try {
+    await dataSource.initialize();
     // migration work...
 } finally {
-    await dataSource.destroy();
+    if (dataSource.isInitialized) {
+        await dataSource.destroy();
+    }
 }
#!/bin/bash
set -euo pipefail

file="apps/server-core/src/cli/commands/migration.ts"

echo "== initialize() call sites =="
rg -n "await dataSource\\.initialize\\(\\)" "$file"

echo
echo "== try/finally blocks around migration flows =="
nl -ba "$file" | sed -n '60,150p'

Also applies to: 123-138

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/cli/commands/migration.ts` around lines 67 - 83, The
DataSource.initialize() is called before the try/finally so if initialization
throws dataSource.destroy() is never called; move await dataSource.initialize()
inside the try block that wraps the migration operations (the conditional using
MigrationOperation.REVERT/STATUS/runMigrations()), and ensure
dataSource.destroy() in the finally runs only if initialization succeeded (e.g.,
track an "initialized" flag after await dataSource.initialize() or check
dataSource.isInitialized) so destroy is not invoked on a non-initialized
DataSource; update references to dataSource.initialize(), dataSource.destroy(),
and the block handling MigrationOperation to implement this change.

89-106: ⚠️ Potential issue | 🔴 Critical

generate still has destructive hard-coded DB targets and credentials.

Line 89–Line 106 hard-code local Postgres/MySQL credentials, and Line 120–Line 121 unconditionally drops/recreates DBs. This can wipe unrelated local data when running migration generate.

💡 Proposed direction
- const connections: DataSourceOptions[] = [
-   { type: 'postgres', database: 'migrations', host: 'localhost', ... },
-   { type: 'mysql', database: 'migrations', host: 'localhost', ... },
- ];
+ // Resolve migration target(s) from env/config instead of fixed localhost credentials.
+ const connections: DataSourceOptions[] = [optionsBuilder.buildWithEnv()];

- await dropDatabase({ options: dataSourceOptions });
- await createDatabase({ options: dataSourceOptions, synchronize: false });
+ if (!context.args.force) {
+   throw new Error('Refusing to drop/create database without --force.');
+ }
+ await dropDatabase({ options: dataSourceOptions, ifExist: true });
+ await createDatabase({ options: dataSourceOptions, synchronize: false, ifNotExist: true });

Also applies to: 120-121

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/src/cli/commands/migration.ts` around lines 89 - 106, The
generate command currently hard-codes local DB credentials in the connections
const and unconditionally drops/recreates databases (lines referenced around the
drop/recreate logic), which is dangerous; change generate to accept connection
targets via CLI flags or environment variables (e.g., --db-type, --host, --port,
--user, --password or a DATABASE_URL) and remove hard-coded postgres/mysql
entries from the connections const, and gate any destructive operations (the
unconditional drop/create) behind an explicit confirmation flag (e.g., --force)
or an interactive prompt; update the code paths that perform the drop/recreate
so they only run when a --force flag is passed or when a
DRY_RUN/ALLOW_DESTRUCTIVE env var is true, and document the new flags in the CLI
help text.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/server-core/test/app/http.ts`:
- Around line 30-31: The helper currently force-casts httpServer.address() to
AddressInfo and reads port; change it to guard the return of
httpServer.address() by checking its type and nullability before using .port:
call const address = httpServer.address(); if address === null return a safe
fallback or throw a clear error; if typeof address === "string" handle the
socket-path case (use that string or a suitable base URL for socket listeners);
otherwise treat it as AddressInfo and read address.port to build baseURL; update
uses of address and baseURL accordingly so no force-cast is performed.

---

Outside diff comments:
In `@apps/server-core/test/app/factory.ts`:
- Around line 20-24: buildTestConfig() currently only reads process.env via
ConfigEnvironmentVariableName and therefore ignores the Vitest-provided
OPENLDAP_CONTAINER_HOST/OPENLDAP_CONTAINER_PORT published in setup.ts, causing
.withLdap() to use stale defaults; fix by either (A) syncing the Vitest context
values to process.env under the expected keys before calling
createTestApplication() (ensure the keys match ConfigEnvironmentVariableName),
or (B) extend buildTestConfig() to accept an optional override object (e.g.,
ldapHost, ldapPort) and apply those values when normalizing the config so that
.withLdap() receives the dynamically provisioned endpoint; update the test setup
to pass the context through the chosen route.

In `@apps/server-core/test/setup.ts`:
- Around line 45-53: The bootstrap can leave the LDAP container running if
app.start() or app.stop() throws; wrap the sequence after
containerConfig.start() in a try/finally so the container is always cleaned up
on failure: after calling containerConfig.start() and assigning
project.provide(...) and globalThis.OPENLDAP_CONTAINER, run
app.start()/app.stop() inside a try block and in the finally ensure the
container is stopped/removed (call the container instance stop/remove methods or
container.stop()) and clear globalThis.OPENLDAP_CONTAINER so no orphaned
containers remain; reference containerConfig.start(),
globalThis.OPENLDAP_CONTAINER, and app.start()/app.stop() to locate where to add
the try/finally cleanup.

---

Duplicate comments:
In `@apps/server-core/src/cli/commands/migration.ts`:
- Around line 67-83: The DataSource.initialize() is called before the
try/finally so if initialization throws dataSource.destroy() is never called;
move await dataSource.initialize() inside the try block that wraps the migration
operations (the conditional using
MigrationOperation.REVERT/STATUS/runMigrations()), and ensure
dataSource.destroy() in the finally runs only if initialization succeeded (e.g.,
track an "initialized" flag after await dataSource.initialize() or check
dataSource.isInitialized) so destroy is not invoked on a non-initialized
DataSource; update references to dataSource.initialize(), dataSource.destroy(),
and the block handling MigrationOperation to implement this change.
- Around line 89-106: The generate command currently hard-codes local DB
credentials in the connections const and unconditionally drops/recreates
databases (lines referenced around the drop/recreate logic), which is dangerous;
change generate to accept connection targets via CLI flags or environment
variables (e.g., --db-type, --host, --port, --user, --password or a
DATABASE_URL) and remove hard-coded postgres/mysql entries from the connections
const, and gate any destructive operations (the unconditional drop/create)
behind an explicit confirmation flag (e.g., --force) or an interactive prompt;
update the code paths that perform the drop/recreate so they only run when a
--force flag is passed or when a DRY_RUN/ALLOW_DESTRUCTIVE env var is true, and
document the new flags in the CLI help text.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0f58d846-4e62-4c6c-8077-c0172a104588

📥 Commits

Reviewing files that changed from the base of the PR and between 4afe07a and 693d545.

📒 Files selected for processing (11)
  • apps/server-core/src/app/builder.ts
  • apps/server-core/src/app/modules/database/module.ts
  • apps/server-core/src/app/modules/oauth2/module.ts
  • apps/server-core/src/cli/commands/migration.ts
  • apps/server-core/test/app/database.ts
  • apps/server-core/test/app/factory.ts
  • apps/server-core/test/app/http.ts
  • apps/server-core/test/app/index.ts
  • apps/server-core/test/app/module.ts
  • apps/server-core/test/setup.ts
  • apps/server-core/test/unit/modules/provisioning.spec.ts

Comment on lines +30 to +31
const address = httpServer.address() as AddressInfo;
const baseURL = `http://localhost:${address.port}`;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# First, locate and examine the test file
find . -type f -name "http.ts" -path "*/test/app/*" | head -20

Repository: authup/authup

Length of output: 92


🏁 Script executed:

# Also search for the HTTP module file
find . -type f -path "*/src/app/modules/http/module.ts" | head -5

Repository: authup/authup

Length of output: 106


🏁 Script executed:

cat -n ./apps/server-core/test/app/http.ts

Repository: authup/authup

Length of output: 1611


🏁 Script executed:

cat -n ./apps/server-core/src/app/modules/http/module.ts | head -100

Repository: authup/authup

Length of output: 3889


🏁 Script executed:

cat -n ./apps/server-core/test/app/module.ts

Repository: authup/authup

Length of output: 658


Guard server.address() before reading port.

Line 30 force-casts away string | null branches without checking. If the client getter is accessed before the server listens, after shutdown, or against a socket-bound listener, this will throw or produce a malformed URL. The HTTP module at apps/server-core/src/app/modules/http/module.ts:72-79 already handles all three branches, so this helper should do the same.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/app/http.ts` around lines 30 - 31, The helper currently
force-casts httpServer.address() to AddressInfo and reads port; change it to
guard the return of httpServer.address() by checking its type and nullability
before using .port: call const address = httpServer.address(); if address ===
null return a safe fallback or throw a clear error; if typeof address ===
"string" handle the socket-path case (use that string or a suitable base URL for
socket listeners); otherwise treat it as AddressInfo and read address.port to
build baseURL; update uses of address and baseURL accordingly so no force-cast
is performed.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
apps/server-core/test/app/database.ts (1)

61-63: Prefer omitting setup instead of a no-op to keep default DB existence safety.

Providing a no-op overrides DatabaseModule’s default setup behavior. Omitting setup keeps the “create-if-missing” fallback and reduces coupling to global setup ordering.

Suggested refactor
 export function createTestDatabaseModuleForSuite(): DatabaseModule {
     return new DatabaseModule({
         prepareBuild: prepareTestBuild,
-        async setup() {
-            // do nothing — DB already exists from global setup
-        },
         async migrate(_container, dataSource) {
             await dataSource.synchronize();
         },
     });
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server-core/test/app/database.ts` around lines 61 - 63, The no-op async
setup method in this test subclass overrides DatabaseModule's default setup
behavior and should be removed; delete the async setup() { /* do nothing */ }
method so the test uses DatabaseModule's built-in create-if-missing DB
setup/fallback instead of overriding it.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/server-core/test/app/database.ts`:
- Around line 21-23: The module currently returns silently when config.env !==
EnvironmentName.TEST which can allow dangerous DB tear-downs if env is
misconfigured; change this to fail fast by throwing an explicit error (or
calling process.exit(1)) with a clear message that the environment is not TEST
(referencing config.env and EnvironmentName.TEST) so the process stops
immediately instead of continuing with destructive DB setup.

---

Nitpick comments:
In `@apps/server-core/test/app/database.ts`:
- Around line 61-63: The no-op async setup method in this test subclass
overrides DatabaseModule's default setup behavior and should be removed; delete
the async setup() { /* do nothing */ } method so the test uses DatabaseModule's
built-in create-if-missing DB setup/fallback instead of overriding it.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3204ada7-df5c-4f2f-99a8-3ea5e52c1381

📥 Commits

Reviewing files that changed from the base of the PR and between 693d545 and ddda936.

📒 Files selected for processing (2)
  • .claude/skills/investigate-pr-comments/SKILL.md
  • apps/server-core/test/app/database.ts
✅ Files skipped from review due to trivial changes (1)
  • .claude/skills/investigate-pr-comments/SKILL.md

Comment thread apps/server-core/test/app/database.ts Resolved
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.

Feature: Application Bootstraping

1 participant