@seidor-cloud-produtos/orbit-backend-lib 2.0.85 → 2.0.87
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/clean-arch/application/cache/cache.d.ts +32 -0
- package/dist/clean-arch/application/cache/cache.js +24 -0
- package/dist/clean-arch/application/cache/client.d.ts +23 -0
- package/dist/clean-arch/application/cache/client.js +11 -0
- package/dist/clean-arch/application/logger/index.d.ts +81 -4
- package/dist/clean-arch/application/logger/index.js +58 -0
- package/dist/clean-arch/application/queue/handler.d.ts +28 -0
- package/dist/clean-arch/application/queue/handler.js +23 -0
- package/dist/clean-arch/application/queue/messages-in-memory.d.ts +6 -0
- package/dist/clean-arch/application/queue/queue-connection.d.ts +17 -0
- package/dist/clean-arch/application/queue/queue.d.ts +31 -0
- package/dist/clean-arch/domain/events/domain-event.d.ts +5 -0
- package/dist/clean-arch/infra/cache/cache-in-memory.d.ts +5 -0
- package/dist/clean-arch/infra/cache/cache-in-memory.js +6 -0
- package/dist/clean-arch/infra/cache/clients/node-cache.d.ts +17 -0
- package/dist/clean-arch/infra/cache/clients/node-cache.js +17 -0
- package/dist/clean-arch/infra/cache/clients/redis.d.ts +15 -0
- package/dist/clean-arch/infra/cache/clients/redis.js +11 -0
- package/dist/clean-arch/infra/http/handle-authorizer-headers.d.ts +2 -0
- package/dist/clean-arch/infra/http/handle-authorizer-headers.js +1 -0
- package/dist/clean-arch/infra/http/handle-user-headers.d.ts +2 -0
- package/dist/clean-arch/infra/http/handle-user-headers.js +1 -0
- package/dist/clean-arch/infra/logger/logger-in-memory.d.ts +24 -1
- package/dist/clean-arch/infra/logger/logger-in-memory.js +19 -0
- package/dist/clean-arch/infra/logger/logger-orbit.d.ts +65 -4
- package/dist/clean-arch/infra/logger/logger-orbit.js +39 -0
- package/dist/clean-arch/infra/queue/create-consumers.d.ts +14 -0
- package/dist/clean-arch/infra/queue/create-consumers.js +11 -0
- package/dist/clean-arch/infra/queue/in-memory/in-memory-queue.d.ts +12 -0
- package/dist/clean-arch/infra/queue/in-memory/in-memory-queue.js +12 -0
- package/dist/clean-arch/infra/queue/queue-controller.d.ts +14 -0
- package/dist/clean-arch/infra/queue/queue-controller.js +8 -0
- package/dist/clean-arch/infra/queue/rabbitmq/amqp-lib.d.ts +86 -0
- package/dist/clean-arch/infra/queue/rabbitmq/amqp-lib.js +72 -2
- package/dist/clean-arch/infra/queue/rabbitmq/types.d.ts +6 -0
- package/dist/clean-arch/infra/queue/worker.d.ts +9 -0
- package/dist/clean-arch/infra/queue/worker.js +9 -0
- package/dist/clean-arch/infra/scaledjob/amqp/runner.d.ts +38 -2
- package/dist/clean-arch/infra/scaledjob/amqp/runner.js +36 -0
- package/dist/clean-arch/infra/scaledjob/amqp/types.d.ts +19 -0
- package/dist/clean-arch/infra/scaledjob/sqs/runner.d.ts +23 -0
- package/dist/clean-arch/infra/scaledjob/sqs/runner.js +26 -2
- package/dist/clean-arch/infra/scaledjob/sqs/types.d.ts +18 -0
- package/dist/clean-arch/infra/scaledjob/types/index.d.ts +5 -0
- package/dist/clean-arch/infra/validations/zod/schemas/common-validation.d.ts +42 -0
- package/dist/clean-arch/infra/validations/zod/schemas/common-validation.js +14 -1
- package/dist/clean-arch/shared/timeout.d.ts +8 -0
- package/dist/clean-arch/shared/timeout.js +8 -0
- package/package.json +1 -1
|
@@ -1,31 +1,63 @@
|
|
|
1
1
|
import { Logger } from '../logger';
|
|
2
2
|
import { CacheClient } from './client';
|
|
3
|
+
/**
|
|
4
|
+
* Opcoes por metodo (sobrescrevem CacheOptions).
|
|
5
|
+
*/
|
|
3
6
|
export type MethodOptions = {
|
|
4
7
|
throwOnError?: boolean;
|
|
5
8
|
};
|
|
9
|
+
/**
|
|
10
|
+
* Opcoes globais do cache.
|
|
11
|
+
* - throwOnError: quando true, propaga erros.
|
|
12
|
+
* - contingencyClients: lista de clientes alternativos para fallback.
|
|
13
|
+
*/
|
|
6
14
|
export type CacheOptions = {
|
|
7
15
|
throwOnError?: boolean;
|
|
8
16
|
contingencyClients?: CacheClient[];
|
|
9
17
|
};
|
|
18
|
+
/**
|
|
19
|
+
* Camada de cache padrao da lib.
|
|
20
|
+
* Responsavel por:
|
|
21
|
+
* - controlar TTL padrao
|
|
22
|
+
* - serializacao JSON
|
|
23
|
+
* - fallback entre clientes
|
|
24
|
+
*/
|
|
10
25
|
export declare abstract class Cache {
|
|
11
26
|
protected logger: Logger;
|
|
12
27
|
protected abstract client: CacheClient;
|
|
13
28
|
protected elegibleClients: CacheClient[];
|
|
29
|
+
/** TTL padrao (segundos). */
|
|
14
30
|
protected DEFAULT_EXPIRATION_SECONDS: number;
|
|
15
31
|
private options?;
|
|
16
32
|
constructor(options?: CacheOptions, logger?: Logger);
|
|
17
33
|
private setElegibleClients;
|
|
18
34
|
private setOptions;
|
|
19
35
|
private setRunningClient;
|
|
36
|
+
/** Inicia o cliente de cache. */
|
|
20
37
|
start(options?: MethodOptions): Promise<void>;
|
|
38
|
+
/** Busca um valor do cache. */
|
|
21
39
|
get(keyCache: string, options?: MethodOptions): Promise<any>;
|
|
40
|
+
/** Grava um valor no cache com TTL (segundos). */
|
|
22
41
|
set(keyCache: string, data: any, expiration?: number, options?: MethodOptions): Promise<void>;
|
|
42
|
+
/** Remove uma chave do cache. */
|
|
23
43
|
del(keyCache: string, options?: MethodOptions): Promise<void>;
|
|
44
|
+
/** Lista chaves; o pattern varia por cliente. */
|
|
24
45
|
getKeys(pattern?: string, options?: MethodOptions): Promise<string[] | null>;
|
|
46
|
+
/** Remove varias chaves de uma vez. */
|
|
25
47
|
delBatch(patterns: string[], options?: MethodOptions): Promise<void>;
|
|
48
|
+
/** Limpa o banco/instancia de cache. */
|
|
26
49
|
flush(): Promise<void>;
|
|
50
|
+
/**
|
|
51
|
+
* Health-check do cache.
|
|
52
|
+
* - se falhar, tenta alternar para um cliente elegivel
|
|
53
|
+
*/
|
|
27
54
|
isRunning(options?: MethodOptions, isContingency?: boolean): Promise<boolean>;
|
|
55
|
+
/** Encerra o cliente de cache. */
|
|
28
56
|
close(options?: MethodOptions): Promise<void>;
|
|
57
|
+
/** Padroniza o log/propagacao de erros. */
|
|
29
58
|
protected handleException(e: Error): Promise<void>;
|
|
59
|
+
/**
|
|
60
|
+
* Busca do cache e, se nao existir, executa a promise e grava o resultado.
|
|
61
|
+
*/
|
|
30
62
|
getOrFetchAndCache<T>(keyCache: string, expiration: number | undefined, promise: () => Promise<T>, options?: MethodOptions): Promise<T | undefined>;
|
|
31
63
|
}
|
|
@@ -2,9 +2,17 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.Cache = void 0;
|
|
4
4
|
const env_1 = require("../../infra/environment/env");
|
|
5
|
+
/**
|
|
6
|
+
* Camada de cache padrao da lib.
|
|
7
|
+
* Responsavel por:
|
|
8
|
+
* - controlar TTL padrao
|
|
9
|
+
* - serializacao JSON
|
|
10
|
+
* - fallback entre clientes
|
|
11
|
+
*/
|
|
5
12
|
class Cache {
|
|
6
13
|
logger;
|
|
7
14
|
elegibleClients;
|
|
15
|
+
/** TTL padrao (segundos). */
|
|
8
16
|
DEFAULT_EXPIRATION_SECONDS = env_1.env?.DEFAULT_CACHE_EXPIRATION || 360;
|
|
9
17
|
options;
|
|
10
18
|
constructor(options, logger = console) {
|
|
@@ -51,6 +59,7 @@ class Cache {
|
|
|
51
59
|
this.logger.warn(`Changed cache client to ${this.client.constructor.name}`);
|
|
52
60
|
return this;
|
|
53
61
|
}
|
|
62
|
+
/** Inicia o cliente de cache. */
|
|
54
63
|
async start(options) {
|
|
55
64
|
try {
|
|
56
65
|
await this.client.start();
|
|
@@ -66,6 +75,7 @@ class Cache {
|
|
|
66
75
|
}
|
|
67
76
|
this.logger.info('💾 Cache Connected');
|
|
68
77
|
}
|
|
78
|
+
/** Busca um valor do cache. */
|
|
69
79
|
async get(keyCache, options) {
|
|
70
80
|
try {
|
|
71
81
|
const dataFromCache = await this.client.get(keyCache);
|
|
@@ -78,6 +88,7 @@ class Cache {
|
|
|
78
88
|
return null;
|
|
79
89
|
}
|
|
80
90
|
}
|
|
91
|
+
/** Grava um valor no cache com TTL (segundos). */
|
|
81
92
|
async set(keyCache, data, expiration = this.DEFAULT_EXPIRATION_SECONDS, options) {
|
|
82
93
|
try {
|
|
83
94
|
return await this.client.set(keyCache, JSON.stringify(data), expiration);
|
|
@@ -89,6 +100,7 @@ class Cache {
|
|
|
89
100
|
return;
|
|
90
101
|
}
|
|
91
102
|
}
|
|
103
|
+
/** Remove uma chave do cache. */
|
|
92
104
|
async del(keyCache, options) {
|
|
93
105
|
try {
|
|
94
106
|
return await this.client.del(keyCache);
|
|
@@ -100,6 +112,7 @@ class Cache {
|
|
|
100
112
|
return;
|
|
101
113
|
}
|
|
102
114
|
}
|
|
115
|
+
/** Lista chaves; o pattern varia por cliente. */
|
|
103
116
|
async getKeys(pattern, options) {
|
|
104
117
|
try {
|
|
105
118
|
return await this.client.getKeys(pattern);
|
|
@@ -111,6 +124,7 @@ class Cache {
|
|
|
111
124
|
return null;
|
|
112
125
|
}
|
|
113
126
|
}
|
|
127
|
+
/** Remove varias chaves de uma vez. */
|
|
114
128
|
async delBatch(patterns, options) {
|
|
115
129
|
try {
|
|
116
130
|
return await this.client.delBatch(patterns);
|
|
@@ -122,6 +136,7 @@ class Cache {
|
|
|
122
136
|
return;
|
|
123
137
|
}
|
|
124
138
|
}
|
|
139
|
+
/** Limpa o banco/instancia de cache. */
|
|
125
140
|
async flush() {
|
|
126
141
|
try {
|
|
127
142
|
return await this.client.flush();
|
|
@@ -130,6 +145,10 @@ class Cache {
|
|
|
130
145
|
await this.handleException(e);
|
|
131
146
|
}
|
|
132
147
|
}
|
|
148
|
+
/**
|
|
149
|
+
* Health-check do cache.
|
|
150
|
+
* - se falhar, tenta alternar para um cliente elegivel
|
|
151
|
+
*/
|
|
133
152
|
async isRunning(options, isContingency = false) {
|
|
134
153
|
let isRunning = false;
|
|
135
154
|
try {
|
|
@@ -146,6 +165,7 @@ class Cache {
|
|
|
146
165
|
}
|
|
147
166
|
return isRunning;
|
|
148
167
|
}
|
|
168
|
+
/** Encerra o cliente de cache. */
|
|
149
169
|
async close(options) {
|
|
150
170
|
this.logger.info('💾 Cache closed');
|
|
151
171
|
try {
|
|
@@ -158,10 +178,14 @@ class Cache {
|
|
|
158
178
|
return;
|
|
159
179
|
}
|
|
160
180
|
}
|
|
181
|
+
/** Padroniza o log/propagacao de erros. */
|
|
161
182
|
async handleException(e) {
|
|
162
183
|
this.logger.error(JSON.stringify(e));
|
|
163
184
|
throw e;
|
|
164
185
|
}
|
|
186
|
+
/**
|
|
187
|
+
* Busca do cache e, se nao existir, executa a promise e grava o resultado.
|
|
188
|
+
*/
|
|
165
189
|
async getOrFetchAndCache(keyCache, expiration = this.DEFAULT_EXPIRATION_SECONDS, promise, options) {
|
|
166
190
|
let data = await this.get(keyCache, options);
|
|
167
191
|
if (!data) {
|
|
@@ -1,16 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Opcoes basicas para clientes de cache.
|
|
3
|
+
* - timeout: segundos usados como timeout de operacoes e ping.
|
|
4
|
+
*/
|
|
1
5
|
export interface CacheClientOptions {
|
|
2
6
|
timeout?: number;
|
|
3
7
|
}
|
|
8
|
+
/**
|
|
9
|
+
* Contrato minimo de um cliente de cache.
|
|
10
|
+
* Cada implementacao deve cuidar de:
|
|
11
|
+
* - conexao (start/close)
|
|
12
|
+
* - operacoes basicas (get/set/del/getKeys/flush)
|
|
13
|
+
*/
|
|
4
14
|
export declare abstract class CacheClient {
|
|
5
15
|
protected connection?: CacheClientOptions | undefined;
|
|
6
16
|
constructor(connection?: CacheClientOptions | undefined);
|
|
17
|
+
/** Inicializa o cliente/conexao. */
|
|
7
18
|
abstract start(): Promise<void>;
|
|
19
|
+
/** Encerra o cliente/conexao. */
|
|
8
20
|
abstract close(): Promise<void>;
|
|
21
|
+
/** Recupera um valor pelo nome da chave. */
|
|
9
22
|
abstract get(keyCache: string): Promise<any>;
|
|
23
|
+
/** Grava um valor com TTL opcional (segundos). */
|
|
10
24
|
abstract set(keyCache: string, data: any, expiration?: number): Promise<void>;
|
|
25
|
+
/** Remove uma chave. */
|
|
11
26
|
abstract del(keyCache: string): Promise<void>;
|
|
27
|
+
/** Remove varias chaves. */
|
|
12
28
|
abstract delBatch(keyCache: string[]): Promise<void>;
|
|
29
|
+
/** Lista chaves; o pattern depende do cliente. */
|
|
13
30
|
abstract getKeys(pattern?: string): Promise<string[] | null>;
|
|
31
|
+
/** Limpa o banco/instancia. */
|
|
14
32
|
abstract flush(): Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* Health-check simples:
|
|
35
|
+
* - grava um ping
|
|
36
|
+
* - le de volta e valida
|
|
37
|
+
*/
|
|
15
38
|
isRunning(): Promise<any>;
|
|
16
39
|
}
|
|
@@ -2,11 +2,22 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.CacheClient = void 0;
|
|
4
4
|
const unique_entity_id_1 = require("../../domain/entities/unique-entity-id");
|
|
5
|
+
/**
|
|
6
|
+
* Contrato minimo de um cliente de cache.
|
|
7
|
+
* Cada implementacao deve cuidar de:
|
|
8
|
+
* - conexao (start/close)
|
|
9
|
+
* - operacoes basicas (get/set/del/getKeys/flush)
|
|
10
|
+
*/
|
|
5
11
|
class CacheClient {
|
|
6
12
|
connection;
|
|
7
13
|
constructor(connection) {
|
|
8
14
|
this.connection = connection;
|
|
9
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* Health-check simples:
|
|
18
|
+
* - grava um ping
|
|
19
|
+
* - le de volta e valida
|
|
20
|
+
*/
|
|
10
21
|
async isRunning() {
|
|
11
22
|
const key = new unique_entity_id_1.UniqueEntityId().toValue();
|
|
12
23
|
await this.set(key, JSON.stringify({ ping: true }), this.connection?.timeout || 60);
|
|
@@ -1,53 +1,130 @@
|
|
|
1
1
|
import { LOG_LEVEL } from '../../infra/environment/types';
|
|
2
2
|
import { Cache } from '../cache/cache';
|
|
3
|
+
/**
|
|
4
|
+
* Identifica o tipo de ator que originou o log.
|
|
5
|
+
*/
|
|
3
6
|
export declare enum ActorEnum {
|
|
4
7
|
SYSTEM = "system",
|
|
5
8
|
USER = "user"
|
|
6
9
|
}
|
|
10
|
+
/**
|
|
11
|
+
* Categoriza o log em negócio ou técnico.
|
|
12
|
+
*/
|
|
7
13
|
export declare enum CategoryEnum {
|
|
8
14
|
BUSINESS = "business",
|
|
9
15
|
TECHNICAL = "technical"
|
|
10
16
|
}
|
|
17
|
+
/**
|
|
18
|
+
* Propriedades obrigatórias após a construção do log.
|
|
19
|
+
*/
|
|
11
20
|
export interface LogProperties {
|
|
12
21
|
level: LOG_LEVEL;
|
|
13
22
|
actor: string;
|
|
14
23
|
type: string;
|
|
15
24
|
dateTime: Date;
|
|
16
25
|
}
|
|
26
|
+
/**
|
|
27
|
+
* Propriedades mínimas de entrada para logar.
|
|
28
|
+
*/
|
|
17
29
|
export interface LogPropertiesInput {
|
|
18
30
|
level: LOG_LEVEL;
|
|
19
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* Parâmetros padrão usados para construir propriedades de log.
|
|
34
|
+
*/
|
|
20
35
|
export interface LogParams {
|
|
21
36
|
actor: string;
|
|
22
37
|
type: string;
|
|
23
38
|
}
|
|
24
|
-
export
|
|
25
|
-
|
|
39
|
+
export type LogParamsInput = Partial<LogParams>;
|
|
40
|
+
/**
|
|
41
|
+
* Opções de comportamento do logger.
|
|
42
|
+
*/
|
|
26
43
|
export interface LogOptions {
|
|
44
|
+
/**
|
|
45
|
+
* Quando `true`, assume que o último argumento do log é `params` adicionais.
|
|
46
|
+
*/
|
|
27
47
|
lastArgIsParams?: boolean;
|
|
28
48
|
}
|
|
49
|
+
/**
|
|
50
|
+
* Interface mínima de um logger.
|
|
51
|
+
*/
|
|
29
52
|
export interface Logger {
|
|
30
53
|
info: (...input: any[]) => Promise<void> | void;
|
|
31
54
|
warn: (...input: any[]) => Promise<void> | void;
|
|
32
55
|
error: (...input: any[]) => Promise<void> | void;
|
|
33
56
|
debug: (...input: any[]) => Promise<void> | void;
|
|
34
57
|
}
|
|
58
|
+
/**
|
|
59
|
+
* Classe base para loggers.
|
|
60
|
+
*
|
|
61
|
+
* Responsável por:
|
|
62
|
+
* - Montar propriedades padrão (`actor`, `type`, `level`, `dateTime`).
|
|
63
|
+
* - Aplicar filtros por nível com apoio opcional de cache.
|
|
64
|
+
* - Delegar o envio para a implementação concreta (`register`).
|
|
65
|
+
*/
|
|
35
66
|
export default abstract class LoggerGateway implements Logger {
|
|
36
67
|
protected cache?: Cache | undefined;
|
|
37
68
|
protected options?: LogOptions | undefined;
|
|
38
|
-
protected params?:
|
|
39
|
-
constructor(cache?: Cache | undefined, options?: LogOptions | undefined, params?:
|
|
69
|
+
protected params?: Partial<LogParams> | undefined;
|
|
70
|
+
constructor(cache?: Cache | undefined, options?: LogOptions | undefined, params?: Partial<LogParams> | undefined);
|
|
40
71
|
private static cacheKey;
|
|
72
|
+
/**
|
|
73
|
+
* Loga com nível `info`.
|
|
74
|
+
*/
|
|
41
75
|
info(...input: any[]): Promise<void>;
|
|
76
|
+
/**
|
|
77
|
+
* Loga com nível `warn`.
|
|
78
|
+
*/
|
|
42
79
|
warn(...input: any[]): Promise<void>;
|
|
80
|
+
/**
|
|
81
|
+
* Loga com nível `error`.
|
|
82
|
+
*/
|
|
43
83
|
error(...input: any[]): Promise<void>;
|
|
84
|
+
/**
|
|
85
|
+
* Loga com nível `debug`.
|
|
86
|
+
*/
|
|
44
87
|
debug(...input: any[]): Promise<void>;
|
|
88
|
+
/**
|
|
89
|
+
* Fluxo principal de logging.
|
|
90
|
+
*
|
|
91
|
+
* - Extrai params extras quando `lastArgIsParams` estiver habilitado.
|
|
92
|
+
* - Monta propriedades finais.
|
|
93
|
+
* - Checa se deve logar (nível/cache).
|
|
94
|
+
* - Delegada envio para `register`.
|
|
95
|
+
*/
|
|
45
96
|
log(props: LogPropertiesInput, dataToLog: any): Promise<void>;
|
|
97
|
+
/**
|
|
98
|
+
* Implementação concreta deve persistir/enviar o log.
|
|
99
|
+
*/
|
|
46
100
|
protected abstract register(props: LogProperties, dataToLog: any, params?: LogParams): Promise<void> | void;
|
|
101
|
+
/**
|
|
102
|
+
* Constrói a lista de níveis aceitos com base no nível configurado.
|
|
103
|
+
*/
|
|
47
104
|
private static buildAcceptLogLevelValues;
|
|
105
|
+
/**
|
|
106
|
+
* Decide se o log deve ser emitido.
|
|
107
|
+
*
|
|
108
|
+
* - `error` sempre é emitido.
|
|
109
|
+
* - Sem cache, sempre emite.
|
|
110
|
+
* - Com cache, consulta o nível permitido por tipo/actor.
|
|
111
|
+
*/
|
|
48
112
|
protected isToLog(props: LogProperties, dataToLog: any): Promise<boolean>;
|
|
113
|
+
/**
|
|
114
|
+
* Monta as propriedades finais do log.
|
|
115
|
+
*/
|
|
49
116
|
protected buildProps(props?: LogPropertiesInput, params?: LogParamsInput): LogProperties;
|
|
117
|
+
/**
|
|
118
|
+
* Monta propriedades padrão.
|
|
119
|
+
*/
|
|
50
120
|
protected buildDefaultProps(params?: LogParamsInput): LogProperties;
|
|
121
|
+
/**
|
|
122
|
+
* Define o nível de log no cache para um filtro (type/actor).
|
|
123
|
+
*
|
|
124
|
+
* @param level Nível mínimo a ser aceito.
|
|
125
|
+
* @param filter Filtro de log por tipo e ator.
|
|
126
|
+
* @param ttl Tempo em segundos (default 4 dias).
|
|
127
|
+
*/
|
|
51
128
|
setLevel(level: LOG_LEVEL, filter: {
|
|
52
129
|
logType: string;
|
|
53
130
|
logActor: string;
|
|
@@ -2,16 +2,30 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.CategoryEnum = exports.ActorEnum = void 0;
|
|
4
4
|
const types_1 = require("../../infra/environment/types");
|
|
5
|
+
/**
|
|
6
|
+
* Identifica o tipo de ator que originou o log.
|
|
7
|
+
*/
|
|
5
8
|
var ActorEnum;
|
|
6
9
|
(function (ActorEnum) {
|
|
7
10
|
ActorEnum["SYSTEM"] = "system";
|
|
8
11
|
ActorEnum["USER"] = "user";
|
|
9
12
|
})(ActorEnum || (exports.ActorEnum = ActorEnum = {}));
|
|
13
|
+
/**
|
|
14
|
+
* Categoriza o log em negócio ou técnico.
|
|
15
|
+
*/
|
|
10
16
|
var CategoryEnum;
|
|
11
17
|
(function (CategoryEnum) {
|
|
12
18
|
CategoryEnum["BUSINESS"] = "business";
|
|
13
19
|
CategoryEnum["TECHNICAL"] = "technical";
|
|
14
20
|
})(CategoryEnum || (exports.CategoryEnum = CategoryEnum = {}));
|
|
21
|
+
/**
|
|
22
|
+
* Classe base para loggers.
|
|
23
|
+
*
|
|
24
|
+
* Responsável por:
|
|
25
|
+
* - Montar propriedades padrão (`actor`, `type`, `level`, `dateTime`).
|
|
26
|
+
* - Aplicar filtros por nível com apoio opcional de cache.
|
|
27
|
+
* - Delegar o envio para a implementação concreta (`register`).
|
|
28
|
+
*/
|
|
15
29
|
class LoggerGateway {
|
|
16
30
|
cache;
|
|
17
31
|
options;
|
|
@@ -22,18 +36,38 @@ class LoggerGateway {
|
|
|
22
36
|
this.params = params;
|
|
23
37
|
}
|
|
24
38
|
static cacheKey = 'LOG_LEVEL';
|
|
39
|
+
/**
|
|
40
|
+
* Loga com nível `info`.
|
|
41
|
+
*/
|
|
25
42
|
async info(...input) {
|
|
26
43
|
return await this.log({ level: types_1.LOG_LEVEL.info }, input);
|
|
27
44
|
}
|
|
45
|
+
/**
|
|
46
|
+
* Loga com nível `warn`.
|
|
47
|
+
*/
|
|
28
48
|
async warn(...input) {
|
|
29
49
|
return await this.log({ level: types_1.LOG_LEVEL.warn }, input);
|
|
30
50
|
}
|
|
51
|
+
/**
|
|
52
|
+
* Loga com nível `error`.
|
|
53
|
+
*/
|
|
31
54
|
async error(...input) {
|
|
32
55
|
return await this.log({ level: types_1.LOG_LEVEL.error }, input);
|
|
33
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* Loga com nível `debug`.
|
|
59
|
+
*/
|
|
34
60
|
async debug(...input) {
|
|
35
61
|
return await this.log({ level: types_1.LOG_LEVEL.debug }, input);
|
|
36
62
|
}
|
|
63
|
+
/**
|
|
64
|
+
* Fluxo principal de logging.
|
|
65
|
+
*
|
|
66
|
+
* - Extrai params extras quando `lastArgIsParams` estiver habilitado.
|
|
67
|
+
* - Monta propriedades finais.
|
|
68
|
+
* - Checa se deve logar (nível/cache).
|
|
69
|
+
* - Delegada envio para `register`.
|
|
70
|
+
*/
|
|
37
71
|
async log(props, dataToLog) {
|
|
38
72
|
try {
|
|
39
73
|
let params = this.params;
|
|
@@ -43,6 +77,7 @@ class LoggerGateway {
|
|
|
43
77
|
...dataToLog[dataToLog.length - 1],
|
|
44
78
|
};
|
|
45
79
|
dataToLog = dataToLog.slice(0, dataToLog.length - 1);
|
|
80
|
+
dataToLog = dataToLog.length === 1 ? dataToLog[0] : dataToLog;
|
|
46
81
|
}
|
|
47
82
|
const buildedProperties = this.buildProps(props, params);
|
|
48
83
|
const isToLog = await this.isToLog(buildedProperties, dataToLog);
|
|
@@ -56,6 +91,9 @@ class LoggerGateway {
|
|
|
56
91
|
console.log('Input', props, dataToLog);
|
|
57
92
|
}
|
|
58
93
|
}
|
|
94
|
+
/**
|
|
95
|
+
* Constrói a lista de níveis aceitos com base no nível configurado.
|
|
96
|
+
*/
|
|
59
97
|
static buildAcceptLogLevelValues(level) {
|
|
60
98
|
const acceptValues = [types_1.LOG_LEVEL.error];
|
|
61
99
|
if (level === types_1.LOG_LEVEL.warn) {
|
|
@@ -69,6 +107,13 @@ class LoggerGateway {
|
|
|
69
107
|
}
|
|
70
108
|
return acceptValues;
|
|
71
109
|
}
|
|
110
|
+
/**
|
|
111
|
+
* Decide se o log deve ser emitido.
|
|
112
|
+
*
|
|
113
|
+
* - `error` sempre é emitido.
|
|
114
|
+
* - Sem cache, sempre emite.
|
|
115
|
+
* - Com cache, consulta o nível permitido por tipo/actor.
|
|
116
|
+
*/
|
|
72
117
|
async isToLog(props, dataToLog) {
|
|
73
118
|
if (props.level === types_1.LOG_LEVEL.error || !this.cache) {
|
|
74
119
|
return true;
|
|
@@ -97,6 +142,9 @@ class LoggerGateway {
|
|
|
97
142
|
const acceptValues = LoggerGateway.buildAcceptLogLevelValues(cachedValue);
|
|
98
143
|
return acceptValues.includes(props.level);
|
|
99
144
|
}
|
|
145
|
+
/**
|
|
146
|
+
* Monta as propriedades finais do log.
|
|
147
|
+
*/
|
|
100
148
|
buildProps(props, params) {
|
|
101
149
|
const defaultProps = this.buildDefaultProps(params);
|
|
102
150
|
if (props) {
|
|
@@ -107,6 +155,9 @@ class LoggerGateway {
|
|
|
107
155
|
}
|
|
108
156
|
return defaultProps;
|
|
109
157
|
}
|
|
158
|
+
/**
|
|
159
|
+
* Monta propriedades padrão.
|
|
160
|
+
*/
|
|
110
161
|
buildDefaultProps(params) {
|
|
111
162
|
return {
|
|
112
163
|
level: types_1.LOG_LEVEL.info,
|
|
@@ -116,6 +167,13 @@ class LoggerGateway {
|
|
|
116
167
|
...(params || {}),
|
|
117
168
|
};
|
|
118
169
|
}
|
|
170
|
+
/**
|
|
171
|
+
* Define o nível de log no cache para um filtro (type/actor).
|
|
172
|
+
*
|
|
173
|
+
* @param level Nível mínimo a ser aceito.
|
|
174
|
+
* @param filter Filtro de log por tipo e ator.
|
|
175
|
+
* @param ttl Tempo em segundos (default 4 dias).
|
|
176
|
+
*/
|
|
119
177
|
async setLevel(level, filter, ttl) {
|
|
120
178
|
if (!this.cache) {
|
|
121
179
|
return;
|
|
@@ -1,7 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Classe base para consumidores de fila.
|
|
3
|
+
*
|
|
4
|
+
* A ideia é estender esta classe e implementar o método `handle`.
|
|
5
|
+
* A lib usa os metadados abaixo para controlar concorrência e timeout.
|
|
6
|
+
*/
|
|
1
7
|
export default abstract class Handler {
|
|
8
|
+
/**
|
|
9
|
+
* Quantas mensagens podem ser processadas em paralelo.
|
|
10
|
+
*
|
|
11
|
+
* No RabbitMQ (`AmqpQueue.on`), este valor é aplicado como `prefetch`.
|
|
12
|
+
* Nos runners de ScaledJob, ele é usado como limite por execução.
|
|
13
|
+
*/
|
|
2
14
|
protected simultaneity: number;
|
|
15
|
+
/**
|
|
16
|
+
* Timeout por mensagem, em segundos.
|
|
17
|
+
*
|
|
18
|
+
* Quando definido, alguns runners competem o `handle` contra um timeout.
|
|
19
|
+
*/
|
|
3
20
|
protected timeoutPerMessageSeconds: number | undefined;
|
|
21
|
+
/**
|
|
22
|
+
* Retorna o nível de concorrência configurado para o handler.
|
|
23
|
+
*/
|
|
4
24
|
getSimultaneity(): number;
|
|
25
|
+
/**
|
|
26
|
+
* Retorna o timeout por mensagem, em segundos, se definido.
|
|
27
|
+
*/
|
|
5
28
|
getTimeoutPerMessageSeconds(): number | undefined;
|
|
29
|
+
/**
|
|
30
|
+
* Processa uma única mensagem.
|
|
31
|
+
*
|
|
32
|
+
* @param message Mensagem já desserializada (normalmente um objeto JSON).
|
|
33
|
+
*/
|
|
6
34
|
abstract handle(message: any): Promise<void>;
|
|
7
35
|
}
|
|
@@ -1,11 +1,34 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
/**
|
|
4
|
+
* Classe base para consumidores de fila.
|
|
5
|
+
*
|
|
6
|
+
* A ideia é estender esta classe e implementar o método `handle`.
|
|
7
|
+
* A lib usa os metadados abaixo para controlar concorrência e timeout.
|
|
8
|
+
*/
|
|
3
9
|
class Handler {
|
|
10
|
+
/**
|
|
11
|
+
* Quantas mensagens podem ser processadas em paralelo.
|
|
12
|
+
*
|
|
13
|
+
* No RabbitMQ (`AmqpQueue.on`), este valor é aplicado como `prefetch`.
|
|
14
|
+
* Nos runners de ScaledJob, ele é usado como limite por execução.
|
|
15
|
+
*/
|
|
4
16
|
simultaneity = 1;
|
|
17
|
+
/**
|
|
18
|
+
* Timeout por mensagem, em segundos.
|
|
19
|
+
*
|
|
20
|
+
* Quando definido, alguns runners competem o `handle` contra um timeout.
|
|
21
|
+
*/
|
|
5
22
|
timeoutPerMessageSeconds = undefined;
|
|
23
|
+
/**
|
|
24
|
+
* Retorna o nível de concorrência configurado para o handler.
|
|
25
|
+
*/
|
|
6
26
|
getSimultaneity() {
|
|
7
27
|
return this.simultaneity;
|
|
8
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* Retorna o timeout por mensagem, em segundos, se definido.
|
|
31
|
+
*/
|
|
9
32
|
getTimeoutPerMessageSeconds() {
|
|
10
33
|
return this.timeoutPerMessageSeconds;
|
|
11
34
|
}
|
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
import DomainEvent from '../../domain/events/domain-event';
|
|
2
|
+
/**
|
|
3
|
+
* Representa uma publicação que falhou e foi guardada em memória.
|
|
4
|
+
*
|
|
5
|
+
* A implementação AMQP usa esta estrutura para re-publicar mensagens
|
|
6
|
+
* após reconexões.
|
|
7
|
+
*/
|
|
2
8
|
export type MessagesInMemory = {
|
|
3
9
|
exchangeName: string;
|
|
4
10
|
domainEvent: DomainEvent;
|
|
@@ -1,9 +1,26 @@
|
|
|
1
1
|
import Queue from './queue';
|
|
2
|
+
/**
|
|
3
|
+
* Contrato de conexão com a infraestrutura de filas.
|
|
4
|
+
*
|
|
5
|
+
* Estende o contrato de `Queue` com ciclo de vida (`connect`/`close`)
|
|
6
|
+
* e com a capacidade opcional de declarar topologia (`createConsumers`).
|
|
7
|
+
*/
|
|
2
8
|
export default interface QueueConnection extends Queue {
|
|
9
|
+
/**
|
|
10
|
+
* Abre a conexão com o provedor de fila.
|
|
11
|
+
*
|
|
12
|
+
* @param props Parâmetros de conexão (ex.: vHost no RabbitMQ).
|
|
13
|
+
*/
|
|
3
14
|
connect(props: unknown): Promise<any>;
|
|
15
|
+
/**
|
|
16
|
+
* Encerra a conexão atual.
|
|
17
|
+
*/
|
|
4
18
|
close(): Promise<void>;
|
|
5
19
|
/**
|
|
20
|
+
* Declara a topologia necessária para um consumidor.
|
|
6
21
|
*
|
|
22
|
+
* Este método é opcional porque algumas implementações não precisam
|
|
23
|
+
* (ou não conseguem) declarar topologia programaticamente.
|
|
7
24
|
* @deprecated Use createQueues() instead.
|
|
8
25
|
*/
|
|
9
26
|
createConsumers?<T>(queueName: string, configs: T | any): Promise<void>;
|
|
@@ -1,7 +1,38 @@
|
|
|
1
1
|
import DomainEvent from '../../domain/events/domain-event';
|
|
2
2
|
import Handler from './handler';
|
|
3
|
+
/**
|
|
4
|
+
* Contrato mínimo de uma implementação de fila.
|
|
5
|
+
*
|
|
6
|
+
* A interface foi pensada para suportar tanto consumo contínuo (`on`)
|
|
7
|
+
* quanto publicação baseada em eventos de domínio (`publish`).
|
|
8
|
+
*/
|
|
3
9
|
export default interface Queue {
|
|
10
|
+
/**
|
|
11
|
+
* Inicia o consumo contínuo de uma fila.
|
|
12
|
+
*
|
|
13
|
+
* @param queueName Nome da fila (e, por convenção, também o routing key).
|
|
14
|
+
* @param callback Handler responsável por processar cada mensagem.
|
|
15
|
+
*/
|
|
4
16
|
on(queueName: string, callback: Handler): Promise<void>;
|
|
17
|
+
/**
|
|
18
|
+
* Publica um evento de domínio em um exchange.
|
|
19
|
+
*
|
|
20
|
+
* Em implementações AMQP, o `domainEvent.name` costuma ser usado como
|
|
21
|
+
* routing key e como nome da fila por convenção.
|
|
22
|
+
*
|
|
23
|
+
* @param exchangeName Nome do exchange de destino.
|
|
24
|
+
* @param domainEvent Evento a ser publicado.
|
|
25
|
+
* @param configs Configurações específicas da implementação (ex.: TTL).
|
|
26
|
+
*/
|
|
5
27
|
publish(exchangeName: string, domainEvent: DomainEvent, configs?: Record<string, any>): Promise<void>;
|
|
28
|
+
/**
|
|
29
|
+
* Faz polling (pull) de uma mensagem.
|
|
30
|
+
*
|
|
31
|
+
* Este método é opcional porque nem toda implementação precisa suportar
|
|
32
|
+
* o modelo de consumo por polling.
|
|
33
|
+
*
|
|
34
|
+
* @param queueName Nome da fila.
|
|
35
|
+
* @param options Opções específicas da implementação (ex.: `noAck` no AMQP).
|
|
36
|
+
*/
|
|
6
37
|
get?(queueName: string, options?: any): Promise<unknown>;
|
|
7
38
|
}
|
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import { Cache } from '../../application/cache/cache';
|
|
2
2
|
import { CacheClient } from '../../application/cache/client';
|
|
3
|
+
/**
|
|
4
|
+
* Cache em memoria pronto para uso na lib.
|
|
5
|
+
* Usa NodeCache como cliente.
|
|
6
|
+
*/
|
|
3
7
|
declare class LibCache extends Cache {
|
|
4
8
|
protected client: CacheClient;
|
|
5
9
|
}
|
|
10
|
+
/** Singleton do cache em memoria. */
|
|
6
11
|
declare const libCacheInstance: LibCache;
|
|
7
12
|
export default libCacheInstance;
|
|
@@ -2,9 +2,15 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
const cache_1 = require("../../application/cache/cache");
|
|
4
4
|
const node_cache_1 = require("./clients/node-cache");
|
|
5
|
+
/**
|
|
6
|
+
* Cache em memoria pronto para uso na lib.
|
|
7
|
+
* Usa NodeCache como cliente.
|
|
8
|
+
*/
|
|
5
9
|
class LibCache extends cache_1.Cache {
|
|
6
10
|
client = new node_cache_1.NodeCache();
|
|
7
11
|
}
|
|
12
|
+
/** Singleton do cache em memoria. */
|
|
8
13
|
const libCacheInstance = new LibCache();
|
|
14
|
+
/** Inicializa no import. */
|
|
9
15
|
libCacheInstance.start();
|
|
10
16
|
exports.default = libCacheInstance;
|