@flusys/nestjs-shared 7.0.2 → 8.0.0-beta.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/classes/api-controller.class.d.ts +4 -4
- package/classes/api-service.class.d.ts +7 -7
- package/classes/disabled-event-bus.class.d.ts +1 -1
- package/classes/domain-event.publisher.d.ts +1 -1
- package/classes/event-bus.registry.d.ts +1 -1
- package/classes/event-transports/event-transport.registry.d.ts +1 -1
- package/classes/event-transports/index.d.ts +2 -2
- package/classes/event-transports/kafka-transport.optional.d.ts +1 -1
- package/classes/event-transports/memory-transport.d.ts +1 -1
- package/classes/event-transports/rabbitmq-transport.optional.d.ts +1 -1
- package/classes/hybrid-event-bus.class.d.ts +1 -1
- package/classes/index.d.ts +11 -11
- package/constants/index.d.ts +2 -2
- package/constants/permissions.d.ts +12 -0
- package/decorators/api-response.decorator.d.ts +1 -1
- package/decorators/current-user.decorator.d.ts +1 -1
- package/decorators/index.d.ts +6 -6
- package/decorators/require-permission.decorator.d.ts +1 -1
- package/dtos/filter-and-pagination.dto.d.ts +1 -1
- package/dtos/index.d.ts +6 -6
- package/entities/index.d.ts +3 -3
- package/enums/index.d.ts +3 -3
- package/exceptions/index.d.ts +2 -2
- package/fesm/470.js +2713 -0
- package/fesm/509.js +793 -0
- package/fesm/667.js +606 -0
- package/fesm/67.js +808 -0
- package/fesm/720.js +914 -0
- package/{cjs/classes/event-transports/rabbitmq-transport.optional.js → fesm/chunks/123.js} +78 -55
- package/fesm/{classes/event-transports/kafka-transport.optional.js → chunks/37.js} +74 -41
- package/fesm/classes/index.js +62 -12
- package/fesm/constants/index.js +445 -17
- package/fesm/decorators/index.js +341 -6
- package/fesm/dtos/index.js +23 -6
- package/fesm/entities/index.js +336 -3
- package/fesm/enums/index.js +57 -3
- package/fesm/exceptions/index.js +280 -2
- package/fesm/guards/index.js +1003 -3
- package/fesm/index.js +1524 -14
- package/fesm/interceptors/index.js +924 -5
- package/fesm/interfaces/index.js +57 -11
- package/fesm/middlewares/index.js +33 -1
- package/fesm/modules/index.js +432 -9
- package/fesm/runtime.js +134 -0
- package/fesm/utils/index.js +1045 -8
- package/filters/global-exception.filter.d.ts +1 -1
- package/filters/index.d.ts +1 -1
- package/guards/index.d.ts +3 -3
- package/guards/jwt-auth.guard.d.ts +1 -1
- package/guards/optional-jwt-auth.guard.d.ts +1 -1
- package/guards/permission.guard.d.ts +2 -2
- package/index.d.ts +14 -14
- package/interceptors/delete-empty-id-from-body.interceptor.d.ts +1 -1
- package/interceptors/idempotency.interceptor.d.ts +2 -2
- package/interceptors/index.d.ts +5 -5
- package/interceptors/response-meta.interceptor.d.ts +1 -1
- package/interceptors/set-user-field-on-body.interceptor.d.ts +1 -1
- package/interceptors/slug.interceptor.d.ts +2 -2
- package/interfaces/ai-assistant-adapter.interface.d.ts +1 -1
- package/interfaces/api.interface.d.ts +2 -2
- package/interfaces/datasource.interface.d.ts +1 -1
- package/interfaces/event-manager-adapter.interface.d.ts +2 -2
- package/interfaces/index.d.ts +11 -11
- package/interfaces/module-config.interface.d.ts +1 -1
- package/interfaces/notification-adapter.interface.d.ts +1 -1
- package/middlewares/index.d.ts +1 -1
- package/middlewares/logger.middleware.d.ts +2 -2
- package/modules/cache/cache.module.d.ts +1 -1
- package/modules/datasource/index.d.ts +1 -1
- package/modules/datasource/multi-tenant-datasource.service.d.ts +4 -4
- package/modules/event-bus/event-bus.explorer.d.ts +2 -2
- package/modules/event-bus/event-bus.module.d.ts +2 -2
- package/modules/event-bus/module-events.provider.d.ts +1 -1
- package/modules/index.d.ts +9 -9
- package/modules/shared-permission-cache/shared-permission-cache.service.d.ts +3 -3
- package/modules/utils/utils.service.d.ts +1 -1
- package/package.json +30 -44
- package/utils/index.d.ts +8 -8
- package/utils/permission-cache-key.util.d.ts +1 -1
- package/utils/query-helpers.util.d.ts +2 -2
- package/utils/request.util.d.ts +1 -1
- package/cjs/classes/api-controller.class.js +0 -728
- package/cjs/classes/api-controller.class.spec.js +0 -684
- package/cjs/classes/api-service.class.js +0 -631
- package/cjs/classes/api-service.class.spec.js +0 -1137
- package/cjs/classes/disabled-event-bus.class.js +0 -15
- package/cjs/classes/disabled-event-bus.class.spec.js +0 -40
- package/cjs/classes/domain-event.publisher.js +0 -76
- package/cjs/classes/domain-event.publisher.spec.js +0 -234
- package/cjs/classes/event-bus.registry.js +0 -68
- package/cjs/classes/event-bus.registry.spec.js +0 -141
- package/cjs/classes/event-transports/event-transport.registry.js +0 -41
- package/cjs/classes/event-transports/event-transport.registry.spec.js +0 -31
- package/cjs/classes/event-transports/index.js +0 -23
- package/cjs/classes/event-transports/kafka-transport.optional.js +0 -151
- package/cjs/classes/event-transports/kafka-transport.optional.spec.js +0 -198
- package/cjs/classes/event-transports/memory-transport.js +0 -53
- package/cjs/classes/event-transports/memory-transport.spec.js +0 -57
- package/cjs/classes/event-transports/rabbitmq-transport.optional.spec.js +0 -255
- package/cjs/classes/handle-custome-db.js +0 -37
- package/cjs/classes/handle-custome-db.spec.js +0 -82
- package/cjs/classes/hybrid-cache.class.js +0 -96
- package/cjs/classes/hybrid-cache.class.spec.js +0 -168
- package/cjs/classes/hybrid-event-bus.class.js +0 -281
- package/cjs/classes/hybrid-event-bus.class.spec.js +0 -218
- package/cjs/classes/index.js +0 -28
- package/cjs/classes/winston.logger.class.js +0 -274
- package/cjs/classes/winston.logger.class.spec.js +0 -330
- package/cjs/constants/index.js +0 -88
- package/cjs/constants/message-keys.js +0 -68
- package/cjs/constants/permissions.js +0 -297
- package/cjs/decorators/api-response.decorator.js +0 -52
- package/cjs/decorators/api-response.decorator.spec.js +0 -126
- package/cjs/decorators/current-user.decorator.js +0 -16
- package/cjs/decorators/current-user.decorator.spec.js +0 -74
- package/cjs/decorators/index.js +0 -23
- package/cjs/decorators/log-action.decorator.js +0 -149
- package/cjs/decorators/log-action.decorator.spec.js +0 -353
- package/cjs/decorators/on-domain-event.decorator.js +0 -13
- package/cjs/decorators/on-domain-event.decorator.spec.js +0 -50
- package/cjs/decorators/public.decorator.js +0 -13
- package/cjs/decorators/public.decorator.spec.js +0 -50
- package/cjs/decorators/require-permission.decorator.js +0 -32
- package/cjs/decorators/require-permission.decorator.spec.js +0 -147
- package/cjs/dtos/delete.dto.js +0 -92
- package/cjs/dtos/filter-and-pagination.dto.js +0 -164
- package/cjs/dtos/get-by-ids.dto.js +0 -65
- package/cjs/dtos/identity-response.dto.js +0 -108
- package/cjs/dtos/index.js +0 -23
- package/cjs/dtos/pagination.dto.js +0 -67
- package/cjs/dtos/response-payload.dto.js +0 -369
- package/cjs/entities/identity.js +0 -100
- package/cjs/entities/index.js +0 -20
- package/cjs/entities/raw-type.js +0 -4
- package/cjs/entities/user-root.js +0 -189
- package/cjs/enums/index.js +0 -20
- package/cjs/enums/notification-type.enum.js +0 -17
- package/cjs/enums/participant-status.enum.js +0 -17
- package/cjs/enums/recurrence-type.enum.js +0 -18
- package/cjs/exceptions/base-app.exception.js +0 -151
- package/cjs/exceptions/base-app.exception.spec.js +0 -157
- package/cjs/exceptions/index.js +0 -19
- package/cjs/exceptions/permission.exception.js +0 -56
- package/cjs/exceptions/permission.exception.spec.js +0 -82
- package/cjs/filters/global-exception.filter.js +0 -279
- package/cjs/filters/global-exception.filter.spec.js +0 -440
- package/cjs/filters/index.js +0 -18
- package/cjs/guards/index.js +0 -20
- package/cjs/guards/jwt-auth.guard.js +0 -75
- package/cjs/guards/jwt-auth.guard.spec.js +0 -75
- package/cjs/guards/optional-jwt-auth.guard.js +0 -67
- package/cjs/guards/optional-jwt-auth.guard.spec.js +0 -55
- package/cjs/guards/permission.guard.js +0 -179
- package/cjs/guards/permission.guard.spec.js +0 -373
- package/cjs/index.js +0 -31
- package/cjs/interceptors/delete-empty-id-from-body.interceptor.js +0 -40
- package/cjs/interceptors/delete-empty-id-from-body.interceptor.spec.js +0 -107
- package/cjs/interceptors/idempotency.interceptor.js +0 -96
- package/cjs/interceptors/idempotency.interceptor.spec.js +0 -116
- package/cjs/interceptors/index.js +0 -22
- package/cjs/interceptors/response-meta.interceptor.js +0 -47
- package/cjs/interceptors/response-meta.interceptor.spec.js +0 -89
- package/cjs/interceptors/set-user-field-on-body.interceptor.js +0 -60
- package/cjs/interceptors/set-user-field-on-body.interceptor.spec.js +0 -128
- package/cjs/interceptors/slug.interceptor.js +0 -75
- package/cjs/interceptors/slug.interceptor.spec.js +0 -110
- package/cjs/interfaces/ai-assistant-adapter.interface.js +0 -24
- package/cjs/interfaces/api.interface.js +0 -4
- package/cjs/interfaces/datasource.interface.js +0 -4
- package/cjs/interfaces/event-bus.interface.js +0 -4
- package/cjs/interfaces/event-manager-adapter.interface.js +0 -11
- package/cjs/interfaces/identity.interface.js +0 -4
- package/cjs/interfaces/index.js +0 -28
- package/cjs/interfaces/logged-user-info.interface.js +0 -6
- package/cjs/interfaces/module-config.interface.js +0 -4
- package/cjs/interfaces/notification-adapter.interface.js +0 -11
- package/cjs/interfaces/permission-sync-adapter.interface.js +0 -11
- package/cjs/interfaces/permission.interface.js +0 -4
- package/cjs/middlewares/index.js +0 -18
- package/cjs/middlewares/logger.middleware.js +0 -264
- package/cjs/middlewares/logger.middleware.spec.js +0 -462
- package/cjs/modules/cache/cache.module.js +0 -39
- package/cjs/modules/cache/cache.module.spec.js +0 -48
- package/cjs/modules/datasource/index.js +0 -18
- package/cjs/modules/datasource/multi-tenant-datasource.service.js +0 -222
- package/cjs/modules/datasource/multi-tenant-datasource.service.spec.js +0 -381
- package/cjs/modules/event-bus/event-bus.explorer.js +0 -124
- package/cjs/modules/event-bus/event-bus.explorer.spec.js +0 -189
- package/cjs/modules/event-bus/event-bus.integration.spec.js +0 -253
- package/cjs/modules/event-bus/event-bus.module.js +0 -94
- package/cjs/modules/event-bus/event-bus.module.spec.js +0 -149
- package/cjs/modules/event-bus/module-events.provider.js +0 -39
- package/cjs/modules/event-bus/module-events.provider.spec.js +0 -56
- package/cjs/modules/index.js +0 -26
- package/cjs/modules/shared-permission-cache/shared-permission-cache.module.js +0 -32
- package/cjs/modules/shared-permission-cache/shared-permission-cache.service.js +0 -101
- package/cjs/modules/shared-permission-cache/shared-permission-cache.service.spec.js +0 -165
- package/cjs/modules/utils/utils.module.js +0 -32
- package/cjs/modules/utils/utils.service.js +0 -76
- package/cjs/modules/utils/utils.service.spec.js +0 -169
- package/cjs/utils/date-time.util.js +0 -94
- package/cjs/utils/date-time.util.spec.js +0 -84
- package/cjs/utils/event-pattern.util.js +0 -103
- package/cjs/utils/event-pattern.util.spec.js +0 -251
- package/cjs/utils/html-sanitizer.util.js +0 -64
- package/cjs/utils/html-sanitizer.util.spec.js +0 -76
- package/cjs/utils/index.js +0 -25
- package/cjs/utils/optional-module.util.js +0 -35
- package/cjs/utils/optional-module.util.spec.js +0 -14
- package/cjs/utils/permission-cache-key.util.js +0 -31
- package/cjs/utils/permission-cache-key.util.spec.js +0 -88
- package/cjs/utils/query-helpers.util.js +0 -60
- package/cjs/utils/query-helpers.util.spec.js +0 -209
- package/cjs/utils/request.util.js +0 -96
- package/cjs/utils/request.util.spec.js +0 -249
- package/cjs/utils/string.util.js +0 -63
- package/cjs/utils/string.util.spec.js +0 -63
- package/fesm/classes/api-controller.class.js +0 -718
- package/fesm/classes/api-controller.class.spec.js +0 -680
- package/fesm/classes/api-service.class.js +0 -621
- package/fesm/classes/api-service.class.spec.js +0 -1133
- package/fesm/classes/disabled-event-bus.class.js +0 -11
- package/fesm/classes/disabled-event-bus.class.spec.js +0 -36
- package/fesm/classes/domain-event.publisher.js +0 -63
- package/fesm/classes/domain-event.publisher.spec.js +0 -230
- package/fesm/classes/event-bus.registry.js +0 -64
- package/fesm/classes/event-bus.registry.spec.js +0 -137
- package/fesm/classes/event-transports/event-transport.registry.js +0 -35
- package/fesm/classes/event-transports/event-transport.registry.spec.js +0 -27
- package/fesm/classes/event-transports/index.js +0 -6
- package/fesm/classes/event-transports/kafka-transport.optional.spec.js +0 -194
- package/fesm/classes/event-transports/memory-transport.js +0 -49
- package/fesm/classes/event-transports/memory-transport.spec.js +0 -53
- package/fesm/classes/event-transports/rabbitmq-transport.optional.js +0 -174
- package/fesm/classes/event-transports/rabbitmq-transport.optional.spec.js +0 -251
- package/fesm/classes/handle-custome-db.js +0 -19
- package/fesm/classes/handle-custome-db.spec.js +0 -78
- package/fesm/classes/hybrid-cache.class.js +0 -81
- package/fesm/classes/hybrid-cache.class.spec.js +0 -164
- package/fesm/classes/hybrid-event-bus.class.js +0 -237
- package/fesm/classes/hybrid-event-bus.class.spec.js +0 -214
- package/fesm/classes/winston.logger.class.js +0 -228
- package/fesm/classes/winston.logger.class.spec.js +0 -327
- package/fesm/constants/message-keys.js +0 -49
- package/fesm/constants/permissions.js +0 -208
- package/fesm/decorators/api-response.decorator.js +0 -42
- package/fesm/decorators/api-response.decorator.spec.js +0 -122
- package/fesm/decorators/current-user.decorator.js +0 -18
- package/fesm/decorators/current-user.decorator.spec.js +0 -73
- package/fesm/decorators/log-action.decorator.js +0 -139
- package/fesm/decorators/log-action.decorator.spec.js +0 -349
- package/fesm/decorators/on-domain-event.decorator.js +0 -10
- package/fesm/decorators/on-domain-event.decorator.spec.js +0 -46
- package/fesm/decorators/public.decorator.js +0 -20
- package/fesm/decorators/public.decorator.spec.js +0 -46
- package/fesm/decorators/require-permission.decorator.js +0 -27
- package/fesm/decorators/require-permission.decorator.spec.js +0 -143
- package/fesm/dtos/delete.dto.js +0 -82
- package/fesm/dtos/filter-and-pagination.dto.js +0 -148
- package/fesm/dtos/get-by-ids.dto.js +0 -55
- package/fesm/dtos/identity-response.dto.js +0 -98
- package/fesm/dtos/pagination.dto.js +0 -57
- package/fesm/dtos/response-payload.dto.js +0 -336
- package/fesm/entities/identity.js +0 -90
- package/fesm/entities/raw-type.js +0 -1
- package/fesm/entities/user-root.js +0 -179
- package/fesm/enums/notification-type.enum.js +0 -7
- package/fesm/enums/participant-status.enum.js +0 -7
- package/fesm/enums/recurrence-type.enum.js +0 -8
- package/fesm/exceptions/base-app.exception.js +0 -115
- package/fesm/exceptions/base-app.exception.spec.js +0 -153
- package/fesm/exceptions/permission.exception.js +0 -35
- package/fesm/exceptions/permission.exception.spec.js +0 -78
- package/fesm/filters/global-exception.filter.js +0 -269
- package/fesm/filters/global-exception.filter.spec.js +0 -436
- package/fesm/filters/index.js +0 -1
- package/fesm/guards/jwt-auth.guard.js +0 -65
- package/fesm/guards/jwt-auth.guard.spec.js +0 -71
- package/fesm/guards/optional-jwt-auth.guard.js +0 -57
- package/fesm/guards/optional-jwt-auth.guard.spec.js +0 -51
- package/fesm/guards/permission.guard.js +0 -169
- package/fesm/guards/permission.guard.spec.js +0 -369
- package/fesm/interceptors/delete-empty-id-from-body.interceptor.js +0 -30
- package/fesm/interceptors/delete-empty-id-from-body.interceptor.spec.js +0 -103
- package/fesm/interceptors/idempotency.interceptor.js +0 -86
- package/fesm/interceptors/idempotency.interceptor.spec.js +0 -112
- package/fesm/interceptors/response-meta.interceptor.js +0 -37
- package/fesm/interceptors/response-meta.interceptor.spec.js +0 -85
- package/fesm/interceptors/set-user-field-on-body.interceptor.js +0 -39
- package/fesm/interceptors/set-user-field-on-body.interceptor.spec.js +0 -124
- package/fesm/interceptors/slug.interceptor.js +0 -65
- package/fesm/interceptors/slug.interceptor.spec.js +0 -106
- package/fesm/interfaces/ai-assistant-adapter.interface.js +0 -3
- package/fesm/interfaces/api.interface.js +0 -1
- package/fesm/interfaces/datasource.interface.js +0 -1
- package/fesm/interfaces/event-bus.interface.js +0 -1
- package/fesm/interfaces/event-manager-adapter.interface.js +0 -1
- package/fesm/interfaces/identity.interface.js +0 -1
- package/fesm/interfaces/logged-user-info.interface.js +0 -3
- package/fesm/interfaces/module-config.interface.js +0 -5
- package/fesm/interfaces/notification-adapter.interface.js +0 -1
- package/fesm/interfaces/permission-sync-adapter.interface.js +0 -1
- package/fesm/interfaces/permission.interface.js +0 -1
- package/fesm/middlewares/logger.middleware.js +0 -235
- package/fesm/middlewares/logger.middleware.spec.js +0 -459
- package/fesm/modules/cache/cache.module.js +0 -29
- package/fesm/modules/cache/cache.module.spec.js +0 -44
- package/fesm/modules/datasource/index.js +0 -1
- package/fesm/modules/datasource/multi-tenant-datasource.service.js +0 -212
- package/fesm/modules/datasource/multi-tenant-datasource.service.spec.js +0 -377
- package/fesm/modules/event-bus/event-bus.explorer.js +0 -114
- package/fesm/modules/event-bus/event-bus.explorer.spec.js +0 -185
- package/fesm/modules/event-bus/event-bus.integration.spec.js +0 -249
- package/fesm/modules/event-bus/event-bus.module.js +0 -84
- package/fesm/modules/event-bus/event-bus.module.spec.js +0 -145
- package/fesm/modules/event-bus/module-events.provider.js +0 -26
- package/fesm/modules/event-bus/module-events.provider.spec.js +0 -52
- package/fesm/modules/shared-permission-cache/shared-permission-cache.module.js +0 -22
- package/fesm/modules/shared-permission-cache/shared-permission-cache.service.js +0 -91
- package/fesm/modules/shared-permission-cache/shared-permission-cache.service.spec.js +0 -161
- package/fesm/modules/utils/utils.module.js +0 -22
- package/fesm/modules/utils/utils.service.js +0 -66
- package/fesm/modules/utils/utils.service.spec.js +0 -165
- package/fesm/utils/date-time.util.js +0 -70
- package/fesm/utils/date-time.util.spec.js +0 -80
- package/fesm/utils/event-pattern.util.js +0 -91
- package/fesm/utils/event-pattern.util.spec.js +0 -247
- package/fesm/utils/html-sanitizer.util.js +0 -69
- package/fesm/utils/html-sanitizer.util.spec.js +0 -72
- package/fesm/utils/optional-module.util.js +0 -25
- package/fesm/utils/optional-module.util.spec.js +0 -10
- package/fesm/utils/permission-cache-key.util.js +0 -10
- package/fesm/utils/permission-cache-key.util.spec.js +0 -84
- package/fesm/utils/query-helpers.util.js +0 -85
- package/fesm/utils/query-helpers.util.spec.js +0 -205
- package/fesm/utils/request.util.js +0 -81
- package/fesm/utils/request.util.spec.js +0 -245
- package/fesm/utils/string.util.js +0 -71
- package/fesm/utils/string.util.spec.js +0 -59
|
@@ -1,237 +0,0 @@
|
|
|
1
|
-
function _define_property(obj, key, value) {
|
|
2
|
-
if (key in obj) {
|
|
3
|
-
Object.defineProperty(obj, key, {
|
|
4
|
-
value: value,
|
|
5
|
-
enumerable: true,
|
|
6
|
-
configurable: true,
|
|
7
|
-
writable: true
|
|
8
|
-
});
|
|
9
|
-
} else {
|
|
10
|
-
obj[key] = value;
|
|
11
|
-
}
|
|
12
|
-
return obj;
|
|
13
|
-
}
|
|
14
|
-
import { envConfig } from '@flusys/nestjs-core/config';
|
|
15
|
-
import { Logger } from '@nestjs/common';
|
|
16
|
-
import { matchEventPattern } from '../utils/event-pattern.util';
|
|
17
|
-
import { EventTransportRegistry } from './event-transports/event-transport.registry';
|
|
18
|
-
import { MemoryTransport } from './event-transports/memory-transport';
|
|
19
|
-
const DEFAULT_DEDUPE_SIZE = 5000;
|
|
20
|
-
/**
|
|
21
|
-
* Event counterpart of HybridCache: one wrapper, transport chosen by configuration.
|
|
22
|
-
*
|
|
23
|
-
* - `memory` in-process only, no broker required (default)
|
|
24
|
-
* - `rabbitmq` topic exchange, cross-service
|
|
25
|
-
* - `kafka` single topic, cross-service
|
|
26
|
-
* - `hybrid` both, with duplicate delivery suppressed by event id
|
|
27
|
-
*/ export class HybridEventBus {
|
|
28
|
-
getTransportLabel() {
|
|
29
|
-
return this.label;
|
|
30
|
-
}
|
|
31
|
-
getActiveTransports() {
|
|
32
|
-
return this.transports.map((transport)=>transport.name);
|
|
33
|
-
}
|
|
34
|
-
async connect() {
|
|
35
|
-
if (this.connected) return;
|
|
36
|
-
if (!this.connecting) {
|
|
37
|
-
this.connecting = this.buildTransports().catch((error)=>{
|
|
38
|
-
// A cached rejection would leave the bus dead for the process lifetime
|
|
39
|
-
this.connecting = undefined;
|
|
40
|
-
throw error;
|
|
41
|
-
});
|
|
42
|
-
}
|
|
43
|
-
await this.connecting;
|
|
44
|
-
this.connected = true;
|
|
45
|
-
}
|
|
46
|
-
async publish(event) {
|
|
47
|
-
if (!await this.ensureConnected()) return;
|
|
48
|
-
await Promise.all(this.transports.map((transport)=>transport.publish(event).catch((error)=>{
|
|
49
|
-
this.logger.warn(`Publish failed on ${transport.name}: ${error.message}`);
|
|
50
|
-
})));
|
|
51
|
-
}
|
|
52
|
-
async subscribe(pattern, handler) {
|
|
53
|
-
this.subscriptions.push({
|
|
54
|
-
pattern,
|
|
55
|
-
handler: handler
|
|
56
|
-
});
|
|
57
|
-
if (!await this.ensureConnected()) return;
|
|
58
|
-
await this.bindSubscriptions();
|
|
59
|
-
}
|
|
60
|
-
async close() {
|
|
61
|
-
await Promise.allSettled(this.transports.map((transport)=>transport.close()));
|
|
62
|
-
this.transports.length = 0;
|
|
63
|
-
this.subscriptions.length = 0;
|
|
64
|
-
this.boundPatterns.clear();
|
|
65
|
-
this.seenIds.clear();
|
|
66
|
-
this.seenOrder.length = 0;
|
|
67
|
-
this.memory = undefined;
|
|
68
|
-
this.connecting = undefined;
|
|
69
|
-
this.connected = false;
|
|
70
|
-
}
|
|
71
|
-
// ─── Private Helpers ────────────────────────────────────────────────────────
|
|
72
|
-
/**
|
|
73
|
-
* Connecting must never throw at the call site - a bus that cannot start is
|
|
74
|
-
* a degraded system, not a failed request. The next call retries.
|
|
75
|
-
*/ async ensureConnected() {
|
|
76
|
-
try {
|
|
77
|
-
await this.connect();
|
|
78
|
-
return true;
|
|
79
|
-
} catch (error) {
|
|
80
|
-
const message = error instanceof Error ? error.message : 'Unknown error';
|
|
81
|
-
this.logger.error(`Event bus is not available: ${message}`);
|
|
82
|
-
return false;
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
resolveLabelFromEnv() {
|
|
86
|
-
const value = envConfig.tryGetValue('USE_EVENT_LABEL', false) || 'memory';
|
|
87
|
-
return value;
|
|
88
|
-
}
|
|
89
|
-
async buildTransports() {
|
|
90
|
-
// Fresh transports know nothing of what was bound on the ones they replace
|
|
91
|
-
this.boundPatterns.clear();
|
|
92
|
-
if (this.label === 'memory' || this.label === 'hybrid') {
|
|
93
|
-
this.memory = new MemoryTransport();
|
|
94
|
-
await this.memory.connect();
|
|
95
|
-
this.registerTransport(this.memory);
|
|
96
|
-
}
|
|
97
|
-
if (this.label !== 'memory') {
|
|
98
|
-
const broker = await this.createBrokerTransport(this.label);
|
|
99
|
-
if (broker) {
|
|
100
|
-
this.registerTransport(broker);
|
|
101
|
-
} else {
|
|
102
|
-
this.logger.error(`Event transport '${this.label}' was requested but is unavailable - delivering ` + `in-process only, so no event will reach another service. Check the broker URL ` + `and that its driver is installed.`);
|
|
103
|
-
if (!this.memory) {
|
|
104
|
-
this.memory = new MemoryTransport();
|
|
105
|
-
await this.memory.connect();
|
|
106
|
-
this.registerTransport(this.memory);
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
await this.bindSubscriptions();
|
|
111
|
-
}
|
|
112
|
-
/**
|
|
113
|
-
* Binds every pattern the bus knows about, skipping the ones already bound.
|
|
114
|
-
*
|
|
115
|
-
* Called once the transports are built, not only from `subscribe`: a
|
|
116
|
-
* subscription taken while the bus was down returns before any transport
|
|
117
|
-
* exists, so nothing would ever bind its routing key on the broker that
|
|
118
|
-
* finally comes up, leaving the process publishing but never consuming.
|
|
119
|
-
*/ async bindSubscriptions() {
|
|
120
|
-
for (const { pattern } of this.subscriptions){
|
|
121
|
-
if (this.boundPatterns.has(pattern)) continue;
|
|
122
|
-
this.boundPatterns.add(pattern);
|
|
123
|
-
await Promise.all(this.transports.map((transport)=>transport.bind(pattern).catch((error)=>{
|
|
124
|
-
this.logger.warn(`Bind failed on ${transport.name}: ${error.message}`);
|
|
125
|
-
})));
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
async createBrokerTransport(label) {
|
|
129
|
-
const name = label === 'hybrid' ? this.resolveHybridBrokerName() : label;
|
|
130
|
-
try {
|
|
131
|
-
await this.loadOptionalTransport(name);
|
|
132
|
-
const factory = EventTransportRegistry.get(name);
|
|
133
|
-
if (!factory) {
|
|
134
|
-
this.logger.error(`Event transport '${name}' is not registered. Available: ${EventTransportRegistry.getAll().join(', ')}`);
|
|
135
|
-
return undefined;
|
|
136
|
-
}
|
|
137
|
-
const transport = factory(this.getTransportConfig(name));
|
|
138
|
-
await transport.connect();
|
|
139
|
-
return transport;
|
|
140
|
-
} catch (error) {
|
|
141
|
-
const message = error instanceof Error ? error.message : 'Unknown error';
|
|
142
|
-
this.logger.error(`Failed to start the '${name}' event transport: ${message}`);
|
|
143
|
-
return undefined;
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
resolveHybridBrokerName() {
|
|
147
|
-
return envConfig.tryGetValue('EVENT_BROKER', false) || 'rabbitmq';
|
|
148
|
-
}
|
|
149
|
-
/**
|
|
150
|
-
* Registers explicitly rather than relying on the transport file's own
|
|
151
|
-
* side effect, which a tree shaking bundler is free to drop.
|
|
152
|
-
*/ async loadOptionalTransport(name) {
|
|
153
|
-
if (EventTransportRegistry.has(name)) return;
|
|
154
|
-
if (name === 'rabbitmq') {
|
|
155
|
-
const { RabbitMqTransport } = await import('./event-transports/rabbitmq-transport.optional');
|
|
156
|
-
EventTransportRegistry.register('rabbitmq', (config)=>new RabbitMqTransport(config));
|
|
157
|
-
return;
|
|
158
|
-
}
|
|
159
|
-
if (name === 'kafka') {
|
|
160
|
-
const { KafkaTransport } = await import('./event-transports/kafka-transport.optional');
|
|
161
|
-
EventTransportRegistry.register('kafka', (config)=>new KafkaTransport(config));
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
getTransportConfig(name) {
|
|
165
|
-
if (name === 'rabbitmq') {
|
|
166
|
-
return {
|
|
167
|
-
url: envConfig.tryGetValue('RABBITMQ_URL', false) || undefined,
|
|
168
|
-
queue: this.options.serviceName ? `${this.options.serviceName}.events` : undefined,
|
|
169
|
-
...this.options.rabbitmq ?? {}
|
|
170
|
-
};
|
|
171
|
-
}
|
|
172
|
-
if (name === 'kafka') {
|
|
173
|
-
return {
|
|
174
|
-
brokers: this.parseBrokers(envConfig.tryGetValue('KAFKA_BROKERS', false)),
|
|
175
|
-
clientId: this.options.serviceName,
|
|
176
|
-
groupId: this.options.serviceName ? `${this.options.serviceName}-events` : undefined,
|
|
177
|
-
...this.options.kafka ?? {}
|
|
178
|
-
};
|
|
179
|
-
}
|
|
180
|
-
return {};
|
|
181
|
-
}
|
|
182
|
-
parseBrokers(value) {
|
|
183
|
-
if (!value) return undefined;
|
|
184
|
-
return value.split(',').map((broker)=>broker.trim()).filter(Boolean);
|
|
185
|
-
}
|
|
186
|
-
registerTransport(transport) {
|
|
187
|
-
transport.onMessage((event)=>this.dispatch(event));
|
|
188
|
-
this.transports.push(transport);
|
|
189
|
-
}
|
|
190
|
-
async dispatch(event) {
|
|
191
|
-
if (this.isDuplicate(event.id)) return;
|
|
192
|
-
const matched = this.subscriptions.filter((subscription)=>matchEventPattern(subscription.pattern, event.name));
|
|
193
|
-
await Promise.all(matched.map(async (subscription)=>{
|
|
194
|
-
try {
|
|
195
|
-
await subscription.handler(event);
|
|
196
|
-
} catch (error) {
|
|
197
|
-
const message = error instanceof Error ? error.message : 'Unknown error';
|
|
198
|
-
this.logger.error(`Handler for '${subscription.pattern}' failed: ${message}`);
|
|
199
|
-
}
|
|
200
|
-
}));
|
|
201
|
-
}
|
|
202
|
-
isDuplicate(eventId) {
|
|
203
|
-
if (!eventId) return false;
|
|
204
|
-
if (this.seenIds.has(eventId)) return true;
|
|
205
|
-
this.seenIds.add(eventId);
|
|
206
|
-
this.seenOrder.push(eventId);
|
|
207
|
-
if (this.seenOrder.length > this.dedupeSize) {
|
|
208
|
-
const evicted = this.seenOrder.shift();
|
|
209
|
-
if (evicted) this.seenIds.delete(evicted);
|
|
210
|
-
}
|
|
211
|
-
return false;
|
|
212
|
-
}
|
|
213
|
-
constructor(options = {}){
|
|
214
|
-
_define_property(this, "options", void 0);
|
|
215
|
-
_define_property(this, "logger", void 0);
|
|
216
|
-
_define_property(this, "subscriptions", void 0);
|
|
217
|
-
_define_property(this, "transports", void 0);
|
|
218
|
-
_define_property(this, "boundPatterns", void 0);
|
|
219
|
-
_define_property(this, "seenIds", void 0);
|
|
220
|
-
_define_property(this, "seenOrder", void 0);
|
|
221
|
-
_define_property(this, "label", void 0);
|
|
222
|
-
_define_property(this, "dedupeSize", void 0);
|
|
223
|
-
_define_property(this, "memory", void 0);
|
|
224
|
-
_define_property(this, "connecting", void 0);
|
|
225
|
-
_define_property(this, "connected", void 0);
|
|
226
|
-
this.options = options;
|
|
227
|
-
this.logger = new Logger(HybridEventBus.name);
|
|
228
|
-
this.subscriptions = [];
|
|
229
|
-
this.transports = [];
|
|
230
|
-
this.boundPatterns = new Set();
|
|
231
|
-
this.seenIds = new Set();
|
|
232
|
-
this.seenOrder = [];
|
|
233
|
-
this.connected = false;
|
|
234
|
-
this.label = options.transport ?? this.resolveLabelFromEnv();
|
|
235
|
-
this.dedupeSize = options.dedupeSize ?? DEFAULT_DEDUPE_SIZE;
|
|
236
|
-
}
|
|
237
|
-
}
|
|
@@ -1,214 +0,0 @@
|
|
|
1
|
-
import { EventTransportRegistry } from './event-transports/event-transport.registry';
|
|
2
|
-
import { MemoryTransport } from './event-transports/memory-transport';
|
|
3
|
-
import { HybridEventBus } from './hybrid-event-bus.class';
|
|
4
|
-
function buildEvent(name = 'storage.folder.created', id = 'event-1') {
|
|
5
|
-
return {
|
|
6
|
-
id,
|
|
7
|
-
name,
|
|
8
|
-
module: 'storage',
|
|
9
|
-
entity: 'folder',
|
|
10
|
-
action: 'created',
|
|
11
|
-
payload: {
|
|
12
|
-
ids: [
|
|
13
|
-
'1'
|
|
14
|
-
]
|
|
15
|
-
},
|
|
16
|
-
actor: {},
|
|
17
|
-
occurredAt: new Date().toISOString(),
|
|
18
|
-
version: 1
|
|
19
|
-
};
|
|
20
|
-
}
|
|
21
|
-
function createFakeTransport(name) {
|
|
22
|
-
const handlers = [];
|
|
23
|
-
const transport = {
|
|
24
|
-
name,
|
|
25
|
-
connect: jest.fn().mockResolvedValue(undefined),
|
|
26
|
-
publish: jest.fn().mockResolvedValue(undefined),
|
|
27
|
-
bind: jest.fn().mockResolvedValue(undefined),
|
|
28
|
-
onMessage: (handler)=>handlers.push(handler),
|
|
29
|
-
close: jest.fn().mockResolvedValue(undefined),
|
|
30
|
-
isReady: ()=>true,
|
|
31
|
-
emit: (event)=>handlers.forEach((handler)=>handler(event))
|
|
32
|
-
};
|
|
33
|
-
return transport;
|
|
34
|
-
}
|
|
35
|
-
describe('HybridEventBus', ()=>{
|
|
36
|
-
const originalLabel = process.env.USE_EVENT_LABEL;
|
|
37
|
-
afterEach(async ()=>{
|
|
38
|
-
EventTransportRegistry.clear();
|
|
39
|
-
if (originalLabel === undefined) delete process.env.USE_EVENT_LABEL;
|
|
40
|
-
else process.env.USE_EVENT_LABEL = originalLabel;
|
|
41
|
-
});
|
|
42
|
-
it('should default to the memory transport', async ()=>{
|
|
43
|
-
const bus = new HybridEventBus();
|
|
44
|
-
await bus.connect();
|
|
45
|
-
expect(bus.getTransportLabel()).toBe('memory');
|
|
46
|
-
expect(bus.getActiveTransports()).toEqual([
|
|
47
|
-
'memory'
|
|
48
|
-
]);
|
|
49
|
-
await bus.close();
|
|
50
|
-
});
|
|
51
|
-
it('should read the transport label from USE_EVENT_LABEL when not given explicitly', ()=>{
|
|
52
|
-
process.env.USE_EVENT_LABEL = 'kafka';
|
|
53
|
-
expect(new HybridEventBus().getTransportLabel()).toBe('kafka');
|
|
54
|
-
});
|
|
55
|
-
it('should prefer an explicit transport option over the env value', ()=>{
|
|
56
|
-
process.env.USE_EVENT_LABEL = 'kafka';
|
|
57
|
-
expect(new HybridEventBus({
|
|
58
|
-
transport: 'memory'
|
|
59
|
-
}).getTransportLabel()).toBe('memory');
|
|
60
|
-
});
|
|
61
|
-
it('should deliver a published event to a matching subscriber', async ()=>{
|
|
62
|
-
const bus = new HybridEventBus({
|
|
63
|
-
transport: 'memory'
|
|
64
|
-
});
|
|
65
|
-
const handler = jest.fn();
|
|
66
|
-
await bus.subscribe('storage.*.created', handler);
|
|
67
|
-
await bus.publish(buildEvent());
|
|
68
|
-
expect(handler).toHaveBeenCalledWith(expect.objectContaining({
|
|
69
|
-
name: 'storage.folder.created'
|
|
70
|
-
}));
|
|
71
|
-
await bus.close();
|
|
72
|
-
});
|
|
73
|
-
it('should not deliver an event to a non matching subscriber', async ()=>{
|
|
74
|
-
const bus = new HybridEventBus({
|
|
75
|
-
transport: 'memory'
|
|
76
|
-
});
|
|
77
|
-
const handler = jest.fn();
|
|
78
|
-
await bus.subscribe('auth.#', handler);
|
|
79
|
-
await bus.publish(buildEvent());
|
|
80
|
-
expect(handler).not.toHaveBeenCalled();
|
|
81
|
-
await bus.close();
|
|
82
|
-
});
|
|
83
|
-
it('should keep publishing when a handler throws', async ()=>{
|
|
84
|
-
const bus = new HybridEventBus({
|
|
85
|
-
transport: 'memory'
|
|
86
|
-
});
|
|
87
|
-
const failing = jest.fn().mockRejectedValue(new Error('boom'));
|
|
88
|
-
const healthy = jest.fn();
|
|
89
|
-
await bus.subscribe('**', failing);
|
|
90
|
-
await bus.subscribe('**', healthy);
|
|
91
|
-
await expect(bus.publish(buildEvent())).resolves.toBeUndefined();
|
|
92
|
-
expect(healthy).toHaveBeenCalled();
|
|
93
|
-
await bus.close();
|
|
94
|
-
});
|
|
95
|
-
it('should publish to both layers in hybrid mode and deliver each event once', async ()=>{
|
|
96
|
-
const broker = createFakeTransport('rabbitmq');
|
|
97
|
-
EventTransportRegistry.register('rabbitmq', ()=>broker);
|
|
98
|
-
const bus = new HybridEventBus({
|
|
99
|
-
transport: 'hybrid'
|
|
100
|
-
});
|
|
101
|
-
const handler = jest.fn();
|
|
102
|
-
await bus.subscribe('**', handler);
|
|
103
|
-
expect(bus.getActiveTransports()).toEqual([
|
|
104
|
-
'memory',
|
|
105
|
-
'rabbitmq'
|
|
106
|
-
]);
|
|
107
|
-
const event = buildEvent();
|
|
108
|
-
await bus.publish(event);
|
|
109
|
-
// the broker loops the same event back to this process
|
|
110
|
-
broker.emit(event);
|
|
111
|
-
expect(broker.publish).toHaveBeenCalledWith(event);
|
|
112
|
-
expect(handler).toHaveBeenCalledTimes(1);
|
|
113
|
-
await bus.close();
|
|
114
|
-
});
|
|
115
|
-
it('should fall back to memory when the broker cannot start', async ()=>{
|
|
116
|
-
EventTransportRegistry.register('kafka', ()=>{
|
|
117
|
-
throw new Error('kafkajs not installed');
|
|
118
|
-
});
|
|
119
|
-
const bus = new HybridEventBus({
|
|
120
|
-
transport: 'kafka'
|
|
121
|
-
});
|
|
122
|
-
await bus.connect();
|
|
123
|
-
expect(bus.getActiveTransports()).toEqual([
|
|
124
|
-
'memory'
|
|
125
|
-
]);
|
|
126
|
-
await bus.close();
|
|
127
|
-
});
|
|
128
|
-
it('should survive a transport that fails to publish', async ()=>{
|
|
129
|
-
const broker = createFakeTransport('rabbitmq');
|
|
130
|
-
broker.publish.mockRejectedValue(new Error('channel closed'));
|
|
131
|
-
EventTransportRegistry.register('rabbitmq', ()=>broker);
|
|
132
|
-
const bus = new HybridEventBus({
|
|
133
|
-
transport: 'rabbitmq'
|
|
134
|
-
});
|
|
135
|
-
await expect(bus.publish(buildEvent())).resolves.toBeUndefined();
|
|
136
|
-
await bus.close();
|
|
137
|
-
});
|
|
138
|
-
it('should not publish or throw while it has no working transport', async ()=>{
|
|
139
|
-
const connectSpy = jest.spyOn(MemoryTransport.prototype, 'connect').mockRejectedValueOnce(new Error('boot failure'));
|
|
140
|
-
const bus = new HybridEventBus({
|
|
141
|
-
transport: 'memory'
|
|
142
|
-
});
|
|
143
|
-
await expect(bus.publish(buildEvent())).resolves.toBeUndefined();
|
|
144
|
-
expect(bus.getActiveTransports()).toEqual([]);
|
|
145
|
-
connectSpy.mockRestore();
|
|
146
|
-
await bus.close();
|
|
147
|
-
});
|
|
148
|
-
it('should retry connecting after a failed attempt instead of staying dead', async ()=>{
|
|
149
|
-
const connectSpy = jest.spyOn(MemoryTransport.prototype, 'connect').mockRejectedValueOnce(new Error('boot failure'));
|
|
150
|
-
const bus = new HybridEventBus({
|
|
151
|
-
transport: 'memory'
|
|
152
|
-
});
|
|
153
|
-
const handler = jest.fn();
|
|
154
|
-
await bus.publish(buildEvent());
|
|
155
|
-
connectSpy.mockRestore();
|
|
156
|
-
await bus.subscribe('**', handler);
|
|
157
|
-
await bus.publish(buildEvent('storage.folder.created', 'event-2'));
|
|
158
|
-
expect(bus.getActiveTransports()).toEqual([
|
|
159
|
-
'memory'
|
|
160
|
-
]);
|
|
161
|
-
expect(handler).toHaveBeenCalledTimes(1);
|
|
162
|
-
await bus.close();
|
|
163
|
-
});
|
|
164
|
-
it('should keep a subscription made while disconnected so a later connect binds it', async ()=>{
|
|
165
|
-
const connectSpy = jest.spyOn(MemoryTransport.prototype, 'connect').mockRejectedValueOnce(new Error('boot failure'));
|
|
166
|
-
const bus = new HybridEventBus({
|
|
167
|
-
transport: 'memory'
|
|
168
|
-
});
|
|
169
|
-
const handler = jest.fn();
|
|
170
|
-
await expect(bus.subscribe('**', handler)).resolves.toBeUndefined();
|
|
171
|
-
connectSpy.mockRestore();
|
|
172
|
-
await bus.publish(buildEvent());
|
|
173
|
-
expect(handler).toHaveBeenCalledTimes(1);
|
|
174
|
-
await bus.close();
|
|
175
|
-
});
|
|
176
|
-
it('should bind a subscription taken while disconnected on the broker that comes up later', async ()=>{
|
|
177
|
-
const broker = createFakeTransport('rabbitmq');
|
|
178
|
-
EventTransportRegistry.register('rabbitmq', ()=>broker);
|
|
179
|
-
const connectSpy = jest.spyOn(MemoryTransport.prototype, 'connect').mockRejectedValueOnce(new Error('boot failure'));
|
|
180
|
-
const bus = new HybridEventBus({
|
|
181
|
-
transport: 'hybrid'
|
|
182
|
-
});
|
|
183
|
-
await bus.subscribe('storage.#', jest.fn());
|
|
184
|
-
expect(broker.bind).not.toHaveBeenCalled();
|
|
185
|
-
connectSpy.mockRestore();
|
|
186
|
-
// Anything that reconnects must bind what is already subscribed, or the
|
|
187
|
-
// queue stays unbound and this process publishes without ever consuming
|
|
188
|
-
await bus.publish(buildEvent());
|
|
189
|
-
expect(broker.bind).toHaveBeenCalledWith('storage.#');
|
|
190
|
-
await bus.close();
|
|
191
|
-
});
|
|
192
|
-
it('should bind each pattern once, not again on every later subscribe', async ()=>{
|
|
193
|
-
const broker = createFakeTransport('rabbitmq');
|
|
194
|
-
EventTransportRegistry.register('rabbitmq', ()=>broker);
|
|
195
|
-
const bus = new HybridEventBus({
|
|
196
|
-
transport: 'rabbitmq'
|
|
197
|
-
});
|
|
198
|
-
await bus.subscribe('storage.#', jest.fn());
|
|
199
|
-
await bus.subscribe('auth.#', jest.fn());
|
|
200
|
-
expect(broker.bind.mock.calls.map(([pattern])=>pattern)).toEqual([
|
|
201
|
-
'storage.#',
|
|
202
|
-
'auth.#'
|
|
203
|
-
]);
|
|
204
|
-
await bus.close();
|
|
205
|
-
});
|
|
206
|
-
it('should forget its transports after close', async ()=>{
|
|
207
|
-
const bus = new HybridEventBus({
|
|
208
|
-
transport: 'memory'
|
|
209
|
-
});
|
|
210
|
-
await bus.connect();
|
|
211
|
-
await bus.close();
|
|
212
|
-
expect(bus.getActiveTransports()).toEqual([]);
|
|
213
|
-
});
|
|
214
|
-
});
|
|
@@ -1,228 +0,0 @@
|
|
|
1
|
-
function _define_property(obj, key, value) {
|
|
2
|
-
if (key in obj) {
|
|
3
|
-
Object.defineProperty(obj, key, {
|
|
4
|
-
value: value,
|
|
5
|
-
enumerable: true,
|
|
6
|
-
configurable: true,
|
|
7
|
-
writable: true
|
|
8
|
-
});
|
|
9
|
-
} else {
|
|
10
|
-
obj[key] = value;
|
|
11
|
-
}
|
|
12
|
-
return obj;
|
|
13
|
-
}
|
|
14
|
-
import { envConfig } from '@flusys/nestjs-core/config';
|
|
15
|
-
import { existsSync, mkdirSync } from 'fs';
|
|
16
|
-
import { join } from 'path';
|
|
17
|
-
import { createLogger, format, transports } from 'winston';
|
|
18
|
-
// Handle both webpack (no default export) and esbuild (default export)
|
|
19
|
-
import * as DailyRotateFileModule from 'winston-daily-rotate-file';
|
|
20
|
-
import * as TransportModule from 'winston-transport';
|
|
21
|
-
const Transport = TransportModule.default || TransportModule;
|
|
22
|
-
const DailyRotateFile = DailyRotateFileModule.default || DailyRotateFileModule;
|
|
23
|
-
// Configuration
|
|
24
|
-
const logConfig = envConfig.getLogConfig();
|
|
25
|
-
const LOG_DIR = logConfig.dir;
|
|
26
|
-
const LOG_LEVEL = logConfig.level;
|
|
27
|
-
const LOG_MAX_SIZE = logConfig.maxSize;
|
|
28
|
-
const LOG_MAX_FILES = logConfig.maxFiles;
|
|
29
|
-
const USE_TENANT_MODE = envConfig.useTenantMode();
|
|
30
|
-
// Ensure logs directory exists
|
|
31
|
-
if (!existsSync(LOG_DIR)) {
|
|
32
|
-
mkdirSync(LOG_DIR, {
|
|
33
|
-
recursive: true
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
// Custom Formats
|
|
37
|
-
/**
|
|
38
|
-
* Custom format for structured logging (production)
|
|
39
|
-
* Multi-line format:
|
|
40
|
-
* - Line 1: Timestamp
|
|
41
|
-
* - Line 2: Log Level
|
|
42
|
-
* - Line 3: [RequestId]
|
|
43
|
-
* - Line 4: Empty
|
|
44
|
-
* - Line 5+: Message with context
|
|
45
|
-
*/ const LEVEL_MAP = {
|
|
46
|
-
error: 'Error',
|
|
47
|
-
warn: 'Warning',
|
|
48
|
-
info: 'Information',
|
|
49
|
-
debug: 'Debug',
|
|
50
|
-
verbose: 'Verbose'
|
|
51
|
-
};
|
|
52
|
-
const LOG_SEPARATOR = '─'.repeat(80);
|
|
53
|
-
const structuredFormat = format.printf(({ timestamp, level, message, context, requestId, userId, tenantId, companyId, method, url, path, statusCode, duration, stack, ...metadata })=>{
|
|
54
|
-
const reqId = requestId || 'no-request-id';
|
|
55
|
-
const levelFormatted = LEVEL_MAP[level] || level.charAt(0).toUpperCase() + level.slice(1);
|
|
56
|
-
const contextParts = [];
|
|
57
|
-
if (context) contextParts.push(`Context: ${context}`);
|
|
58
|
-
if (method && (path || url)) contextParts.push(`Endpoint: ${method} ${path || url}`);
|
|
59
|
-
if (statusCode) contextParts.push(`Status: ${statusCode}`);
|
|
60
|
-
if (duration) contextParts.push(`Duration: ${duration}`);
|
|
61
|
-
if (userId) contextParts.push(`UserId: ${userId}`);
|
|
62
|
-
if (tenantId) contextParts.push(`TenantId: ${tenantId}`);
|
|
63
|
-
if (companyId) contextParts.push(`CompanyId: ${companyId}`);
|
|
64
|
-
let content = message;
|
|
65
|
-
if (contextParts.length > 0) {
|
|
66
|
-
content = `${contextParts.join(' | ')}\n${message}`;
|
|
67
|
-
}
|
|
68
|
-
const metaKeys = Object.keys(metadata).filter((k)=>k !== 'splat');
|
|
69
|
-
if (metaKeys.length > 0) {
|
|
70
|
-
const metaStr = JSON.stringify(metaKeys.reduce((acc, k)=>({
|
|
71
|
-
...acc,
|
|
72
|
-
[k]: metadata[k]
|
|
73
|
-
}), {}));
|
|
74
|
-
content += `\nMetadata: ${metaStr}`;
|
|
75
|
-
}
|
|
76
|
-
if (stack) {
|
|
77
|
-
content += `\nStack: ${stack}`;
|
|
78
|
-
}
|
|
79
|
-
return `${LOG_SEPARATOR}\n${timestamp} | ${levelFormatted} | [${reqId}]\n${content}`;
|
|
80
|
-
});
|
|
81
|
-
// Transports
|
|
82
|
-
/**
|
|
83
|
-
* Daily rotating file transport for all logs
|
|
84
|
-
*/ const combinedRotateTransport = new DailyRotateFile({
|
|
85
|
-
filename: `${LOG_DIR}/combined-%DATE%.log`,
|
|
86
|
-
datePattern: 'YYYY-MM-DD',
|
|
87
|
-
zippedArchive: true,
|
|
88
|
-
maxSize: LOG_MAX_SIZE,
|
|
89
|
-
maxFiles: LOG_MAX_FILES,
|
|
90
|
-
level: LOG_LEVEL
|
|
91
|
-
});
|
|
92
|
-
/**
|
|
93
|
-
* Daily rotating file transport for error logs only
|
|
94
|
-
*/ const errorRotateTransport = new DailyRotateFile({
|
|
95
|
-
filename: `${LOG_DIR}/error-%DATE%.log`,
|
|
96
|
-
datePattern: 'YYYY-MM-DD',
|
|
97
|
-
zippedArchive: true,
|
|
98
|
-
maxSize: LOG_MAX_SIZE,
|
|
99
|
-
maxFiles: LOG_MAX_FILES,
|
|
100
|
-
level: 'error'
|
|
101
|
-
});
|
|
102
|
-
// Transport Caches
|
|
103
|
-
const moduleTransportCache = new Map();
|
|
104
|
-
const tenantTransportCache = new Map();
|
|
105
|
-
function getCachedTransport(cache, name) {
|
|
106
|
-
const cached = cache.get(name);
|
|
107
|
-
if (cached) return cached;
|
|
108
|
-
const logDir = join(LOG_DIR, name);
|
|
109
|
-
if (!existsSync(logDir)) {
|
|
110
|
-
mkdirSync(logDir, {
|
|
111
|
-
recursive: true
|
|
112
|
-
});
|
|
113
|
-
}
|
|
114
|
-
const transport = new DailyRotateFile({
|
|
115
|
-
filename: `${logDir}/combined-%DATE%.log`,
|
|
116
|
-
datePattern: 'YYYY-MM-DD',
|
|
117
|
-
zippedArchive: true,
|
|
118
|
-
maxSize: LOG_MAX_SIZE,
|
|
119
|
-
maxFiles: LOG_MAX_FILES,
|
|
120
|
-
level: LOG_LEVEL
|
|
121
|
-
});
|
|
122
|
-
cache.set(name, transport);
|
|
123
|
-
return transport;
|
|
124
|
-
}
|
|
125
|
-
const getModuleTransport = (name)=>getCachedTransport(moduleTransportCache, name);
|
|
126
|
-
const getTenantTransport = (name)=>getCachedTransport(tenantTransportCache, name);
|
|
127
|
-
let TenantAwareTransport = class TenantAwareTransport extends Transport {
|
|
128
|
-
log(info, callback) {
|
|
129
|
-
setImmediate(()=>this.emit('logged', info));
|
|
130
|
-
const tenantId = info.tenantId || info.metadata?.tenantId;
|
|
131
|
-
const transport = USE_TENANT_MODE && tenantId ? getTenantTransport(tenantId) : this.defaultTransport;
|
|
132
|
-
transport.log(info, callback);
|
|
133
|
-
}
|
|
134
|
-
constructor(defaultTransport){
|
|
135
|
-
super(), _define_property(this, "defaultTransport", void 0), this.defaultTransport = defaultTransport;
|
|
136
|
-
}
|
|
137
|
-
};
|
|
138
|
-
const tenantAwareCombinedTransport = new TenantAwareTransport(combinedRotateTransport);
|
|
139
|
-
const consoleTransport = new transports.Console({
|
|
140
|
-
level: LOG_LEVEL,
|
|
141
|
-
format: format.combine(format.colorize({
|
|
142
|
-
all: true
|
|
143
|
-
}), format.timestamp({
|
|
144
|
-
format: 'YYYY-MM-DD HH:mm:ss'
|
|
145
|
-
}), format.errors({
|
|
146
|
-
stack: true
|
|
147
|
-
}), structuredFormat)
|
|
148
|
-
});
|
|
149
|
-
// Logger Instances
|
|
150
|
-
/**
|
|
151
|
-
* Development logger configuration
|
|
152
|
-
* - Console output with colors
|
|
153
|
-
* - Human-readable format
|
|
154
|
-
* - Debug level by default
|
|
155
|
-
*/ const devLogger = createLogger({
|
|
156
|
-
level: LOG_LEVEL,
|
|
157
|
-
format: format.combine(format.timestamp({
|
|
158
|
-
format: 'YYYY-MM-DD HH:mm:ss'
|
|
159
|
-
}), format.errors({
|
|
160
|
-
stack: true
|
|
161
|
-
})),
|
|
162
|
-
transports: [
|
|
163
|
-
consoleTransport
|
|
164
|
-
],
|
|
165
|
-
exitOnError: false
|
|
166
|
-
});
|
|
167
|
-
/**
|
|
168
|
-
* Production logger configuration
|
|
169
|
-
* - File-based logging with rotation
|
|
170
|
-
* - JSON structured format
|
|
171
|
-
* - Separate error log file
|
|
172
|
-
* - Compressed old logs
|
|
173
|
-
* - Tenant-aware routing (when USE_TENANT_MODE=true)
|
|
174
|
-
*/ const prodLogger = createLogger({
|
|
175
|
-
level: LOG_LEVEL,
|
|
176
|
-
format: format.combine(format.timestamp({
|
|
177
|
-
format: 'YYYY-MM-DD HH:mm:ss.SSS'
|
|
178
|
-
}), format.errors({
|
|
179
|
-
stack: true
|
|
180
|
-
}), structuredFormat),
|
|
181
|
-
transports: [
|
|
182
|
-
tenantAwareCombinedTransport,
|
|
183
|
-
errorRotateTransport
|
|
184
|
-
],
|
|
185
|
-
exitOnError: false
|
|
186
|
-
});
|
|
187
|
-
// Exports
|
|
188
|
-
/**
|
|
189
|
-
* Winston logger instance (global)
|
|
190
|
-
* - DEV: Console output with colors
|
|
191
|
-
* - PROD: File-based with daily rotation, tenant-aware routing
|
|
192
|
-
*/ export const instance = envConfig.isProduction() ? prodLogger : devLogger;
|
|
193
|
-
/**
|
|
194
|
-
* Module logger cache to avoid creating multiple loggers for the same module
|
|
195
|
-
*/ const moduleLoggerCache = new Map();
|
|
196
|
-
/**
|
|
197
|
-
* Create a module-specific logger instance
|
|
198
|
-
* - DEV: Console output (same as global)
|
|
199
|
-
* - PROD: File-based with module-specific folder + shared error log
|
|
200
|
-
*
|
|
201
|
-
* @param moduleName - The module name (e.g., 'auth', 'iam', 'storage')
|
|
202
|
-
* @returns Logger instance for the module
|
|
203
|
-
*/ export function createModuleLogger(moduleName) {
|
|
204
|
-
// In dev mode, use global console logger
|
|
205
|
-
if (!envConfig.isProduction()) {
|
|
206
|
-
return devLogger;
|
|
207
|
-
}
|
|
208
|
-
// Check cache first
|
|
209
|
-
if (moduleLoggerCache.has(moduleName)) {
|
|
210
|
-
return moduleLoggerCache.get(moduleName);
|
|
211
|
-
}
|
|
212
|
-
// Create module-specific logger for production
|
|
213
|
-
const moduleLogger = createLogger({
|
|
214
|
-
level: LOG_LEVEL,
|
|
215
|
-
format: format.combine(format.timestamp({
|
|
216
|
-
format: 'YYYY-MM-DD HH:mm:ss.SSS'
|
|
217
|
-
}), format.errors({
|
|
218
|
-
stack: true
|
|
219
|
-
}), structuredFormat),
|
|
220
|
-
transports: [
|
|
221
|
-
getModuleTransport(moduleName),
|
|
222
|
-
errorRotateTransport
|
|
223
|
-
],
|
|
224
|
-
exitOnError: false
|
|
225
|
-
});
|
|
226
|
-
moduleLoggerCache.set(moduleName, moduleLogger);
|
|
227
|
-
return moduleLogger;
|
|
228
|
-
}
|