Skip to content

refactor: replace internal DI system with eldin package - #2945

Merged
tada5hi merged 2 commits into
masterfrom
2944-di
Mar 27, 2026
Merged

tada5hi merged 2 commits into
masterfrom
2944-di

Conversation

@tada5hi

@tada5hi tada5hi commented Mar 26, 2026 •

Copy link
Copy Markdown
Collaborator

closes #2944

Summary by CodeRabbit

  • New Features

    • Added eldin as a runtime dependency for DI.
  • Refactor

    • Replaced the custom DI implementation with eldin; module interfaces and lifecycle APIs now use eldin container types.
    • Switched symbol-based injection keys to type-safe typed tokens across the app.
  • Documentation

    • Clarified test-running commands and when global test setup is required.
  • Chores

    • Expanded CI workflow permissions to include id-token write for releases.

@coderabbitai

coderabbitai Bot commented Mar 26, 2026 •

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 48434081-71b1-4e75-81ad-412d43e9fcef

📥 Commits

Reviewing files that changed from the base of the PR and between 2917094 and c83c41e.

📒 Files selected for processing (1)
  • apps/server-core/src/app/modules/authentication/module.ts

📝 Walkthrough

Walkthrough

Migrates the project DI from a custom DependencyContainer/IDIContainer to the external eldin library: replaces Module with IModule, converts many Symbol(...) injection keys to TypedToken<T>, updates container types and resolve calls across modules/tests/CLI, and deletes the legacy DI implementation and types. Adds eldin dependency and grants id-token: write in release workflow; docs updated for testing guidance.

Changes

