@seidor-cloud-produtos/orbit-backend-lib 2.0.28 → 2.0.30

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.
@@ -65,7 +65,7 @@ class Cache {
65
65
  }
66
66
  return;
67
67
  }
68
- await logger_in_memory_1.default.debug()?.log('💾 Cache Connected');
68
+ await logger_in_memory_1.default.log('💾 Cache Connected');
69
69
  }
70
70
  async get(keyCache, options) {
71
71
  try {
@@ -148,7 +148,7 @@ class Cache {
148
148
  return isRunning;
149
149
  }
150
150
  async close(options) {
151
- await logger_in_memory_1.default.debug()?.log('💾 Cache closed');
151
+ await logger_in_memory_1.default.log('💾 Cache closed');
152
152
  try {
153
153
  return await this.client.close();
154
154
  }
@@ -1,5 +1,7 @@
1
1
  export default abstract class Handler {
2
2
  protected simultaneity: number;
3
+ protected timeoutPerMessageSeconds: number | undefined;
3
4
  getSimultaneity(): number;
5
+ getTimeoutPerMessageSeconds(): number | undefined;
4
6
  abstract handle(message: any): Promise<void>;
5
7
  }
@@ -2,8 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  class Handler {
4
4
  simultaneity = 1;
5
+ timeoutPerMessageSeconds = undefined;
5
6
  getSimultaneity() {
6
7
  return this.simultaneity;
7
8
  }
9
+ getTimeoutPerMessageSeconds() {
10
+ return this.timeoutPerMessageSeconds;
11
+ }
8
12
  }
9
13
  exports.default = Handler;
@@ -6,7 +6,6 @@ export declare class LoggerInMemory extends LoggerGateway {
6
6
  private info;
7
7
  private error;
8
8
  private warning;
9
- debug(): this | undefined;
10
9
  }
11
10
  declare const loggerInMemory: LoggerInMemory;
12
11
  export default loggerInMemory;
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.LoggerInMemory = void 0;
4
4
  const tslib_1 = require("tslib");
5
- const env_1 = require("../../infra/environment/env");
6
5
  const logger_1 = tslib_1.__importDefault(require("../../application/logger"));
7
6
  const types_1 = require("../environment/types");
8
7
  const cache_1 = require("../../../clean-arch/application/cache/cache");
@@ -33,11 +32,6 @@ class LoggerInMemory extends logger_1.default {
33
32
  warning(error, props) {
34
33
  console.warn(error, props);
35
34
  }
36
- debug() {
37
- if (env_1.env?.LOG_LEVEL === types_1.LOG_LEVEL.debug)
38
- return this;
39
- return undefined;
40
- }
41
35
  }
42
36
  exports.LoggerInMemory = LoggerInMemory;
43
37
  const loggerInMemory = new LoggerInMemory(new CacheInMemory());
@@ -1,6 +1,7 @@
1
- import Handler from '../../../clean-arch/application/queue/handler';
2
- import AmqpQueue from '../queue/rabbitmq/amqp-lib';
3
- import { AmqpQueueGetResult } from '../queue/rabbitmq/types';
1
+ /// <reference types="node" />
2
+ import Handler from '../../../application/queue/handler';
3
+ import AmqpQueue from '../../queue/rabbitmq/amqp-lib';
4
+ import { AmqpQueueGetResult } from '../../queue/rabbitmq/types';
4
5
  import { RabbitMQScaledJobOptions } from './types';
5
6
  export interface IRunnerOptions extends Partial<RabbitMQScaledJobOptions> {
6
7
  }
@@ -13,7 +14,9 @@ export declare class RabbitMQScaledJobRunner<T = any> {
13
14
  private setOptions;
14
15
  private handleError;
15
16
  protected errorStrategy(getResult: AmqpQueueGetResult): Promise<void>;
16
- private rejectTimeout;
17
+ protected parse(raw: {
18
+ content: Buffer;
19
+ }): any;
17
20
  private finishProcess;
18
21
  run(): Promise<void>;
19
22
  }
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.RabbitMQScaledJobRunner = void 0;
4
4
  const tslib_1 = require("tslib");
5
- const logger_in_memory_1 = tslib_1.__importDefault(require("../logger/logger-in-memory"));
5
+ const logger_in_memory_1 = tslib_1.__importDefault(require("../../logger/logger-in-memory"));
6
6
  class RabbitMQScaledJobRunner {
7
7
  amqpQueue;
8
8
  queueName;
@@ -18,9 +18,6 @@ class RabbitMQScaledJobRunner {
18
18
  this.options = {
19
19
  errorStrategy: options?.errorStrategy || 'nack-dlq',
20
20
  manualAck: options?.manualAck || true,
21
- parse: options?.parse ||
22
- (raw => JSON.parse(raw.content.toString())),
23
- timeoutMs: options?.timeoutMs || 10000,
24
21
  };
25
22
  }
26
23
  async handleError(error, getResult) {
@@ -41,15 +38,16 @@ class RabbitMQScaledJobRunner {
41
38
  logger_in_memory_1.default.log('[RabbitMQScaledJobRunner] Falha ao aplicar estratégia de erro');
42
39
  }
43
40
  }
44
- rejectTimeout() {
45
- return new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), this.options.timeoutMs));
41
+ parse(raw) {
42
+ return JSON.parse(raw.content.toString());
46
43
  }
47
44
  async finishProcess() {
48
- logger_in_memory_1.default.debug()?.log('[RabbitMQScaledJobRunner] Finished process');
45
+ logger_in_memory_1.default.log('[RabbitMQScaledJobRunner] Finished process');
49
46
  }
50
47
  async run() {
51
48
  let getResult = null;
52
49
  let consumedMessages = 0;
50
+ const timeoutPerMessageSeconds = this.handler.getTimeoutPerMessageSeconds();
53
51
  const messagesToGet = this.handler.getSimultaneity();
54
52
  try {
55
53
  while (consumedMessages < messagesToGet) {
@@ -62,11 +60,13 @@ class RabbitMQScaledJobRunner {
62
60
  return;
63
61
  }
64
62
  const { channel, rawMessage } = getResult;
65
- const msg = this.options.parse(rawMessage);
66
- logger_in_memory_1.default
67
- .debug()
68
- ?.log(`[RabbitMQScaledJobRunner] Mensagem recebida ${JSON.stringify(msg, null, 2)}`);
69
- await Promise.race([this.handler.handle(msg), this.rejectTimeout()]);
63
+ const msg = this.parse(rawMessage);
64
+ logger_in_memory_1.default.log(`[RabbitMQScaledJobRunner] Mensagem recebida ${JSON.stringify(msg, null, 2)}`);
65
+ const promises = [this.handler.handle(msg)];
66
+ if (timeoutPerMessageSeconds) {
67
+ promises.push(rejectTimeout(timeoutPerMessageSeconds * 1000));
68
+ }
69
+ await Promise.race(promises);
70
70
  if (this.options.manualAck) {
71
71
  await this.amqpQueue.ack(channel, rawMessage);
72
72
  }
@@ -81,9 +81,7 @@ class RabbitMQScaledJobRunner {
81
81
  if (getResult) {
82
82
  getResult = null;
83
83
  consumedMessages += 1;
84
- logger_in_memory_1.default
85
- .debug()
86
- ?.log(`[RabbitMQScaledJobRunner] Mensagens consumidas: ${consumedMessages}`);
84
+ logger_in_memory_1.default.log(`[RabbitMQScaledJobRunner] Mensagens consumidas: ${consumedMessages}`);
87
85
  }
88
86
  }
89
87
  }
@@ -0,0 +1,6 @@
1
+ import { ScaledJobOptions } from '../types';
2
+ export type ErrorStrategy = 'nack-dlq' | 'nack-requeue';
3
+ export interface RabbitMQScaledJobOptions extends ScaledJobOptions {
4
+ manualAck: boolean;
5
+ errorStrategy: ErrorStrategy;
6
+ }
@@ -0,0 +1,11 @@
1
+ import Handler from '../../../../clean-arch/application/queue/handler';
2
+ import { SQSScaledJobOptions } from './types';
3
+ export declare class SQSScaledJobRunner {
4
+ private readonly handler;
5
+ private readonly queueUrl;
6
+ private readonly options;
7
+ private sqs;
8
+ constructor(handler: Handler, queueUrl: string, options: SQSScaledJobOptions);
9
+ private static parseMessage;
10
+ run(): Promise<void>;
11
+ }
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SQSScaledJobRunner = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const logger_in_memory_1 = tslib_1.__importDefault(require("../../logger/logger-in-memory"));
6
+ const client_sqs_1 = require("@aws-sdk/client-sqs");
7
+ const types_1 = require("../../environment/types");
8
+ class SQSScaledJobRunner {
9
+ handler;
10
+ queueUrl;
11
+ options;
12
+ sqs;
13
+ constructor(handler, queueUrl, options) {
14
+ this.handler = handler;
15
+ this.queueUrl = queueUrl;
16
+ this.options = options;
17
+ this.sqs = new client_sqs_1.SQSClient({ region: this.options.sqsRegion });
18
+ }
19
+ static parseMessage(rawMessage) {
20
+ if (rawMessage === null || rawMessage === undefined) {
21
+ throw new Error('[SQSScaledJobRunner] Mensagem inválida.');
22
+ }
23
+ if (typeof rawMessage !== 'string') {
24
+ throw new Error('[SQSScaledJobRunner] Mensagem deve ser uma string.');
25
+ }
26
+ return JSON.parse(rawMessage);
27
+ }
28
+ async run() {
29
+ let consumedMessages = 0;
30
+ const simultaneity = this.handler.getSimultaneity();
31
+ const timeoutPerMessageSeconds = this.handler.getTimeoutPerMessageSeconds();
32
+ while (consumedMessages < simultaneity) {
33
+ try {
34
+ const resp = await this.sqs.send(new client_sqs_1.ReceiveMessageCommand({
35
+ QueueUrl: this.queueUrl,
36
+ MaxNumberOfMessages: 1,
37
+ WaitTimeSeconds: this.options.waitTimeSeconds,
38
+ }));
39
+ const messages = resp.Messages ?? [];
40
+ if (!messages.length) {
41
+ logger_in_memory_1.default.log('[SQSScaledJobRunner] Nenhuma mensagem disponível.', { level: types_1.LOG_LEVEL.warn });
42
+ break;
43
+ }
44
+ const [rawMessage] = messages;
45
+ const message = SQSScaledJobRunner.parseMessage(rawMessage.Body);
46
+ logger_in_memory_1.default.log(`[SQSScaledJobRunner] Mensagem recebida ${JSON.stringify(message)}`);
47
+ const promises = [this.handler.handle(message)];
48
+ if (timeoutPerMessageSeconds) {
49
+ promises.push(rejectTimeout(timeoutPerMessageSeconds * 1000));
50
+ }
51
+ await Promise.race(promises);
52
+ logger_in_memory_1.default.log('[SQSScaledJobRunner] Mensagem processada com sucesso');
53
+ await this.sqs.send(new client_sqs_1.DeleteMessageCommand({
54
+ QueueUrl: this.queueUrl,
55
+ ReceiptHandle: rawMessage.ReceiptHandle,
56
+ }));
57
+ consumedMessages++;
58
+ logger_in_memory_1.default.log('[SQSScaledJobRunner] Mensagem deletada');
59
+ }
60
+ catch (error) {
61
+ logger_in_memory_1.default.log(`[SQSScaledJobRunner] Erro: ${JSON.stringify(error)}`, { level: types_1.LOG_LEVEL.error });
62
+ }
63
+ finally {
64
+ logger_in_memory_1.default.log(`[SQSScaledJobRunner] Mensagens consumidas: ${consumedMessages}`);
65
+ }
66
+ }
67
+ }
68
+ }
69
+ exports.SQSScaledJobRunner = SQSScaledJobRunner;
@@ -0,0 +1,5 @@
1
+ import { ScaledJobOptions } from '../types';
2
+ export interface SQSScaledJobOptions extends ScaledJobOptions {
3
+ waitTimeSeconds: number;
4
+ sqsRegion: string;
5
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ export interface ScaledJobOptions {
2
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1 @@
1
+ declare function rejectTimeout(timeoutMs: number): Promise<void>;
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ function rejectTimeout(timeoutMs) {
3
+ return new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), timeoutMs));
4
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seidor-cloud-produtos/orbit-backend-lib",
3
- "version": "2.0.28",
3
+ "version": "2.0.30",
4
4
  "description": "Internal lib for backend components",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -78,6 +78,7 @@
78
78
  "vitest": "^0.32.0"
79
79
  },
80
80
  "dependencies": {
81
+ "@aws-sdk/client-sqs": "3.940.0",
81
82
  "@fastify/cors": "8.3.0",
82
83
  "@nestjs/common": "8.4.7",
83
84
  "amqplib": "0.10.9",
@@ -1,7 +0,0 @@
1
- export type ErrorStrategy = 'nack-dlq' | 'nack-requeue';
2
- export type RabbitMQScaledJobOptions = {
3
- parse: (raw: any) => any;
4
- manualAck: boolean;
5
- errorStrategy: ErrorStrategy;
6
- timeoutMs: number;
7
- };