Repository navigation
refactor!: restructure server-kit hub-style & replace singletons with DI - #3112
Conversation
Mirror PrivateAIM/hub's server-kit design:
- server-kit: flatten services/{cache,logger,redis,vault} to top-level
folders (module.ts/types.ts/index.ts convention), rename type.ts ->
types.ts, drop the singa-based logger & vault singletons (useLogger,
setLogger(Factory), isLoggerUsable, vault accessors) and the singa dep.
- Logger is now a winston-shaped structural type; consumers no longer
depend on winston types.
- domain-event: DomainEventPublisher gains { logger } ctx, register()
and safePublish() (event-bus failures are logged, never fail the
originating transaction); redis/socket publishers become
IDomainEventHandlers under domain-event/handlers/.
- server-core: logger is injected via DI (middlewares, RealmService,
WebClientProvisioner) instead of useLogger(); new declarative
EntitySubscriber base (hub BaseSubscriber pattern) replaces 22
hand-written TypeORM subscribers; DatabaseModule registers the
publisher in the container and injects it via setPublisher() after
dataSource.initialize(); event-publisher & data-source singa
singletons deleted.
- typeorm-extension global registry removed: identity-provider
mapper/account repositories and OAuth2KeyRepository take DataSource
via constructor; setDataSource/useDataSource have no call sites left.
- Fix dead cache-invalidation keys: permission afterRemove unprefixed
key, policy afterUpdate REALM->POLICY prefix, scope dead USER key
(dropped); dedupe same-realm event destinations.
BREAKING CHANGE: @authup/server-kit no longer exports useLogger /
setLogger / setLoggerFactory / isLoggerUsable / vault singleton
accessors; DomainEventRedisPublisher/DomainEventSocketPublisher are
renamed to DomainEventRedisHandler/DomainEventSocketHandler (mount ->
register); Logger is a structural type instead of winston's Logger.
📝 WalkthroughWalkthroughThis PR eliminates global singleton patterns from the Authup framework by migrating to constructor-based dependency injection. It removes the ChangesSingleton Infrastructure Removal and Dependency Cleanup
Domain Event Handler Refactoring
Declarative Entity Subscriber Base Class
Dependency Injection Wiring
Documentation
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
authup
@authup/client-web
@authup/server-core
@authup/access
@authup/client-web-kit
@authup/client-web-kit-theme
@authup/client-web-nuxt
@authup/client-web-theme
@authup/core-http-kit
@authup/core-kit
@authup/core-realtime-kit
@authup/errors
@authup/i18n
@authup/kit
@authup/server-adapter-kit
@authup/server-adapter-node
@authup/server-adapter-socket-io
@authup/server-adapter-web
@authup/server-kit
@authup/server-test-kit
@authup/specs
commit: |
There was a problem hiding this comment.
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/provisioning/module.ts (1)
93-95:⚠️ Potential issue | 🟠 Major | ⚡ Quick winDeclare
ModuleName.LOGGERas a module dependency before resolvingLoggerInjectionKey.At Line 245, setup now requires
LoggerInjectionKey, but Line 94 does not includeModuleName.LOGGER. This can break startup ordering and throw during provisioning setup.Proposed fix
constructor(sources: IProvisioningSource[] = []) { this.name = ModuleName.PROVISIONING; - this.dependencies = [ModuleName.CONFIG, ModuleName.DATABASE]; + this.dependencies = [ModuleName.CONFIG, ModuleName.DATABASE, ModuleName.LOGGER]; this.sources = sources; }Also applies to: 245-245
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/app/modules/provisioning/module.ts` around lines 93 - 95, The ModuleName.LOGGER dependency is missing from the provisioning module's dependency list which causes LoggerInjectionKey resolution during setup (in ModuleName.PROVISIONING's provisioning setup code) to race; update the dependencies array in module.ts (where this.name = ModuleName.PROVISIONING and this.dependencies = [...]) to include ModuleName.LOGGER alongside ModuleName.CONFIG and ModuleName.DATABASE so the logger module is initialized before LoggerInjectionKey is resolved in the setup logic.apps/server-core/src/app/modules/database/module.ts (1)
96-109:⚠️ Potential issue | 🟠 Major | ⚡ Quick winEnsure teardown cleanup runs even when
DataSource.destroy()fails.At Line 99, a thrown destroy error skips later cleanup, leaving
DatabaseInjectionKey.DomainEventPublisherregistered andeventRedisClientundisconnected. Move unregister/disconnect into afinallyblock.Suggested fix
async teardown(container: IContainer): Promise<void> { - const dataSource = container.tryResolve(DatabaseInjectionKey.DataSource); - if (dataSource.success) { - await dataSource.data.destroy(); - - container.unregister(DatabaseInjectionKey.DataSource); - } - - container.unregister(DatabaseInjectionKey.DomainEventPublisher); - - if (this.eventRedisClient) { - this.eventRedisClient.disconnect(); - this.eventRedisClient = undefined; - } + try { + const dataSource = container.tryResolve(DatabaseInjectionKey.DataSource); + if (dataSource.success) { + await dataSource.data.destroy(); + container.unregister(DatabaseInjectionKey.DataSource); + } + } finally { + container.unregister(DatabaseInjectionKey.DomainEventPublisher); + if (this.eventRedisClient) { + await this.eventRedisClient.disconnect(); + this.eventRedisClient = undefined; + } + } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/server-core/src/app/modules/database/module.ts` around lines 96 - 109, The teardown method can bail out if dataSource.data.destroy() throws, preventing cleanup; modify teardown in the module.ts to wrap the destroy call in a try/finally (or try/catch/finally) so that container.unregister(DatabaseInjectionKey.DomainEventPublisher) and the eventRedisClient.disconnect()/undefined assignment always run in the finally block, while still awaiting DataSource.destroy() and rethrowing or logging errors as appropriate; reference the teardown function, DatabaseInjectionKey.DataSource, DatabaseInjectionKey.DomainEventPublisher, eventRedisClient, and DataSource.destroy() when making the change.
🧹 Nitpick comments (1)
packages/server-kit/src/domain-event/module.ts (1)
59-67: 💤 Low valueConsider simpler iteration syntax.
The
while(true)loop with manual iterator is functionally correct but verbose. Afor...ofloop would be more idiomatic.Suggested simplification
- const handlers = this.handlers.values(); - while (true) { - const it = handlers.next(); - if (it.done) { - return; - } - - await it.value.handle(ctx); - } + for (const handler of this.handlers) { + await handler.handle(ctx); + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/server-kit/src/domain-event/module.ts` around lines 59 - 67, The loop using an explicit iterator over this.handlers.values() (variables: handlers, it) is verbose; replace the manual while(true) iterator in the method with an idiomatic for...of over this.handlers.values() and await each handler.handle(ctx) inside the loop (keep the same await semantics and early return behavior by simply finishing the loop). This simplifies the code while preserving behavior for the handlers iteration.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/server-kit/src/domain-event/handlers/socket/module.ts`:
- Around line 23-24: The handler is mutating the shared
DomainEventPublishContext by assigning ctx.content =
transformDomainEventData(ctx.content); avoid this by creating a local const
content = transformDomainEventData(ctx.content) and then use that local content
for all subsequent operations inside async handle(ctx:
DomainEventPublishContext): Promise<void>, leaving ctx.content untouched so
other handlers get the original data; update all references in this module
(inside handle) to use the local content variable and keep
transformDomainEventData and DomainEventPublisher.publish usage unchanged.
---
Outside diff comments:
In `@apps/server-core/src/app/modules/database/module.ts`:
- Around line 96-109: The teardown method can bail out if
dataSource.data.destroy() throws, preventing cleanup; modify teardown in the
module.ts to wrap the destroy call in a try/finally (or try/catch/finally) so
that container.unregister(DatabaseInjectionKey.DomainEventPublisher) and the
eventRedisClient.disconnect()/undefined assignment always run in the finally
block, while still awaiting DataSource.destroy() and rethrowing or logging
errors as appropriate; reference the teardown function,
DatabaseInjectionKey.DataSource, DatabaseInjectionKey.DomainEventPublisher,
eventRedisClient, and DataSource.destroy() when making the change.
In `@apps/server-core/src/app/modules/provisioning/module.ts`:
- Around line 93-95: The ModuleName.LOGGER dependency is missing from the
provisioning module's dependency list which causes LoggerInjectionKey resolution
during setup (in ModuleName.PROVISIONING's provisioning setup code) to race;
update the dependencies array in module.ts (where this.name =
ModuleName.PROVISIONING and this.dependencies = [...]) to include
ModuleName.LOGGER alongside ModuleName.CONFIG and ModuleName.DATABASE so the
logger module is initialized before LoggerInjectionKey is resolved in the setup
logic.
---
Nitpick comments:
In `@packages/server-kit/src/domain-event/module.ts`:
- Around line 59-67: The loop using an explicit iterator over
this.handlers.values() (variables: handlers, it) is verbose; replace the manual
while(true) iterator in the method with an idiomatic for...of over
this.handlers.values() and await each handler.handle(ctx) inside the loop (keep
the same await semantics and early return behavior by simply finishing the
loop). This simplifies the code while preserving behavior for the handlers
iteration.
🪄 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: b954c267-e3b6-406f-b249-ed08d82598a2
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (84)
.agents/architecture.md.agents/structure.mdapps/server-core/package.jsonapps/server-core/src/adapters/database/data-source/index.tsapps/server-core/src/adapters/database/data-source/singleton.tsapps/server-core/src/adapters/database/domains/client-permission/subscriber.tsapps/server-core/src/adapters/database/domains/client-role/subscriber.tsapps/server-core/src/adapters/database/domains/client-scope/subscriber.tsapps/server-core/src/adapters/database/domains/client/subscriber.tsapps/server-core/src/adapters/database/domains/identity-provider-account/subscriber.tsapps/server-core/src/adapters/database/domains/identity-provider-attribute/subscriber.tsapps/server-core/src/adapters/database/domains/identity-provider-role-mapping/subscriber.tsapps/server-core/src/adapters/database/domains/identity-provider/subscriber.tsapps/server-core/src/adapters/database/domains/permission/subscriber.tsapps/server-core/src/adapters/database/domains/policy-attribute/subscriber.tsapps/server-core/src/adapters/database/domains/policy/subscriber.tsapps/server-core/src/adapters/database/domains/realm/subscriber.tsapps/server-core/src/adapters/database/domains/robot-permission/subscriber.tsapps/server-core/src/adapters/database/domains/robot-role/subscriber.tsapps/server-core/src/adapters/database/domains/robot/subscriber.tsapps/server-core/src/adapters/database/domains/role-attribute/subscriber.tsapps/server-core/src/adapters/database/domains/role-permission/subscriber.tsapps/server-core/src/adapters/database/domains/role/subscriber.tsapps/server-core/src/adapters/database/domains/scope/subscriber.tsapps/server-core/src/adapters/database/domains/user-attribute/subscriber.tsapps/server-core/src/adapters/database/domains/user-permission/subscriber.tsapps/server-core/src/adapters/database/domains/user-role/subscriber.tsapps/server-core/src/adapters/database/domains/user/subscriber.tsapps/server-core/src/adapters/database/event-publisher/module.tsapps/server-core/src/adapters/database/index.tsapps/server-core/src/adapters/database/subscriber/index.tsapps/server-core/src/adapters/database/subscriber/module.tsapps/server-core/src/adapters/database/subscriber/types.tsapps/server-core/src/adapters/http/middleware/built-in/error.tsapps/server-core/src/adapters/http/middleware/built-in/logger.tsapps/server-core/src/app/modules/database/constants.tsapps/server-core/src/app/modules/database/module.tsapps/server-core/src/app/modules/http/modules/controller.tsapps/server-core/src/app/modules/http/modules/middleware.tsapps/server-core/src/app/modules/identity/module.tsapps/server-core/src/app/modules/identity/repositories/provider/account/module.tsapps/server-core/src/app/modules/identity/repositories/provider/mapper/attribute.tsapps/server-core/src/app/modules/identity/repositories/provider/mapper/permission.tsapps/server-core/src/app/modules/identity/repositories/provider/mapper/role.tsapps/server-core/src/app/modules/logger/module.tsapps/server-core/src/app/modules/oauth2/module.tsapps/server-core/src/app/modules/oauth2/repositories/key/repository.tsapps/server-core/src/app/modules/provisioning/module.tsapps/server-core/src/core/entities/client/web-client.tsapps/server-core/src/core/entities/realm/service.tsapps/server-core/test/unit/core/identity/provider/account.spec.tspackages/server-kit/package.jsonpackages/server-kit/src/cache/adapters/index.tspackages/server-kit/src/cache/adapters/memory.tspackages/server-kit/src/cache/adapters/redis.tspackages/server-kit/src/cache/helper.tspackages/server-kit/src/cache/index.tspackages/server-kit/src/cache/types.tspackages/server-kit/src/crypto/json-web-token/index.tspackages/server-kit/src/crypto/json-web-token/sign/types.tspackages/server-kit/src/crypto/json-web-token/types.tspackages/server-kit/src/crypto/json-web-token/verify/types.tspackages/server-kit/src/domain-event/handlers/index.tspackages/server-kit/src/domain-event/handlers/redis/index.tspackages/server-kit/src/domain-event/handlers/redis/module.tspackages/server-kit/src/domain-event/handlers/socket/index.tspackages/server-kit/src/domain-event/handlers/socket/module.tspackages/server-kit/src/domain-event/index.tspackages/server-kit/src/domain-event/module.tspackages/server-kit/src/domain-event/types.tspackages/server-kit/src/domain-event/utils.tspackages/server-kit/src/index.tspackages/server-kit/src/logger/index.tspackages/server-kit/src/logger/module.tspackages/server-kit/src/logger/types.tspackages/server-kit/src/redis/check.tspackages/server-kit/src/redis/factory.tspackages/server-kit/src/redis/index.tspackages/server-kit/src/redis/module.tspackages/server-kit/src/services/logger/singleton.tspackages/server-kit/src/services/logger/types.tspackages/server-kit/src/services/vault/singleton.tspackages/server-kit/src/vault/index.tspackages/server-kit/src/vault/module.ts
💤 Files with no reviewable changes (10)
- apps/server-core/src/adapters/database/event-publisher/module.ts
- packages/server-kit/src/vault/index.ts
- packages/server-kit/src/services/vault/singleton.ts
- packages/server-kit/src/services/logger/singleton.ts
- packages/server-kit/package.json
- packages/server-kit/src/services/logger/types.ts
- apps/server-core/src/adapters/database/data-source/index.ts
- apps/server-core/src/adapters/database/data-source/singleton.ts
- apps/server-core/package.json
- packages/server-kit/src/logger/index.ts
| async handle(ctx: DomainEventPublishContext) : Promise<void> { | ||
| ctx.content = transformDomainEventData(ctx.content); |
There was a problem hiding this comment.
Avoid mutating the shared context object.
ctx.content is mutated directly, but the same ctx object is passed to all registered handlers by DomainEventPublisher.publish(). If multiple handlers are registered, the mutation affects subsequent handlers—potentially causing double-transformation or inconsistent event data depending on handler execution order.
Proposed fix
async handle(ctx: DomainEventPublishContext) : Promise<void> {
- ctx.content = transformDomainEventData(ctx.content);
+ const content = transformDomainEventData(ctx.content);
for (let i = 0; i < ctx.destinations.length; i++) {
const destination = ctx.destinations[i];
// ... rest uses `content` instead of `ctx.content`Then update all references to ctx.content within this method to use the local content variable.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/server-kit/src/domain-event/handlers/socket/module.ts` around lines
23 - 24, The handler is mutating the shared DomainEventPublishContext by
assigning ctx.content = transformDomainEventData(ctx.content); avoid this by
creating a local const content = transformDomainEventData(ctx.content) and then
use that local content for all subsequent operations inside async handle(ctx:
DomainEventPublishContext): Promise<void>, leaving ctx.content untouched so
other handlers get the original data; update all references in this module
(inside handle) to use the local content variable and keep
transformDomainEventData and DomainEventPublisher.publish usage unchanged.
Summary
Mirrors PrivateAIM/hub's server-kit design and removes all global mutable state from
@authup/server-kitandapps/server-core(net −1,361 lines).@authup/server-kitservices/{cache,logger,redis,vault}flattened to top-level folders (hub's one-folder-per-concern layout,module.ts/types.ts/index.tsconvention);type.ts→types.ts.useLogger,setLogger(Factory),isLoggerUsable, vault accessors);singadependency dropped.Loggeris now a winston-shaped structural type (error/warn/info/http/verbose/debug) — consumers no longer depend on winston.DomainEventPublisherfollows hub'sEntityEventPublisher: optionalloggerctx,register(handler), andsafePublish()(failures logged, never propagated into the originating DB transaction); redis/socket publishers becameIDomainEventHandlers (domain-event/handlers/).apps/server-coreRealmService/WebClientProvisionervia context. (Also fixes a latent crash: the error middleware'suseLogger()threw on 500s when no logger was configured.)EntitySubscriber<T>base (hubBaseSubscriberpattern,adapters/database/subscriber/) replaces 22 hand-written TypeORM subscribers (~110 → ~30 lines each).DatabaseModuleregisters the publisher underDatabaseInjectionKey.DomainEventPublisherand injects it viasetPublisher()afterdataSource.initialize(); teardown disconnects the event redis client and unregisters the token. Theevent-publisheranddata-sourcesinga singletons are deleted.OAuth2KeyRepositoryreceiveDataSourcevia constructor;setDataSource/useDataSource/unsetDataSourcehave zero call sites.afterRemoveused an unprefixed key, policyafterUpdateusedCachePrefix.REALM, scope usedCachePrefix.USER(dropped — no scope cache exists). Same-realm junction events are no longer published twice to the same namespace.Breaking changes (
@authup/server-kit)useLogger,setLogger,setLoggerFactory,isLoggerUsable,setVaultFactory,useVaultClient,isVaultClientUsable.DomainEventRedisPublisher/DomainEventSocketPublisher→DomainEventRedisHandler/DomainEventSocketHandler;DomainEventPublisher.mount()→register();IDomainEventPublishergainedsafePublish.Loggertype narrowed from winston'sLoggerto a structural type.Behavioral notes
safePublishsemantics): at-most-once delivery, logged on failure.Test plan
npm run buildfor server-kit, server-core, all server-adapter packages, server-test-kit, and the authup CLInpm run test --workspace=apps/server-core— 88 files / 862 tests pass (integration suite against Docker MySQL/Postgres/Redis)singa,useLogger,useDataSource,setDataSourceremain in source🤖 Generated with Claude Code
Summary by CodeRabbit
Improvements
Refactoring
Chores