Μετάβαση στο περιεχόμενο
Από την έκδοση 0.5.0 τα πακέτα συνεχίζουν ως @cqrs-ddd, με τεκμηρίωση στο aristoteliss.github.io/ddd-cqrs· οι εφαρμογές NestJS προσθέτουν το @cqrs-ddd/nestjs. Αυτός ο ιστότοπος τεκμηριώνει τη σειρά 0.4.x.

Σύνδεση μιας εφαρμογής

Το users-api καταχωρίζει τα πακέτα μία φορά, σε τρία modules. Ένας handler δηλώνει τότε μόνο τα behaviors που αφορούν ειδικά αυτόν, όπως στο Μια εντολή μέσα από κάθε επίπεδο.

  1. Το CorrelationMiddleware ορίζει το correlation id· το TenantSchemaMiddleware εκτελεί το υπόλοιπο αίτημα εντός του tenant που ορίζει το x-tenant-schema (δείτε Πολλοί tenants σε μία εγκατάσταση).
  2. Το AuthSessionGuard επιλύει το principal· το SessionPrincipalContextInterceptor το καθιστά διαθέσιμο στην εφαρμογή· το HttpRouteInterceptor ονομάζει το HTTP span από τη διαδρομή του.
  3. Το StandardSchemaValidationPipe επικυρώνει τις παραμέτρους που έχουν δηλωθεί με schema.
  4. Ο controller αποστέλλει ένα command ή query· το bus εκτελεί το pipeline του: τα καθολικά before behaviors, αυτά του ίδιου του handler, και στη συνέχεια τον handler.
  5. Κατά την έξοδο, τα exception filters μετατρέπουν τα framework-neutral σφάλματα των πακέτων σε απαντήσεις HTTP: 400 για validation, 403 για απενεργοποιημένο feature ή απαγορευμένη ενέργεια, 429 για rate limit, 409 ή 422 για σύγκρουση idempotency.
api/src/app.module.ts
/* Copyright (C) 2026-present Aristotelis — see repository license. */
import { contextSources } from '@common/context/context-sources.js';
import { AuthSessionGuard } from '@common/guards/auth-session.guard.js';
import { SessionPrincipalContextInterceptor } from '@common/interceptors/session-principal-context.interceptor.js';
import { CorrelationMiddleware } from '@cqrs-ddd/nestjs/correlation';
import { JobContextModule } from '@cqrs-ddd/nestjs/job-context';
import {
type MiddlewareConsumer,
Module,
type NestModule,
StandardSchemaValidationPipe,
} from '@nestjs/common';
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
import { CqrsModule } from '@nestjs/cqrs';
import { TenantSchemaMiddleware } from '@persistence/middlewares/tenant-schema.middleware.js';
import { persistenceConfig } from '@persistence/persistence.config.js';
import { PersistenceModule } from '@persistence/persistence.module.js';
import { AuthorizationModule } from './auths/authorization.module.js';
import { AuthsModule } from './auths/auths.module.js';
import { SessionJobPrincipal } from './auths/infrastructure/session-job-principal.js';
import { DomainExceptionFilter } from './common/filters/domain-exception.filter.js';
import {
ObservabilityModule,
ReliabilityModule,
} from './common/modules/index.js';
import { RolesModule } from './roles/roles.module.js';
import { UsersModule } from './users/users.module.js';
/**
* Root composition module of the Users API application.
*
* Orchestrates cross-cutting infrastructure concerns (Observability, Reliability, Persistence,
* CASL Authorization, CQRS) alongside business domain modules (Users, Roles, Auths).
*
* ### Architectural Layout
* - {@link ObservabilityModule}: Structured logging (Pino), OpenTelemetry tracing & metrics, global pipeline behaviors, and audit logging.
* - {@link ReliabilityModule}: BullMQ queue engine, dead-letter storage, rate limiting, distributed idempotency, resilience policies, caching, and feature flags.
* - {@link AuthorizationModule}: role- and attribute-based access control (`CaslBehavior`, `CaslAuthorizer`) on the application's permission source.
* - {@link PersistenceModule}: MikroORM database connection, entity repositories, and tenant schema manager.
* - {@link JobContextModule}: carries a request's tenant, correlation id and principal into the jobs it enqueues.
* - `StandardSchemaValidationPipe`: validates every route parameter declared with a `schema`; NestJS answers 400 with its own body.
* - {@link DomainExceptionFilter}: the one global filter; every error becomes a NestJS `HttpException`.
* - {@link CorrelationMiddleware}: takes or creates the correlation id of every request.
* - Domain Feature Modules: {@link UsersModule}, {@link RolesModule}, {@link AuthsModule}.
*/
@Module({
imports: [
CqrsModule.forRoot(),
ObservabilityModule,
ReliabilityModule,
AuthorizationModule,
PersistenceModule,
UsersModule,
RolesModule,
AuthsModule,
JobContextModule.forRoot({
imports: [AuthsModule],
principal: SessionJobPrincipal,
tenants: () => persistenceConfig().tenants,
sources: contextSources,
}),
],
providers: [
{ provide: APP_GUARD, useClass: AuthSessionGuard },
{ provide: APP_INTERCEPTOR, useClass: SessionPrincipalContextInterceptor },
{ provide: APP_PIPE, useValue: new StandardSchemaValidationPipe() },
{ provide: APP_FILTER, useClass: DomainExceptionFilter },
],
})
export class AppModule implements NestModule {
constructor(
private readonly tenantSchemaMiddleware: TenantSchemaMiddleware,
) {}
configure(consumer: MiddlewareConsumer) {
consumer
.apply(
CorrelationMiddleware,
this.tenantSchemaMiddleware.use.bind(this.tenantSchemaMiddleware),
)
.forRoutes('*');
}
}