Cohort / File(s) Summary
DI Core Removal
apps/server-core/src/core/di/... (module.ts, provider/*.ts, types.ts, provider/index.ts)
Deleted the custom DI implementation, provider typedefs, type-guards, and IDIContainer/related types and barrel exports.
Public Core Exports
apps/server-core/src/core/index.ts, apps/server-core/src/core/di/index.ts
Removed re-exports exposing the legacy DI surface.
Injection Key Typing
apps/server-core/src/app/modules/.../constants.ts, apps/server-core/src/core/identity/provider/authentication/constants.ts, apps/server-core/src/core/identity/provider/authentication/constants.ts
Replaced untyped Symbol('...') keys with new TypedToken<T>('...') for many modules (authentication, cache, config, database, http, identity, ldap, logger, mail, oauth2, vault, etc.).
Module Interfaces / Container Types
apps/server-core/src/app/modules/types.ts, many apps/server-core/src/app/modules/*/module.ts files, apps/server-core/src/app/module.ts, apps/server-core/src/app/builder.ts, apps/server-core/src/app/types.ts
Renamed/shifted module interfaces to IModule, updated method signatures to accept IContainer from eldin (start/stop/prepareBuild/etc.), and updated application/builder types to use IModule/IContainer.
Container API Changes at Call Sites
apps/server-core/src/app/modules/.../module.ts, apps/server-core/src/app/modules/http/modules/{controller,middleware}.ts, apps/server-core/src/app/modules/provisioning/sources/.../module.ts, apps/server-core/src/cli/*, apps/server-core/test/*
Removed explicit generic container.resolve<T>(...) usage; switched optional lookups from safeResolve to tryResolve; adapted registrations/resolves to rely on TypedToken<T> inference.
HTTP Wiring Bulk Update
apps/server-core/src/app/modules/http/modules/controller.ts, apps/server-core/src/app/modules/http/modules/middleware.ts
Updated ~30+ method signatures to accept IContainer and removed many explicit type-only imports and generic resolves; runtime wiring preserved.
Provisioning Sources & Types
apps/server-core/src/core/provisioning/types.ts, apps/server-core/src/app/modules/provisioning/sources/*/module.ts
IProvisioningSource.load and related source load signatures now accept IContainer; resolves simplified.
Package + Workflow + Docs
apps/server-core/package.json, .github/workflows/release.yml, .agents/testing.md
Added runtime dependency eldin@^1.1.0; added id-token: write workflow permission; clarified Vitest config/test-run guidance in docs.
Tests Updated
apps/server-core/test/app/database.ts, apps/server-core/test/unit/modules/provisioning.spec.ts
Tests switched from DependencyContainer/IDIContainer to Container/IContainer from eldin and updated resolve call sites accordingly.

Sequence Diagram(s)

sequenceDiagram
  participant CLI as CLI / Startup
  participant App as Application / Builder
  participant Container as eldin.Container (IContainer)
  participant Module as IModule (many modules)
  CLI->>App: instantiate builder
  App->>Container: new Container()
  App->>Module: addModule(IModule)
  App->>Module: buildModules()
  App->>Module: start(container: IContainer)
  Module->>Container: container.resolve(TypedToken)
  Container-->>Module: instance / tryResolve result
  Module-->>Container: container.register(TypedToken, value/factory)
  Container-->>App: services available for other modules
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Poem

🐰 From symbols bare to tokens typed,

I hopped through code where types were swiped.
With eldin's chest I neatly store,
Resolved and shared forevermore.
A little hop — DI refined, hooray! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

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.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'refactor: replace internal DI system with eldin package' clearly and concisely describes the main change: replacing the internal dependency injection system with an external package.
Linked Issues check ✅ Passed The pull request successfully implements Phase A objectives from issue #2944: replaces the internal DI system with eldin (external TypedToken-based package), uses IContainer interface, removes useFactory/useValue split, replaces AuthupError with ContainerError, and renames types for consistency.
Out of Scope Changes check ✅ Passed All changes are directly related to the DI system refactoring objective. The addition of the 'eldin' dependency, migration from IDIContainer to IContainer, TypedToken conversions for injection keys, and removal of internal DI infrastructure are all in-scope and necessary for the refactoring.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 2944-di

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.

@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/src/app/modules/http/module.ts (1)

86-93: ⚠️ Potential issue | 🔴 Critical

Bug: this.instance is never assigned, causing stop() to be a no-op.

The stop() method checks if (!this.instance) and returns early, but this.instance is never assigned in start(). The server is created and registered in the container (Line 79) but never stored in the class field. This means stop() will always return early without actually closing the server.

🐛 Proposed fix
         container.register(HTTPInjectionKey.Server, { useValue: server });
+        this.instance = server;
 
         logger.debug('Started http server.');
🤖 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 86 - 93, The
stop() method is a no-op because this.instance is never set in start(); modify
the start() flow that creates and registers the server (the code that registers
HTTPInjectionKey.Server and returns the server) to also assign the created
server to the class field this.instance so stop() can close it; ensure the
instance assigned is the same object registered under HTTPInjectionKey.Server
and that start()/stop() consistently use this.instance for lifecycle management.
apps/server-core/src/app/modules/vault/module.ts (1)

44-49: ⚠️ Potential issue | 🟡 Minor

Hardcoded default credentials in source code.

The default connection string start123@http://127.0.0.1:8090/v1/ contains what appears to be a credential (start123). Even for local development defaults, embedding credentials in source code is a security concern as they may be committed to version control and could leak.

Consider moving this to environment variables or a configuration file that is not committed to the repository.

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

In `@apps/server-core/src/app/modules/vault/module.ts` around lines 44 - 49, The
createClient method currently injects a hardcoded credential in the
connectionString passed to createVaultClient; remove the embedded credential and
read the connection string (or separate username/credential) from a
non-committed configuration source such as environment variables or a config
loader instead. Update the createClient(data: string | boolean) implementation
to construct connectionString from process.env (or a ConfigService) and fallback
to a safe local URL without credentials if needed, then pass that value into
createVaultClient; ensure references to connectionString, createClient, and
createVaultClient are updated accordingly and add a clear error/log when the
required env var is missing.
🧹 Nitpick comments (4)
.github/workflows/release.yml (1)

17-17: Change appears unrelated to PR objectives, but the addition is valid.

The id-token: write permission is typically added to enable npm provenance, which is a good security practice that creates a verifiable link between published packages and their source repository. However, this change seems unrelated to the DI system refactoring described in the PR objectives.

If this is intentional (e.g., the eldin package or updated monoship requires provenance), please confirm. Otherwise, consider splitting this into a separate PR for clearer change tracking.

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

In @.github/workflows/release.yml at line 17, The workflow change adds the
GitHub Actions permission "id-token: write" (the id-token: write line in
.github/workflows/release.yml) which is unrelated to the DI refactor; either
confirm the intent in this PR by adding a brief note in the PR description
referencing why npm provenance or package requirements (e.g., eldIn/monoship)
need it, or move that permission change into a separate focused PR; update the
PR description or split the commit accordingly and ensure the workflow change is
documented so reviewers can see it’s intentional.
apps/server-core/package.json (1)

65-65: Remove unused tsyringe dependency.

tsyringe is no longer referenced in the codebase and can be safely removed from apps/server-core/package.json to reduce dependency surface and maintenance overhead.

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

In `@apps/server-core/package.json` at line 65, Remove the unused "tsyringe"
dependency from the package.json dependencies (delete the "tsyringe" entry) and
then reinstall dependencies (npm/yarn/pnpm install) so lockfiles are updated;
also run a quick search for any remaining imports of "tsyringe" (e.g., import {
... } from 'tsyringe') and remove or refactor them if found to ensure no runtime
or build errors.
apps/server-core/src/app/modules/http/modules/controller.ts (2)

238-246: Consider caching IdentityPermissionProvider to avoid repeated instantiation.

createIdentityPermissionProvider is called 10 times across various factory methods, each time creating new repository instances. While this doesn't introduce a bug, it's inefficient.

Consider registering IdentityPermissionProvider in the DI container or caching it at the module level:

♻️ Potential optimization
 export class HTTPControllerModule {
+    private identityPermissionProvider?: IdentityPermissionProvider;
+
+    getIdentityPermissionProvider(container: IContainer): IdentityPermissionProvider {
+        if (!this.identityPermissionProvider) {
+            this.identityPermissionProvider = this.createIdentityPermissionProvider(container);
+        }
+        return this.identityPermissionProvider;
+    }
+
     createIdentityPermissionProvider(container: IContainer) {

Then replace all this.createIdentityPermissionProvider(container) calls with this.getIdentityPermissionProvider(container).

🤖 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/modules/controller.ts` around lines 238
- 246, createIdentityPermissionProvider currently instantiates new repositories
each time it’s called (observed in createIdentityPermissionProvider), causing
repeated allocations; change this by caching or registering a singleton: either
register IdentityPermissionProvider in your DI container under a unique key when
first requested or add a module-level getIdentityPermissionProvider(container)
that lazily creates and stores a single IdentityPermissionProvider instance
(constructed with ClientRepository, UserRepository, RobotRepository,
RoleRepository) and return that on subsequent calls, then replace all calls to
this.createIdentityPermissionProvider(container) with
this.getIdentityPermissionProvider(container) (or resolve from the container) to
ensure only one shared instance is used.

641-647: Minor: Repository<any> loses type safety.

Line 643 uses Repository<any>, which sacrifices compile-time type checking. If a corresponding interface type exists (e.g., IdentityProviderRoleMapping), consider using it for better type safety. This is a pre-existing pattern, so addressing it is optional.

🤖 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/modules/controller.ts` around lines 641
- 647, The Repository is currently typed as Repository<any> in
createIdentityProviderRoleController which loses compile-time safety; change the
DI resolve to use the concrete entity/interface type (e.g.,
Repository<IdentityProviderRoleMapping>) instead of any, update the generic on
IdentityProviderRoleMappingRepositoryAdapter usage if needed, and add/import the
IdentityProviderRoleMapping type so the
container.resolve<Repository<IdentityProviderRoleMapping>>(IdentityProviderRoleMappingEntity)
provides proper typing for repository and downstream code (referencing
createIdentityProviderRoleController,
IdentityProviderRoleMappingRepositoryAdapter, and
IdentityProviderRoleMappingEntity).
🤖 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/modules/authentication/module.ts`:
- Around line 47-49: The SessionManager factory resolves ConfigInjectionKey but
the registration's dependsOn array does not include ModuleName.CONFIG; update
the provider registration that constructs new SessionManager to add
ModuleName.CONFIG to its dependsOn so config is guaranteed to be initialized
before the factory runs (locate the provider that calls
c.resolve(ConfigInjectionKey) and add ModuleName.CONFIG to its dependsOn
alongside any existing dependencies).

---

Outside diff comments:
In `@apps/server-core/src/app/modules/http/module.ts`:
- Around line 86-93: The stop() method is a no-op because this.instance is never
set in start(); modify the start() flow that creates and registers the server
(the code that registers HTTPInjectionKey.Server and returns the server) to also
assign the created server to the class field this.instance so stop() can close
it; ensure the instance assigned is the same object registered under
HTTPInjectionKey.Server and that start()/stop() consistently use this.instance
for lifecycle management.

In `@apps/server-core/src/app/modules/vault/module.ts`:
- Around line 44-49: The createClient method currently injects a hardcoded
credential in the connectionString passed to createVaultClient; remove the
embedded credential and read the connection string (or separate
username/credential) from a non-committed configuration source such as
environment variables or a config loader instead. Update the createClient(data:
string | boolean) implementation to construct connectionString from process.env
(or a ConfigService) and fallback to a safe local URL without credentials if
needed, then pass that value into createVaultClient; ensure references to
connectionString, createClient, and createVaultClient are updated accordingly
and add a clear error/log when the required env var is missing.

---

Nitpick comments:
In @.github/workflows/release.yml:
- Line 17: The workflow change adds the GitHub Actions permission "id-token:
write" (the id-token: write line in .github/workflows/release.yml) which is
unrelated to the DI refactor; either confirm the intent in this PR by adding a
brief note in the PR description referencing why npm provenance or package
requirements (e.g., eldIn/monoship) need it, or move that permission change into
a separate focused PR; update the PR description or split the commit accordingly
and ensure the workflow change is documented so reviewers can see it’s
intentional.

In `@apps/server-core/package.json`:
- Line 65: Remove the unused "tsyringe" dependency from the package.json
dependencies (delete the "tsyringe" entry) and then reinstall dependencies
(npm/yarn/pnpm install) so lockfiles are updated; also run a quick search for
any remaining imports of "tsyringe" (e.g., import { ... } from 'tsyringe') and
remove or refactor them if found to ensure no runtime or build errors.

In `@apps/server-core/src/app/modules/http/modules/controller.ts`:
- Around line 238-246: createIdentityPermissionProvider currently instantiates
new repositories each time it’s called (observed in
createIdentityPermissionProvider), causing repeated allocations; change this by
caching or registering a singleton: either register IdentityPermissionProvider
in your DI container under a unique key when first requested or add a
module-level getIdentityPermissionProvider(container) that lazily creates and
stores a single IdentityPermissionProvider instance (constructed with
ClientRepository, UserRepository, RobotRepository, RoleRepository) and return
that on subsequent calls, then replace all calls to
this.createIdentityPermissionProvider(container) with
this.getIdentityPermissionProvider(container) (or resolve from the container) to
ensure only one shared instance is used.
- Around line 641-647: The Repository is currently typed as Repository<any> in
createIdentityProviderRoleController which loses compile-time safety; change the
DI resolve to use the concrete entity/interface type (e.g.,
Repository<IdentityProviderRoleMapping>) instead of any, update the generic on
IdentityProviderRoleMappingRepositoryAdapter usage if needed, and add/import the
IdentityProviderRoleMapping type so the
container.resolve<Repository<IdentityProviderRoleMapping>>(IdentityProviderRoleMappingEntity)
provides proper typing for repository and downstream code (referencing
createIdentityProviderRoleController,
IdentityProviderRoleMappingRepositoryAdapter, and
IdentityProviderRoleMappingEntity).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 158be425-9600-44b9-9f83-a26988febe11

📥 Commits

Reviewing files that changed from the base of the PR and between 41e28c0 and 2917094.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (51)
  • .agents/testing.md
  • .github/workflows/release.yml
  • apps/server-core/package.json
  • apps/server-core/src/app/builder.ts
  • apps/server-core/src/app/module.ts
  • apps/server-core/src/app/modules/authentication/constants.ts
  • apps/server-core/src/app/modules/authentication/module.ts
  • apps/server-core/src/app/modules/cache/constants.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/constants.ts
  • apps/server-core/src/app/modules/config/module.ts
  • apps/server-core/src/app/modules/database/constants.ts
  • apps/server-core/src/app/modules/database/module.ts
  • apps/server-core/src/app/modules/http/constants.ts
  • apps/server-core/src/app/modules/http/module.ts
  • apps/server-core/src/app/modules/http/modules/controller.ts
  • apps/server-core/src/app/modules/http/modules/middleware.ts
  • apps/server-core/src/app/modules/identity/constants.ts
  • apps/server-core/src/app/modules/identity/module.ts
  • apps/server-core/src/app/modules/ldap/constants.ts
  • apps/server-core/src/app/modules/ldap/module.ts
  • apps/server-core/src/app/modules/logger/constants.ts
  • apps/server-core/src/app/modules/logger/module.ts
  • apps/server-core/src/app/modules/mail/constants.ts
  • apps/server-core/src/app/modules/mail/module.ts
  • apps/server-core/src/app/modules/oauth2/constants.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/provisioning/sources/composite/module.ts
  • apps/server-core/src/app/modules/provisioning/sources/default/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/constants.ts
  • apps/server-core/src/app/modules/vault/module.ts
  • apps/server-core/src/app/types.ts
  • apps/server-core/src/cli/commands/healthcheck.ts
  • apps/server-core/src/cli/commands/migration.ts
  • apps/server-core/src/cli/commands/swagger.ts
  • apps/server-core/src/core/di/index.ts
  • apps/server-core/src/core/di/module.ts
  • apps/server-core/src/core/di/provider/factory.ts
  • apps/server-core/src/core/di/provider/index.ts
  • apps/server-core/src/core/di/provider/value.ts
  • apps/server-core/src/core/di/types.ts
  • apps/server-core/src/core/identity/provider/authentication/constants.ts
  • apps/server-core/src/core/index.ts
  • apps/server-core/src/core/provisioning/types.ts
  • apps/server-core/test/app/database.ts
  • apps/server-core/test/unit/modules/provisioning.spec.ts
💤 Files with no reviewable changes (7)
  • apps/server-core/src/core/di/index.ts
  • apps/server-core/src/core/index.ts
  • apps/server-core/src/core/di/provider/index.ts
  • apps/server-core/src/core/di/provider/value.ts
  • apps/server-core/src/core/di/provider/factory.ts
  • apps/server-core/src/core/di/types.ts
  • apps/server-core/src/core/di/module.ts

@tada5hi
tada5hi merged commit bc08cc9 into master Mar 27, 2026
2 checks passed
@tada5hi
tada5hi deleted the 2944-di branch March 27, 2026 09:20
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.

refactor: evolve DI system for extraction as standalone library

1 participant