@quanticjs/core 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bootstrap/bootstrapService.d.ts +8 -0
- package/dist/bootstrap/bootstrapService.js +58 -0
- package/dist/cqrs/PipelineExecutor.d.ts +31 -0
- package/dist/cqrs/PipelineExecutor.js +81 -0
- package/dist/cqrs/behaviors/CacheBehavior.d.ts +9 -0
- package/dist/cqrs/behaviors/CacheBehavior.js +68 -0
- package/dist/cqrs/behaviors/DistributedLockBehavior.d.ts +12 -0
- package/dist/cqrs/behaviors/DistributedLockBehavior.js +90 -0
- package/dist/cqrs/behaviors/FeatureFlagBehavior.d.ts +8 -0
- package/dist/cqrs/behaviors/FeatureFlagBehavior.js +58 -0
- package/dist/cqrs/behaviors/InvalidateCacheBehavior.d.ts +9 -0
- package/dist/cqrs/behaviors/InvalidateCacheBehavior.js +61 -0
- package/dist/cqrs/behaviors/LogBehavior.d.ts +9 -0
- package/dist/cqrs/behaviors/LogBehavior.js +125 -0
- package/dist/cqrs/behaviors/PerformanceBehavior.d.ts +12 -0
- package/dist/cqrs/behaviors/PerformanceBehavior.js +56 -0
- package/dist/cqrs/behaviors/TransactionalBehavior.d.ts +18 -0
- package/dist/cqrs/behaviors/TransactionalBehavior.js +77 -0
- package/dist/cqrs/behaviors/ValidationBehavior.d.ts +4 -0
- package/dist/cqrs/behaviors/ValidationBehavior.js +33 -0
- package/dist/cqrs/behaviors/WorkflowBehavior.d.ts +8 -0
- package/dist/cqrs/behaviors/WorkflowBehavior.js +61 -0
- package/dist/cqrs/constants.d.ts +2 -0
- package/dist/cqrs/constants.js +5 -0
- package/dist/cqrs/decorators/Cache.decorator.d.ts +13 -0
- package/dist/cqrs/decorators/Cache.decorator.js +18 -0
- package/dist/cqrs/decorators/DistributedLock.decorator.d.ts +15 -0
- package/dist/cqrs/decorators/DistributedLock.decorator.js +23 -0
- package/dist/cqrs/decorators/FeatureFlag.decorator.d.ts +9 -0
- package/dist/cqrs/decorators/FeatureFlag.decorator.js +14 -0
- package/dist/cqrs/decorators/InvalidateCache.decorator.d.ts +6 -0
- package/dist/cqrs/decorators/InvalidateCache.decorator.js +14 -0
- package/dist/cqrs/decorators/IsolatedTransaction.decorator.d.ts +14 -0
- package/dist/cqrs/decorators/IsolatedTransaction.decorator.js +25 -0
- package/dist/cqrs/decorators/Log.decorator.d.ts +11 -0
- package/dist/cqrs/decorators/Log.decorator.js +18 -0
- package/dist/cqrs/decorators/Validate.decorator.d.ts +24 -0
- package/dist/cqrs/decorators/Validate.decorator.js +37 -0
- package/dist/cqrs/decorators/Workflow.decorator.d.ts +8 -0
- package/dist/cqrs/decorators/Workflow.decorator.js +14 -0
- package/dist/cqrs/interfaces/WorkflowEngine.d.ts +14 -0
- package/dist/cqrs/interfaces/WorkflowEngine.js +4 -0
- package/dist/cqrs/pipeline/QuanticCommandBus.d.ts +37 -0
- package/dist/cqrs/pipeline/QuanticCommandBus.js +99 -0
- package/dist/cqrs/pipeline/QuanticQueryBus.d.ts +28 -0
- package/dist/cqrs/pipeline/QuanticQueryBus.js +78 -0
- package/dist/cqrs/pipeline/runPipeline.d.ts +3 -0
- package/dist/cqrs/pipeline/runPipeline.js +12 -0
- package/dist/cqrs/transaction/TransactionContext.d.ts +18 -0
- package/dist/cqrs/transaction/TransactionContext.js +26 -0
- package/dist/cqrs/transaction/getTransactionalRepo.d.ts +16 -0
- package/dist/cqrs/transaction/getTransactionalRepo.js +22 -0
- package/dist/cqrs/validation/ICommandValidator.d.ts +48 -0
- package/dist/cqrs/validation/ICommandValidator.js +21 -0
- package/dist/entities/BaseEntity.d.ts +5 -0
- package/dist/entities/BaseEntity.js +31 -0
- package/dist/entities/TenantBaseEntity.d.ts +4 -0
- package/dist/entities/TenantBaseEntity.js +22 -0
- package/dist/events/DomainEvent.d.ts +14 -0
- package/dist/events/DomainEvent.js +27 -0
- package/dist/events/OutboxEvent.entity.d.ts +18 -0
- package/dist/events/OutboxEvent.entity.js +87 -0
- package/dist/events/OutboxPublisherService.d.ts +14 -0
- package/dist/events/OutboxPublisherService.js +104 -0
- package/dist/events/RedisStreamConsumer.d.ts +43 -0
- package/dist/events/RedisStreamConsumer.js +158 -0
- package/dist/events/RedisStreamPublisher.d.ts +9 -0
- package/dist/events/RedisStreamPublisher.js +60 -0
- package/dist/filters/GlobalExceptionFilter.d.ts +11 -0
- package/dist/filters/GlobalExceptionFilter.js +102 -0
- package/dist/guards/JwtAuthGuard.d.ts +10 -0
- package/dist/guards/JwtAuthGuard.js +46 -0
- package/dist/guards/JwtStrategy.d.ts +22 -0
- package/dist/guards/JwtStrategy.js +47 -0
- package/dist/guards/RolesGuard.d.ts +8 -0
- package/dist/guards/RolesGuard.js +52 -0
- package/dist/index.d.ts +69 -0
- package/dist/index.js +146 -0
- package/dist/interceptors/ResultInterceptor.d.ts +7 -0
- package/dist/interceptors/ResultInterceptor.js +88 -0
- package/dist/lifecycle/GracefulShutdownService.d.ts +24 -0
- package/dist/lifecycle/GracefulShutdownService.js +93 -0
- package/dist/logging/pino-config.d.ts +35 -0
- package/dist/logging/pino-config.js +79 -0
- package/dist/metrics/MetricsController.d.ts +7 -0
- package/dist/metrics/MetricsController.js +42 -0
- package/dist/metrics/MetricsService.d.ts +13 -0
- package/dist/metrics/MetricsService.js +58 -0
- package/dist/middleware/CorrelationIdMiddleware.d.ts +4 -0
- package/dist/middleware/CorrelationIdMiddleware.js +33 -0
- package/dist/middleware/CorrelationStore.d.ts +11 -0
- package/dist/middleware/CorrelationStore.js +9 -0
- package/dist/middleware/TenantContextMiddleware.d.ts +7 -0
- package/dist/middleware/TenantContextMiddleware.js +27 -0
- package/dist/middleware/TenantStore.d.ts +9 -0
- package/dist/middleware/TenantStore.js +9 -0
- package/dist/redis/redis.module.d.ts +8 -0
- package/dist/redis/redis.module.js +49 -0
- package/dist/resilience/CircuitBreakerFactory.d.ts +12 -0
- package/dist/resilience/CircuitBreakerFactory.js +22 -0
- package/dist/result/Result.d.ts +26 -0
- package/dist/result/Result.js +62 -0
- package/dist/shared-kernel.module.d.ts +13 -0
- package/dist/shared-kernel.module.js +87 -0
- package/dist/subscribers/TenantSubscriber.d.ts +20 -0
- package/dist/subscribers/TenantSubscriber.js +52 -0
- package/dist/testing/TestingModuleFactory.d.ts +23 -0
- package/dist/testing/TestingModuleFactory.js +63 -0
- package/dist/testing/index.d.ts +2 -0
- package/dist/testing/index.js +7 -0
- package/dist/testing/mocks.d.ts +34 -0
- package/dist/testing/mocks.js +62 -0
- package/dist/unleash/initial-flags.d.ts +7 -0
- package/dist/unleash/initial-flags.js +9 -0
- package/dist/unleash/unleash.module.d.ts +9 -0
- package/dist/unleash/unleash.module.js +47 -0
- package/package.json +140 -0
- package/src/bootstrap/bootstrapService.ts +72 -0
- package/src/cqrs/behaviors/CacheBehavior.spec.ts +63 -0
- package/src/cqrs/behaviors/CacheBehavior.ts +54 -0
- package/src/cqrs/behaviors/DistributedLockBehavior.ts +88 -0
- package/src/cqrs/behaviors/FeatureFlagBehavior.ts +46 -0
- package/src/cqrs/behaviors/InvalidateCacheBehavior.spec.ts +89 -0
- package/src/cqrs/behaviors/InvalidateCacheBehavior.ts +50 -0
- package/src/cqrs/behaviors/LogBehavior.spec.ts +55 -0
- package/src/cqrs/behaviors/LogBehavior.ts +121 -0
- package/src/cqrs/behaviors/PerformanceBehavior.spec.ts +48 -0
- package/src/cqrs/behaviors/PerformanceBehavior.ts +43 -0
- package/src/cqrs/behaviors/TransactionalBehavior.ts +64 -0
- package/src/cqrs/behaviors/ValidationBehavior.spec.ts +114 -0
- package/src/cqrs/behaviors/ValidationBehavior.ts +29 -0
- package/src/cqrs/behaviors/WorkflowBehavior.spec.ts +97 -0
- package/src/cqrs/behaviors/WorkflowBehavior.ts +62 -0
- package/src/cqrs/constants.ts +2 -0
- package/src/cqrs/decorators/Cache.decorator.ts +24 -0
- package/src/cqrs/decorators/DistributedLock.decorator.ts +34 -0
- package/src/cqrs/decorators/FeatureFlag.decorator.ts +23 -0
- package/src/cqrs/decorators/InvalidateCache.decorator.spec.ts +20 -0
- package/src/cqrs/decorators/InvalidateCache.decorator.ts +17 -0
- package/src/cqrs/decorators/IsolatedTransaction.decorator.ts +24 -0
- package/src/cqrs/decorators/Log.decorator.ts +22 -0
- package/src/cqrs/decorators/Validate.decorator.ts +39 -0
- package/src/cqrs/decorators/Workflow.decorator.ts +22 -0
- package/src/cqrs/interfaces/WorkflowEngine.ts +19 -0
- package/src/cqrs/pipeline/QuanticCommandBus.ts +69 -0
- package/src/cqrs/pipeline/QuanticQueryBus.ts +56 -0
- package/src/cqrs/pipeline/runPipeline.ts +22 -0
- package/src/cqrs/transaction/TransactionContext.ts +26 -0
- package/src/cqrs/transaction/getTransactionalRepo.ts +23 -0
- package/src/cqrs/validation/ICommandValidator.ts +55 -0
- package/src/entities/BaseEntity.ts +16 -0
- package/src/entities/TenantBaseEntity.ts +7 -0
- package/src/events/DomainEvent.ts +27 -0
- package/src/events/OutboxEvent.entity.ts +56 -0
- package/src/events/OutboxPublisherService.ts +94 -0
- package/src/events/RedisStreamConsumer.ts +172 -0
- package/src/events/RedisStreamPublisher.ts +54 -0
- package/src/filters/GlobalExceptionFilter.ts +125 -0
- package/src/guards/JwtAuthGuard.ts +29 -0
- package/src/guards/JwtStrategy.ts +41 -0
- package/src/guards/RolesGuard.ts +39 -0
- package/src/index.ts +118 -0
- package/src/interceptors/ResultInterceptor.ts +93 -0
- package/src/lifecycle/GracefulShutdownService.ts +77 -0
- package/src/logging/pino-config.ts +80 -0
- package/src/metrics/MetricsController.ts +17 -0
- package/src/metrics/MetricsService.ts +55 -0
- package/src/middleware/CorrelationIdMiddleware.ts +27 -0
- package/src/middleware/CorrelationStore.ts +13 -0
- package/src/middleware/TenantContextMiddleware.ts +21 -0
- package/src/middleware/TenantStore.ts +11 -0
- package/src/redis/redis.module.ts +41 -0
- package/src/resilience/CircuitBreakerFactory.ts +33 -0
- package/src/result/Result.ts +66 -0
- package/src/shared-kernel.module.ts +87 -0
- package/src/subscribers/TenantSubscriber.ts +47 -0
- package/src/testing/TestingModuleFactory.ts +78 -0
- package/src/testing/index.ts +2 -0
- package/src/testing/mocks.ts +59 -0
- package/src/unleash/unleash.module.ts +45 -0
- package/tsconfig.json +22 -0
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
var OutboxPublisherService_1;
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
exports.OutboxPublisherService = void 0;
|
|
14
|
+
const common_1 = require("@nestjs/common");
|
|
15
|
+
const typeorm_1 = require("typeorm");
|
|
16
|
+
const OutboxEvent_entity_1 = require("./OutboxEvent.entity");
|
|
17
|
+
const RedisStreamPublisher_1 = require("./RedisStreamPublisher");
|
|
18
|
+
const POLL_INTERVAL_MS = 100;
|
|
19
|
+
const BATCH_SIZE = 50;
|
|
20
|
+
const MAX_PUBLISH_ATTEMPTS = 5;
|
|
21
|
+
const DLQ_STREAM = 'arex:events:dlq';
|
|
22
|
+
let OutboxPublisherService = OutboxPublisherService_1 = class OutboxPublisherService {
|
|
23
|
+
dataSource;
|
|
24
|
+
redisPublisher;
|
|
25
|
+
logger = new common_1.Logger(OutboxPublisherService_1.name);
|
|
26
|
+
timer = null;
|
|
27
|
+
processing = false;
|
|
28
|
+
constructor(dataSource, redisPublisher) {
|
|
29
|
+
this.dataSource = dataSource;
|
|
30
|
+
this.redisPublisher = redisPublisher;
|
|
31
|
+
}
|
|
32
|
+
onModuleInit() {
|
|
33
|
+
this.timer = setInterval(() => this.pollAndPublish(), POLL_INTERVAL_MS);
|
|
34
|
+
this.logger.log(`Outbox publisher started (${POLL_INTERVAL_MS}ms poll interval)`);
|
|
35
|
+
}
|
|
36
|
+
onModuleDestroy() {
|
|
37
|
+
if (this.timer) {
|
|
38
|
+
clearInterval(this.timer);
|
|
39
|
+
this.timer = null;
|
|
40
|
+
}
|
|
41
|
+
this.logger.log('Outbox publisher stopped');
|
|
42
|
+
}
|
|
43
|
+
async pollAndPublish() {
|
|
44
|
+
if (this.processing)
|
|
45
|
+
return;
|
|
46
|
+
this.processing = true;
|
|
47
|
+
try {
|
|
48
|
+
const repo = this.dataSource.getRepository(OutboxEvent_entity_1.OutboxEvent);
|
|
49
|
+
const events = await repo.find({
|
|
50
|
+
where: { status: OutboxEvent_entity_1.OutboxEventStatus.Pending },
|
|
51
|
+
order: { createdAt: 'ASC' },
|
|
52
|
+
take: BATCH_SIZE,
|
|
53
|
+
});
|
|
54
|
+
for (const event of events) {
|
|
55
|
+
try {
|
|
56
|
+
await this.redisPublisher.publishToStream(event.streamKey, {
|
|
57
|
+
eventId: event.id,
|
|
58
|
+
eventType: event.eventType,
|
|
59
|
+
aggregateId: event.aggregateId,
|
|
60
|
+
organizationId: event.organizationId || '',
|
|
61
|
+
payload: JSON.stringify(event.payload),
|
|
62
|
+
occurredAt: event.createdAt.toISOString(),
|
|
63
|
+
});
|
|
64
|
+
event.status = OutboxEvent_entity_1.OutboxEventStatus.Published;
|
|
65
|
+
event.publishedAt = new Date();
|
|
66
|
+
await repo.save(event);
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
event.publishAttempts += 1;
|
|
70
|
+
event.lastError = error.message;
|
|
71
|
+
if (event.publishAttempts >= MAX_PUBLISH_ATTEMPTS) {
|
|
72
|
+
event.status = OutboxEvent_entity_1.OutboxEventStatus.Failed;
|
|
73
|
+
this.logger.error(`Event ${event.id} exceeded max attempts, routing to DLQ`);
|
|
74
|
+
try {
|
|
75
|
+
await this.redisPublisher.publishToStream(DLQ_STREAM, {
|
|
76
|
+
eventId: event.id,
|
|
77
|
+
eventType: event.eventType,
|
|
78
|
+
aggregateId: event.aggregateId,
|
|
79
|
+
error: event.lastError || 'unknown',
|
|
80
|
+
payload: JSON.stringify(event.payload),
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
this.logger.error(`Failed to route event ${event.id} to DLQ`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
await repo.save(event);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
this.logger.error('Outbox poll cycle failed', error.stack);
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
this.processing = false;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
exports.OutboxPublisherService = OutboxPublisherService;
|
|
100
|
+
exports.OutboxPublisherService = OutboxPublisherService = OutboxPublisherService_1 = __decorate([
|
|
101
|
+
(0, common_1.Injectable)(),
|
|
102
|
+
__metadata("design:paramtypes", [typeorm_1.DataSource,
|
|
103
|
+
RedisStreamPublisher_1.RedisStreamPublisher])
|
|
104
|
+
], OutboxPublisherService);
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
|
2
|
+
import type { Redis } from 'ioredis';
|
|
3
|
+
/**
|
|
4
|
+
* Abstract base class for Redis Stream consumer groups.
|
|
5
|
+
*
|
|
6
|
+
* Subclasses declare `streamKey`, `consumerGroup`, `consumerName`
|
|
7
|
+
* and implement `handleMessage(fields)`.
|
|
8
|
+
*
|
|
9
|
+
* Lifecycle:
|
|
10
|
+
* - OnModuleInit: creates consumer group (idempotent), starts read loop
|
|
11
|
+
* - OnModuleDestroy: stops the read loop gracefully, disconnects dedicated client
|
|
12
|
+
*
|
|
13
|
+
* Connection strategy:
|
|
14
|
+
* - Shared REDIS_CLIENT: used for non-blocking ops (XGROUP CREATE, XACK)
|
|
15
|
+
* - Dedicated cloned connection: used ONLY for blocking XREADGROUP BLOCK calls
|
|
16
|
+
* - This prevents blocking consumers from starving non-blocking callers
|
|
17
|
+
* (cache, distributed locks, publishers) that share the main REDIS_CLIENT.
|
|
18
|
+
*
|
|
19
|
+
* Features:
|
|
20
|
+
* - Auto-creates consumer group via XGROUP CREATE ... MKSTREAM
|
|
21
|
+
* - Recovers pending (unacked) messages on startup before reading new ones
|
|
22
|
+
* - XREADGROUP BLOCK for efficient new-message polling (on dedicated connection)
|
|
23
|
+
* - XACK after successful processing (on shared connection)
|
|
24
|
+
* - Graceful shutdown (finishes in-flight message, disconnects dedicated client)
|
|
25
|
+
*/
|
|
26
|
+
export declare abstract class RedisStreamConsumer implements OnModuleInit, OnModuleDestroy {
|
|
27
|
+
protected readonly redis?: Redis | undefined;
|
|
28
|
+
protected readonly logger: Logger;
|
|
29
|
+
abstract readonly streamKey: string;
|
|
30
|
+
abstract readonly consumerGroup: string;
|
|
31
|
+
abstract readonly consumerName: string;
|
|
32
|
+
/** Override to filter by eventType. Return true to process. Default: all messages. */
|
|
33
|
+
protected shouldHandle(_fields: Record<string, string>): boolean;
|
|
34
|
+
abstract handleMessage(fields: Record<string, string>): Promise<void>;
|
|
35
|
+
private running;
|
|
36
|
+
/** Dedicated connection for blocking XREADGROUP — cloned from shared client on init */
|
|
37
|
+
private blockingClient?;
|
|
38
|
+
constructor(redis?: Redis | undefined);
|
|
39
|
+
onModuleInit(): Promise<void>;
|
|
40
|
+
onModuleDestroy(): Promise<void>;
|
|
41
|
+
private consumeLoop;
|
|
42
|
+
private readMessages;
|
|
43
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
12
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.RedisStreamConsumer = void 0;
|
|
16
|
+
const common_1 = require("@nestjs/common");
|
|
17
|
+
const constants_1 = require("../cqrs/constants");
|
|
18
|
+
/**
|
|
19
|
+
* Abstract base class for Redis Stream consumer groups.
|
|
20
|
+
*
|
|
21
|
+
* Subclasses declare `streamKey`, `consumerGroup`, `consumerName`
|
|
22
|
+
* and implement `handleMessage(fields)`.
|
|
23
|
+
*
|
|
24
|
+
* Lifecycle:
|
|
25
|
+
* - OnModuleInit: creates consumer group (idempotent), starts read loop
|
|
26
|
+
* - OnModuleDestroy: stops the read loop gracefully, disconnects dedicated client
|
|
27
|
+
*
|
|
28
|
+
* Connection strategy:
|
|
29
|
+
* - Shared REDIS_CLIENT: used for non-blocking ops (XGROUP CREATE, XACK)
|
|
30
|
+
* - Dedicated cloned connection: used ONLY for blocking XREADGROUP BLOCK calls
|
|
31
|
+
* - This prevents blocking consumers from starving non-blocking callers
|
|
32
|
+
* (cache, distributed locks, publishers) that share the main REDIS_CLIENT.
|
|
33
|
+
*
|
|
34
|
+
* Features:
|
|
35
|
+
* - Auto-creates consumer group via XGROUP CREATE ... MKSTREAM
|
|
36
|
+
* - Recovers pending (unacked) messages on startup before reading new ones
|
|
37
|
+
* - XREADGROUP BLOCK for efficient new-message polling (on dedicated connection)
|
|
38
|
+
* - XACK after successful processing (on shared connection)
|
|
39
|
+
* - Graceful shutdown (finishes in-flight message, disconnects dedicated client)
|
|
40
|
+
*/
|
|
41
|
+
let RedisStreamConsumer = class RedisStreamConsumer {
|
|
42
|
+
redis;
|
|
43
|
+
logger = new common_1.Logger(this.constructor.name);
|
|
44
|
+
/** Override to filter by eventType. Return true to process. Default: all messages. */
|
|
45
|
+
shouldHandle(_fields) {
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
running = false;
|
|
49
|
+
/** Dedicated connection for blocking XREADGROUP — cloned from shared client on init */
|
|
50
|
+
blockingClient;
|
|
51
|
+
constructor(redis) {
|
|
52
|
+
this.redis = redis;
|
|
53
|
+
}
|
|
54
|
+
async onModuleInit() {
|
|
55
|
+
if (!this.redis) {
|
|
56
|
+
this.logger.warn('Redis client not available — consumer disabled');
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
// Clone a dedicated connection for blocking reads.
|
|
60
|
+
// This prevents XREADGROUP BLOCK from starving cache/lock/publish ops on the shared client.
|
|
61
|
+
this.blockingClient = this.redis.duplicate();
|
|
62
|
+
this.blockingClient.on('error', (err) => this.logger.error(`Blocking client error on ${this.streamKey}: ${err.message}`));
|
|
63
|
+
// Create consumer group (idempotent) — uses shared client (non-blocking)
|
|
64
|
+
try {
|
|
65
|
+
await this.redis.xgroup('CREATE', this.streamKey, this.consumerGroup, '0', 'MKSTREAM');
|
|
66
|
+
this.logger.log(`Created consumer group "${this.consumerGroup}" on "${this.streamKey}"`);
|
|
67
|
+
}
|
|
68
|
+
catch (err) {
|
|
69
|
+
if (!err.message?.includes('BUSYGROUP')) {
|
|
70
|
+
throw err;
|
|
71
|
+
}
|
|
72
|
+
// Group already exists — fine
|
|
73
|
+
}
|
|
74
|
+
this.running = true;
|
|
75
|
+
// Process pending messages first, then new ones
|
|
76
|
+
// Run in background so NestJS startup isn't blocked
|
|
77
|
+
void this.consumeLoop();
|
|
78
|
+
}
|
|
79
|
+
async onModuleDestroy() {
|
|
80
|
+
this.running = false;
|
|
81
|
+
// Disconnect the dedicated blocking client
|
|
82
|
+
if (this.blockingClient) {
|
|
83
|
+
this.blockingClient.disconnect();
|
|
84
|
+
this.blockingClient = undefined;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async consumeLoop() {
|
|
88
|
+
// Phase 1: recover pending (unacked) messages
|
|
89
|
+
await this.readMessages('0');
|
|
90
|
+
// Phase 2: read new messages
|
|
91
|
+
while (this.running) {
|
|
92
|
+
await this.readMessages('>');
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
async readMessages(id) {
|
|
96
|
+
if (!this.redis || !this.blockingClient || !this.running)
|
|
97
|
+
return;
|
|
98
|
+
try {
|
|
99
|
+
const blockMs = id === '>' ? 5000 : undefined;
|
|
100
|
+
const args = [
|
|
101
|
+
'GROUP',
|
|
102
|
+
this.consumerGroup,
|
|
103
|
+
this.consumerName,
|
|
104
|
+
'COUNT',
|
|
105
|
+
'10',
|
|
106
|
+
];
|
|
107
|
+
if (blockMs !== undefined) {
|
|
108
|
+
args.push('BLOCK', blockMs);
|
|
109
|
+
}
|
|
110
|
+
args.push('STREAMS', this.streamKey, id);
|
|
111
|
+
// Use dedicated blocking client for XREADGROUP — never the shared REDIS_CLIENT
|
|
112
|
+
const results = await this.blockingClient.xreadgroup(...args);
|
|
113
|
+
if (!results || results.length === 0) {
|
|
114
|
+
if (id === '0')
|
|
115
|
+
return; // No pending — switch to new messages
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const [, entries] = results[0];
|
|
119
|
+
if (entries.length === 0 && id === '0') {
|
|
120
|
+
return; // All pending recovered
|
|
121
|
+
}
|
|
122
|
+
for (const [messageId, fieldArray] of entries) {
|
|
123
|
+
// Parse flat field array into Record
|
|
124
|
+
const fields = {};
|
|
125
|
+
for (let i = 0; i < fieldArray.length; i += 2) {
|
|
126
|
+
fields[fieldArray[i]] = fieldArray[i + 1];
|
|
127
|
+
}
|
|
128
|
+
if (!this.shouldHandle(fields)) {
|
|
129
|
+
// Ack and skip — uses shared client (non-blocking)
|
|
130
|
+
await this.redis.xack(this.streamKey, this.consumerGroup, messageId);
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
try {
|
|
134
|
+
await this.handleMessage(fields);
|
|
135
|
+
// XACK on shared client — non-blocking
|
|
136
|
+
await this.redis.xack(this.streamKey, this.consumerGroup, messageId);
|
|
137
|
+
}
|
|
138
|
+
catch (err) {
|
|
139
|
+
this.logger.error(`Failed to process message ${messageId} on ${this.streamKey}: ${err.message}`, err.stack);
|
|
140
|
+
// Don't ack — message stays pending for retry on next startup
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
catch (err) {
|
|
145
|
+
if (!this.running)
|
|
146
|
+
return; // Shutdown in progress
|
|
147
|
+
this.logger.error(`Consumer read error on ${this.streamKey}: ${err.message}`, err.stack);
|
|
148
|
+
// Back off before retrying
|
|
149
|
+
await new Promise((r) => setTimeout(r, 2000));
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
exports.RedisStreamConsumer = RedisStreamConsumer;
|
|
154
|
+
exports.RedisStreamConsumer = RedisStreamConsumer = __decorate([
|
|
155
|
+
__param(0, (0, common_1.Optional)()),
|
|
156
|
+
__param(0, (0, common_1.Inject)(constants_1.REDIS_CLIENT)),
|
|
157
|
+
__metadata("design:paramtypes", [Function])
|
|
158
|
+
], RedisStreamConsumer);
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Redis } from 'ioredis';
|
|
2
|
+
import { DomainEvent } from './DomainEvent';
|
|
3
|
+
export declare class RedisStreamPublisher {
|
|
4
|
+
private readonly redis?;
|
|
5
|
+
private readonly logger;
|
|
6
|
+
constructor(redis?: Redis | undefined);
|
|
7
|
+
publish(event: DomainEvent): Promise<void>;
|
|
8
|
+
publishToStream(streamKey: string, fields: Record<string, string>): Promise<string | null>;
|
|
9
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
12
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
13
|
+
};
|
|
14
|
+
var RedisStreamPublisher_1;
|
|
15
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
|
+
exports.RedisStreamPublisher = void 0;
|
|
17
|
+
const common_1 = require("@nestjs/common");
|
|
18
|
+
const constants_1 = require("../cqrs/constants");
|
|
19
|
+
const MAX_STREAM_LENGTH = 10000;
|
|
20
|
+
let RedisStreamPublisher = RedisStreamPublisher_1 = class RedisStreamPublisher {
|
|
21
|
+
redis;
|
|
22
|
+
logger = new common_1.Logger(RedisStreamPublisher_1.name);
|
|
23
|
+
constructor(redis) {
|
|
24
|
+
this.redis = redis;
|
|
25
|
+
}
|
|
26
|
+
async publish(event) {
|
|
27
|
+
if (!this.redis) {
|
|
28
|
+
this.logger.warn('Redis client not available, skipping event publish');
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
await this.publishToStream(event.streamKey, {
|
|
32
|
+
eventId: event.eventId,
|
|
33
|
+
eventType: event.eventType,
|
|
34
|
+
aggregateId: event.aggregateId,
|
|
35
|
+
organizationId: event.organizationId || '',
|
|
36
|
+
payload: JSON.stringify(event.payload),
|
|
37
|
+
occurredAt: event.occurredAt.toISOString(),
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
async publishToStream(streamKey, fields) {
|
|
41
|
+
if (!this.redis)
|
|
42
|
+
return null;
|
|
43
|
+
try {
|
|
44
|
+
const messageId = await this.redis.xadd(streamKey, 'MAXLEN', '~', String(MAX_STREAM_LENGTH), '*', ...Object.entries(fields).flat());
|
|
45
|
+
this.logger.debug(`Published to ${streamKey}: ${messageId}`);
|
|
46
|
+
return messageId;
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
this.logger.error(`Failed to publish to ${streamKey}`, error.stack);
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
exports.RedisStreamPublisher = RedisStreamPublisher;
|
|
55
|
+
exports.RedisStreamPublisher = RedisStreamPublisher = RedisStreamPublisher_1 = __decorate([
|
|
56
|
+
(0, common_1.Injectable)(),
|
|
57
|
+
__param(0, (0, common_1.Optional)()),
|
|
58
|
+
__param(0, (0, common_1.Inject)(constants_1.REDIS_CLIENT)),
|
|
59
|
+
__metadata("design:paramtypes", [Function])
|
|
60
|
+
], RedisStreamPublisher);
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { ExceptionFilter, ArgumentsHost } from '@nestjs/common';
|
|
2
|
+
/**
|
|
3
|
+
* Global exception filter for framework-level exceptions (guards, pipes, throttler).
|
|
4
|
+
* Result<T> errors are handled by ResultInterceptor — they never reach this filter.
|
|
5
|
+
*/
|
|
6
|
+
export declare class GlobalExceptionFilter implements ExceptionFilter {
|
|
7
|
+
private readonly logger;
|
|
8
|
+
private readonly isProduction;
|
|
9
|
+
catch(exception: unknown, host: ArgumentsHost): void;
|
|
10
|
+
private toProblemDetails;
|
|
11
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var GlobalExceptionFilter_1;
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.GlobalExceptionFilter = void 0;
|
|
11
|
+
const common_1 = require("@nestjs/common");
|
|
12
|
+
const throttler_1 = require("@nestjs/throttler");
|
|
13
|
+
const CorrelationStore_1 = require("../middleware/CorrelationStore");
|
|
14
|
+
/**
|
|
15
|
+
* Global exception filter for framework-level exceptions (guards, pipes, throttler).
|
|
16
|
+
* Result<T> errors are handled by ResultInterceptor — they never reach this filter.
|
|
17
|
+
*/
|
|
18
|
+
let GlobalExceptionFilter = GlobalExceptionFilter_1 = class GlobalExceptionFilter {
|
|
19
|
+
logger = new common_1.Logger(GlobalExceptionFilter_1.name);
|
|
20
|
+
isProduction = process.env.NODE_ENV === 'production';
|
|
21
|
+
catch(exception, host) {
|
|
22
|
+
const ctx = host.switchToHttp();
|
|
23
|
+
const request = ctx.getRequest();
|
|
24
|
+
const response = ctx.getResponse();
|
|
25
|
+
const correlationId = CorrelationStore_1.correlationStore.getStore()?.correlationId;
|
|
26
|
+
if (response.headersSent)
|
|
27
|
+
return;
|
|
28
|
+
if (correlationId) {
|
|
29
|
+
response.setHeader('X-Correlation-ID', correlationId);
|
|
30
|
+
}
|
|
31
|
+
const problem = this.toProblemDetails(exception, correlationId, request.originalUrl);
|
|
32
|
+
if (problem.retryAfter) {
|
|
33
|
+
response.setHeader('Retry-After', String(problem.retryAfter));
|
|
34
|
+
}
|
|
35
|
+
this.logger.error({
|
|
36
|
+
msg: `${problem.status} ${problem.title}`,
|
|
37
|
+
correlationId,
|
|
38
|
+
status: problem.status,
|
|
39
|
+
detail: problem.detail,
|
|
40
|
+
});
|
|
41
|
+
response
|
|
42
|
+
.status(problem.status)
|
|
43
|
+
.setHeader('Content-Type', 'application/problem+json')
|
|
44
|
+
.json(problem);
|
|
45
|
+
}
|
|
46
|
+
toProblemDetails(exception, correlationId, instance) {
|
|
47
|
+
// ThrottlerException → 429
|
|
48
|
+
if (exception instanceof throttler_1.ThrottlerException) {
|
|
49
|
+
return {
|
|
50
|
+
type: 'https://arex.dev/errors/RATE_LIMITED',
|
|
51
|
+
title: 'Too Many Requests',
|
|
52
|
+
status: 429,
|
|
53
|
+
detail: 'Rate limit exceeded. Please retry later.',
|
|
54
|
+
instance,
|
|
55
|
+
correlationId,
|
|
56
|
+
retryAfter: 60,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
// NestJS HttpException (guards, pipes, etc.)
|
|
60
|
+
if (exception instanceof common_1.HttpException) {
|
|
61
|
+
const status = exception.getStatus();
|
|
62
|
+
const exceptionResponse = exception.getResponse();
|
|
63
|
+
const detail = typeof exceptionResponse === 'string'
|
|
64
|
+
? exceptionResponse
|
|
65
|
+
: exceptionResponse.message;
|
|
66
|
+
if (status === 400 && Array.isArray(detail)) {
|
|
67
|
+
return {
|
|
68
|
+
type: 'https://arex.dev/errors/VALIDATION_ERROR',
|
|
69
|
+
title: 'Validation Error',
|
|
70
|
+
status: 400,
|
|
71
|
+
detail: 'One or more validation errors occurred.',
|
|
72
|
+
instance,
|
|
73
|
+
correlationId,
|
|
74
|
+
errors: detail.map((msg) => ({ message: msg })),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
type: `https://arex.dev/errors/HTTP_${status}`,
|
|
79
|
+
title: exception.name,
|
|
80
|
+
status,
|
|
81
|
+
detail: typeof detail === 'string' ? detail : JSON.stringify(detail),
|
|
82
|
+
instance,
|
|
83
|
+
correlationId,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
// Unhandled errors (middleware crashes, etc.)
|
|
87
|
+
const error = exception instanceof Error ? exception : new Error(String(exception));
|
|
88
|
+
return {
|
|
89
|
+
type: 'https://arex.dev/errors/INTERNAL_ERROR',
|
|
90
|
+
title: 'Internal Server Error',
|
|
91
|
+
status: 500,
|
|
92
|
+
detail: this.isProduction ? 'An unexpected error occurred.' : error.message,
|
|
93
|
+
instance,
|
|
94
|
+
correlationId,
|
|
95
|
+
...(this.isProduction ? {} : { stack: error.stack }),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
exports.GlobalExceptionFilter = GlobalExceptionFilter;
|
|
100
|
+
exports.GlobalExceptionFilter = GlobalExceptionFilter = GlobalExceptionFilter_1 = __decorate([
|
|
101
|
+
(0, common_1.Catch)()
|
|
102
|
+
], GlobalExceptionFilter);
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { ExecutionContext } from '@nestjs/common';
|
|
2
|
+
import { Reflector } from '@nestjs/core';
|
|
3
|
+
export declare const Public: () => (target: object, _key?: string | symbol, descriptor?: PropertyDescriptor) => void;
|
|
4
|
+
declare const JwtAuthGuard_base: import("@nestjs/passport").Type<import("@nestjs/passport").IAuthGuard>;
|
|
5
|
+
export declare class JwtAuthGuard extends JwtAuthGuard_base {
|
|
6
|
+
private readonly reflector;
|
|
7
|
+
constructor(reflector: Reflector);
|
|
8
|
+
canActivate(context: ExecutionContext): boolean | Promise<boolean> | import("rxjs").Observable<boolean>;
|
|
9
|
+
}
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.JwtAuthGuard = exports.Public = void 0;
|
|
13
|
+
const common_1 = require("@nestjs/common");
|
|
14
|
+
const core_1 = require("@nestjs/core");
|
|
15
|
+
const passport_1 = require("@nestjs/passport");
|
|
16
|
+
const IS_PUBLIC_KEY = 'isPublic';
|
|
17
|
+
const Public = () => (target, _key, descriptor) => {
|
|
18
|
+
if (descriptor) {
|
|
19
|
+
Reflect.defineMetadata(IS_PUBLIC_KEY, true, descriptor.value);
|
|
20
|
+
}
|
|
21
|
+
else {
|
|
22
|
+
Reflect.defineMetadata(IS_PUBLIC_KEY, true, target);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
exports.Public = Public;
|
|
26
|
+
let JwtAuthGuard = class JwtAuthGuard extends (0, passport_1.AuthGuard)('jwt') {
|
|
27
|
+
reflector;
|
|
28
|
+
constructor(reflector) {
|
|
29
|
+
super();
|
|
30
|
+
this.reflector = reflector;
|
|
31
|
+
}
|
|
32
|
+
canActivate(context) {
|
|
33
|
+
const isPublic = this.reflector.getAllAndOverride(IS_PUBLIC_KEY, [
|
|
34
|
+
context.getHandler(),
|
|
35
|
+
context.getClass(),
|
|
36
|
+
]);
|
|
37
|
+
if (isPublic)
|
|
38
|
+
return true;
|
|
39
|
+
return super.canActivate(context);
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
exports.JwtAuthGuard = JwtAuthGuard;
|
|
43
|
+
exports.JwtAuthGuard = JwtAuthGuard = __decorate([
|
|
44
|
+
(0, common_1.Injectable)(),
|
|
45
|
+
__metadata("design:paramtypes", [core_1.Reflector])
|
|
46
|
+
], JwtAuthGuard);
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Strategy } from 'passport-jwt';
|
|
2
|
+
export interface JwtPayload {
|
|
3
|
+
sub: string;
|
|
4
|
+
email: string;
|
|
5
|
+
realm_access?: {
|
|
6
|
+
roles: string[];
|
|
7
|
+
};
|
|
8
|
+
preferred_username?: string;
|
|
9
|
+
}
|
|
10
|
+
declare const JwtStrategy_base: new (...args: [opt: import("passport-jwt").StrategyOptionsWithRequest] | [opt: import("passport-jwt").StrategyOptionsWithoutRequest]) => Strategy & {
|
|
11
|
+
validate(...args: any[]): unknown;
|
|
12
|
+
};
|
|
13
|
+
export declare class JwtStrategy extends JwtStrategy_base {
|
|
14
|
+
constructor();
|
|
15
|
+
validate(payload: JwtPayload): {
|
|
16
|
+
keycloakId: string;
|
|
17
|
+
email: string;
|
|
18
|
+
roles: string[];
|
|
19
|
+
username: string | undefined;
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export {};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.JwtStrategy = void 0;
|
|
13
|
+
const common_1 = require("@nestjs/common");
|
|
14
|
+
const passport_1 = require("@nestjs/passport");
|
|
15
|
+
const passport_jwt_1 = require("passport-jwt");
|
|
16
|
+
const jwks_rsa_1 = require("jwks-rsa");
|
|
17
|
+
let JwtStrategy = class JwtStrategy extends (0, passport_1.PassportStrategy)(passport_jwt_1.Strategy) {
|
|
18
|
+
constructor() {
|
|
19
|
+
const internalUrl = process.env.KEYCLOAK_INTERNAL_URL || process.env.KEYCLOAK_URL || 'http://localhost:8080';
|
|
20
|
+
const publicUrl = process.env.KEYCLOAK_URL || 'http://localhost:8080';
|
|
21
|
+
const realm = process.env.KEYCLOAK_REALM || 'arex';
|
|
22
|
+
super({
|
|
23
|
+
jwtFromRequest: passport_jwt_1.ExtractJwt.fromAuthHeaderAsBearerToken(),
|
|
24
|
+
secretOrKeyProvider: (0, jwks_rsa_1.passportJwtSecret)({
|
|
25
|
+
jwksUri: `${internalUrl}/realms/${realm}/protocol/openid-connect/certs`,
|
|
26
|
+
cache: true,
|
|
27
|
+
cacheMaxAge: 600_000,
|
|
28
|
+
rateLimit: true,
|
|
29
|
+
}),
|
|
30
|
+
issuer: `${publicUrl}/realms/${realm}`,
|
|
31
|
+
algorithms: ['RS256'],
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
validate(payload) {
|
|
35
|
+
return {
|
|
36
|
+
keycloakId: payload.sub,
|
|
37
|
+
email: payload.email,
|
|
38
|
+
roles: payload.realm_access?.roles || [],
|
|
39
|
+
username: payload.preferred_username,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
exports.JwtStrategy = JwtStrategy;
|
|
44
|
+
exports.JwtStrategy = JwtStrategy = __decorate([
|
|
45
|
+
(0, common_1.Injectable)(),
|
|
46
|
+
__metadata("design:paramtypes", [])
|
|
47
|
+
], JwtStrategy);
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { CanActivate, ExecutionContext } from '@nestjs/common';
|
|
2
|
+
import { Reflector } from '@nestjs/core';
|
|
3
|
+
export declare const Roles: (...roles: string[]) => ClassDecorator & MethodDecorator;
|
|
4
|
+
export declare class RolesGuard implements CanActivate {
|
|
5
|
+
private readonly reflector;
|
|
6
|
+
constructor(reflector: Reflector);
|
|
7
|
+
canActivate(context: ExecutionContext): boolean;
|
|
8
|
+
}
|