Το ObservabilityModule ταξινομεί τα καθολικά behaviors ώστε η τηλεμετρία να περικλείει ό,τι προσθέτει ένας handler: logging, μετά το span και τα metrics, μετά το AttributesBehavior, το οποίο αντιγράφει τις αποφάσεις των προσθέτων στο span, και έπειτα το validation. Τα commands και events λαμβάνουν επίσης το DeadLetterBehavior. Συνδέει επίσης τον tenant του @nestjs-pipeline/tenant με τα tenant-scoped cache keys του @cqrs-ddd/core:

api/src/common/modules/observability.module.ts
/* Copyright (C) 2026-present Aristotelis — see repository license. */
import { IncomingMessage } from 'node:http';
import { AUDIT_MODULE_DEFAULTS } from '@common/audit/audit.options.js';
import { HEADERS } from '@common/constants/headers.constants.js';
import { contextSources } from '@common/context/context-sources.js';
import { HttpRouteInterceptor } from '@common/interceptors/http-route.interceptor.js';
import { setTenantResolver } from '@cqrs-ddd/core/application';
import { PipelineModule } from '@cqrs-ddd/nestjs';
import { LoggingBehavior, logging } from '@cqrs-ddd/pipeline';
import { AuditBehavior, LogAuditSink } from '@cqrs-ddd/pipeline-audit';
import { buildCacheAttributes } from '@cqrs-ddd/pipeline-cache';
import {
buildDeadLetterAttributes,
DeadLetterBehavior,
} from '@cqrs-ddd/pipeline-deadletter';
import { buildFeatureFlagAttributes } from '@cqrs-ddd/pipeline-feature-flags';
import { buildIdempotencyAttributes } from '@cqrs-ddd/pipeline-idempotency';
import {
AttributesBehavior,
MetricsBehavior,
TraceBehavior,
} from '@cqrs-ddd/pipeline-opentelemetry';
import { buildRateLimitAttributes } from '@cqrs-ddd/pipeline-rate-limit';
import { currentTenantId } from '@cqrs-ddd/pipeline-tenant';
import { ZodValidationBehavior } from '@cqrs-ddd/pipeline-zod';
import { Logger, Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { LoggerModule, NativeLogger } from 'nestjs-pino';
/** Credential headers redacted from structured HTTP logs. */
const HTTP_LOG_REDACT_PATHS = [
'req.headers.authorization',
'req.headers.cookie',
`req.headers["${HEADERS.API_KEY}"]`,
`req.headers["${HEADERS.API_ID}"]`,
'req.headers["set-cookie"]',
'res.headers["set-cookie"]',
];
/**
* Configures structured HTTP logging, correlation propagation, tracing, metrics,
* request validation and operational audit recording. It places the global
* behaviors of every handler's pipeline, and provides the logging, telemetry,
* validation and audit behaviors under their behavior classes. Global pipeline
* ordering keeps telemetry around handler-local behaviors so their outcomes
* reach the span.
*
* HTTP server spans carry the matched route (`HttpRouteInterceptor`).
*
* HTTP credentials are redacted through `HTTP_LOG_REDACT_PATHS`. Auditing uses
* a log sink on the Nest logger with `failOpen: true`; durable audit requirements need
* a persistent sink and an explicit failure policy.
*
* It also makes the pipeline's tenant the tenant of `@cqrs-ddd/core`'s
* tenant-scoped helpers (`cacheKey`, `cacheKeyTemplate`), before any
* lifecycle hook can start work that reads it.
*
* @example Register application observability
* ```ts
* @Module({ imports: [ObservabilityModule] })
* export class AppModule {}
* ```
*/
@Module({
imports: [
LoggerModule.forRoot({
pinoHttp: {
autoLogging: true,
level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
redact: {
paths: HTTP_LOG_REDACT_PATHS,
censor: '[REDACTED]',
},
transport:
process.env.NODE_ENV !== 'production'
? {
target: 'pino-pretty',
options: {
colorize: true,
messageFormat: '[{context}] {msg}',
translateTime: 'SYS:HH:MM:ss.l',
},
}
: undefined,
customProps: (req: IncomingMessage) => ({
context: `${req.method} ${req.url}`,
}),
},
}),
PipelineModule.forRoot({
sources: contextSources,
globalBehaviors: [
{
scope: 'all',
before: [
logging({ requestResponseLogLevel: 'log' }),
[TraceBehavior, { tracerName: 'users-api' }],
[MetricsBehavior, { meterName: 'users-api' }],
[
AttributesBehavior,
{
factories: [
buildFeatureFlagAttributes,
buildCacheAttributes,
buildIdempotencyAttributes,
buildRateLimitAttributes,
buildDeadLetterAttributes,
],
},
],
ZodValidationBehavior,
],
},
{
scope: 'commands',
before: [DeadLetterBehavior],
},
{
scope: 'events',
before: [DeadLetterBehavior],
},
],
}),
],
providers: [
{ provide: APP_INTERCEPTOR, useClass: HttpRouteInterceptor },
{
provide: LoggingBehavior,
inject: [NativeLogger],
useFactory: (logger: NativeLogger) => new LoggingBehavior(logger),
},
TraceBehavior,
{
provide: MetricsBehavior,
useFactory: () => new MetricsBehavior(new Logger(MetricsBehavior.name)),
},
AttributesBehavior,
ZodValidationBehavior,
{
provide: AuditBehavior,
useFactory: () => {
const logger = new Logger(AuditBehavior.name);
return new AuditBehavior(
new LogAuditSink({ logger }),
AUDIT_MODULE_DEFAULTS,
logger,
);
},
},
],
exports: [LoggerModule],
})
export class ObservabilityModule {
constructor() {
setTenantResolver(currentTenantId);
}
}

Το ReliabilityModule συνδέει τα πρόσθετα με την υποδομή τους: BullMQ queues, το dead-letter transport, το rate limiter, το idempotency store, τις πολιτικές ανθεκτικότητας (resilience policies), την cache αποκρίσεων και τα feature flags:

api/src/common/modules/reliability.module.ts
/* Copyright (C) 2026-present Aristotelis — see repository license. */
import { RATE_LIMIT_CAPACITY, RATE_LIMITER } from '@common/constants/index.js';
import { redisConfig } from '@common/environment/redis.config.js';
import { buildCache, CacheBehavior } from '@cqrs-ddd/pipeline-cache';
import {
BullMqDeadLetterTransport,
DeadLetterBehavior,
} from '@cqrs-ddd/pipeline-deadletter';
import {
createFeatureFlagClient,
FeatureFlagBehavior,
releaseFeatureFlagProvider,
} from '@cqrs-ddd/pipeline-feature-flags';
import {
IdempotencyBehavior,
MemoryIdempotencyStore,
} from '@cqrs-ddd/pipeline-idempotency';
import {
RateLimitBehavior,
type RateLimiterLike,
} from '@cqrs-ddd/pipeline-rate-limit';
import { ResilienceBehavior } from '@cqrs-ddd/pipeline-resilience';
import { BullModule, getQueueToken } from '@nestjs/bullmq';
import {
Inject,
Logger,
Module,
type OnApplicationShutdown,
} from '@nestjs/common';
import { TypedInMemoryProvider } from '@openfeature/server-sdk';
import type { Queue } from 'bullmq';
import type { Cache } from 'cache-manager';
import { RateLimiterMemory } from 'rate-limiter-flexible';
import { DEAD_LETTER_DEFAULTS } from '../dead-letter/dead-letter.options.js';
/** Injection token of the store `CacheBehavior` caches handler responses in. */
export const RESPONSE_CACHE = Symbol('RESPONSE_CACHE');
const FEATURE_FLAGS = {
provider: new TypedInMemoryProvider({
'user-registration': {
disabled: false,
variants: { on: true, off: false },
defaultVariant: 'on',
},
'role-creation': {
disabled: false,
variants: { on: true, off: false },
defaultVariant: 'on',
},
}),
};
/**
* Wires BullMQ, and the behaviors that handlers place for reliability: dead
* letters, rate limiting, idempotency, resilience, response caching and feature
* flags. Each is a provider under its behavior class, built once here; the
* pipeline takes these instances.
*
* Rate-limit quotas and idempotency records are process-local. Response caching
* uses memory for local development and Redis when REDIS_HOST is configured or
* NODE_ENV is production. Every Redis client takes its connection from
* `redisConfig()`. Repository snapshot caching has its own adapters and
* invalidation lifecycle; this module configures pipeline response caching.
* On shutdown it stops the idempotency store's sweep, disconnects the response
* cache and releases the feature-flag provider.
*
* @example Register the pipeline infrastructure alongside observability
* ```ts
* @Module({ imports: [ObservabilityModule, ReliabilityModule] })
* export class AppModule {}
* ```
*/
@Module({
imports: [
BullModule.forRootAsync({
useFactory: () => {
const { host, port } = redisConfig();
return { connection: { host, port } };
},
}),
BullModule.registerQueue({
name: 'dead-letters',
forceDisconnectOnShutdown: true,
}),
],
providers: [
{
provide: DeadLetterBehavior,
inject: [getQueueToken('dead-letters')],
useFactory: (queue: Queue) =>
new DeadLetterBehavior(
new BullMqDeadLetterTransport(queue),
DEAD_LETTER_DEFAULTS,
new Logger(DeadLetterBehavior.name),
),
},
{
provide: RATE_LIMITER,
useFactory: () => new RateLimiterMemory(RATE_LIMIT_CAPACITY),
},
{
provide: RateLimitBehavior,
inject: [RATE_LIMITER],
useFactory: (limiter: RateLimiterLike) =>
new RateLimitBehavior(
limiter,
undefined,
new Logger(RateLimitBehavior.name),
),
},
{
provide: MemoryIdempotencyStore,
useFactory: () => new MemoryIdempotencyStore(),
},
{
provide: IdempotencyBehavior,
inject: [MemoryIdempotencyStore],
useFactory: (store: MemoryIdempotencyStore) =>
new IdempotencyBehavior(
store,
undefined,
new Logger(IdempotencyBehavior.name),
),
},
{
provide: ResilienceBehavior,
useFactory: () =>
new ResilienceBehavior(undefined, new Logger(ResilienceBehavior.name)),
},
{
provide: RESPONSE_CACHE,
useFactory: () => {
const redis = redisConfig();
return buildCache({
store:
!redis.isConfigured && process.env.NODE_ENV !== 'production'
? { type: 'memory' }
: { type: 'redis', url: redis.url },
ttl: 30_000,
});
},
},
{
provide: CacheBehavior,
inject: [RESPONSE_CACHE],
useFactory: (cache: Cache) =>
new CacheBehavior(cache, undefined, new Logger(CacheBehavior.name)),
},
{
provide: FeatureFlagBehavior,
useFactory: async () =>
new FeatureFlagBehavior(
await createFeatureFlagClient(FEATURE_FLAGS),
undefined,
{ environment: process.env.NODE_ENV ?? 'development' },
new Logger(FeatureFlagBehavior.name),
),
},
],
exports: [BullModule, RATE_LIMITER],
})
export class ReliabilityModule implements OnApplicationShutdown {
constructor(
private readonly idempotencyStore: MemoryIdempotencyStore,
@Inject(RESPONSE_CACHE) private readonly responseCache: Cache,
) {}
async onApplicationShutdown(): Promise<void> {
this.idempotencyStore.destroy();
await this.responseCache.disconnect();
await releaseFeatureFlagProvider(FEATURE_FLAGS);
}
}