Skip to content

Conversation

@nolramaf
Copy link
Contributor

@nolramaf nolramaf commented Sep 1, 2025

Summary by Sourcery

Introduce a global SQS configuration mode with unified queue provisioning and event routing, add large-payload handling via S3 fallback, and enhance queue management abstractions in SqsController.

New Features:

  • Introduce a global SQS mode to automatically provision and publish events to queues across all instances under a common prefix
  • Add S3 fallback storage for oversized SQS messages when payloads exceed MAX_PAYLOAD_SIZE and S3 storage is enabled

Enhancements:

  • Refactor SqsController to dynamically choose between global and per-instance event lists and queue naming based on configuration
  • Validate message payload size and switch dataType to ‘s3’ with automatic upload when exceeding SQS limits
  • Enable content-based deduplication for globally managed FIFO queues
  • Streamline queue listing, creation, and removal abstractions using a unified prefixName parameter

Build:

  • Extend environment configuration to include SQS_GLOBAL_ENABLED, SQS_GLOBAL_PREFIX_NAME, SQS_MAX_PAYLOAD_SIZE, and per-event flags
  • Expose HttpServer.NAME in config for richer message metadata

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Sep 1, 2025

Reviewer's Guide

Introduces global SQS configuration, enabling prefix-based queue creation and event filtering, enforces payload size limits with optional S3 fallback, and refactors controller methods for uniform queue management under global or per-instance modes.

Sequence diagram for SQS event dispatch with global configuration and S3 fallback

sequenceDiagram
    participant Controller as SqsController
    participant Config as ConfigService
    participant SQS as SQS
    participant S3 as S3Service
    participant Logger as Logger

    Controller->>Config: get SQS config
    alt GLOBAL_ENABLED
        Controller->>SQS: sendMessage (global queue)
    else per-instance
        Controller->>SQS: sendMessage (instance queue)
    end
    Controller->>Config: get MAX_PAYLOAD_SIZE
    Controller->>SQS: prepare message
    alt payload size > MAX_PAYLOAD_SIZE
        Controller->>Config: get S3 config
        alt S3 ENABLED
            Controller->>S3: uploadFile
            S3-->>Controller: fileUrl
            Controller->>SQS: sendMessage (with fileUrl)
        else S3 not enabled
            Controller->>Logger: error (payload too large)
        end
    else payload size OK
        Controller->>SQS: sendMessage (with message)
    end
Loading

Class diagram for updated SqsController and Sqs config types

classDiagram
    class SqsController {
        +sqs: SQS
        +logger
        +monitor
        +name
        +status
        +set(instanceName: string, data: EventDto): Promise<any>
        +saveQueues(prefixName: string, events: string[], enable: boolean)
        +listQueues(prefixName: string)
        +removeQueuesByInstance(prefixName: string)
    }
    class Sqs {
        +ENABLED: boolean
        +GLOBAL_ENABLED: boolean
        +GLOBAL_PREFIX_NAME: string
        +ACCESS_KEY_ID: string
        +SECRET_ACCESS_KEY: string
        +ACCOUNT_ID: string
        +REGION: string
        +MAX_PAYLOAD_SIZE: number
        +EVENTS: object
    }
    SqsController --> Sqs : uses

    class ConfigService {
        +envProcess(): Env
    }
    ConfigService --> Sqs : returns Sqs config

    class HttpServer {
        +NAME: string
        +TYPE: 'http' | 'https'
        +PORT: number
        +URL: string
    }
    SqsController --> HttpServer : uses

    class S3 {
        +ENABLE: boolean
    }
    SqsController --> S3 : uses
Loading

File-Level Changes

Change Details Files
Added global SQS configuration flags and event mapping
  • Extended Sqs type with GLOBAL_ENABLED, GLOBAL_PREFIX_NAME, MAX_PAYLOAD_SIZE, and EVENTS map
  • Updated ConfigService to load new GLOBAL_* env vars and add SERVER.NAME
  • Aligned .env.example with new SQS global variables
src/config/env.config.ts
.env.example
Enhanced SqsController initialization and guard logic for global mode
  • Switched Promise initializer to async and added global queue initialization when GLOBAL_ENABLED
  • Updated set() guard to skip operations if global mode is active
  • Uncommented redundant debug console log repositioning
src/api/integrations/event/sqs/sqs.controller.ts
Unified event filtering and queue naming based on mode
  • Fetch events from global config or per-instance settings depending on GLOBAL_ENABLED
  • Construct queueName with GLOBAL_PREFIX_NAME or instanceName accordingly
  • Include MessageDeduplicationId only when not in global mode
src/api/integrations/event/sqs/sqs.controller.ts
Implemented payload size enforcement with S3 fallback
  • Calculate JSON payload byte size and compare against MAX_PAYLOAD_SIZE
  • Upload oversized payloads to S3 when enabled and reference URL in message
  • Log error and skip sending if payload too large and S3 is disabled
src/api/integrations/event/sqs/sqs.controller.ts
Refactored queue management methods to use prefixName
  • Renamed listQueuesByInstance/removeQueuesByInstance to generic listQueues/removeQueuesByInstance with prefixName
  • Apply ContentBasedDeduplication attribute on queue creation when global mode is active
  • Update log messages and error handling to reference prefixName
src/api/integrations/event/sqs/sqs.controller.ts

Possibly linked issues

  • Docker folder is deleted #1: The PR implements the global SQS configuration, including new environment variables and logic to enable and use global queues, directly addressing the issue where global SQS was not functioning.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes and they look great!

Blocking issues:

  • Detected possible user input going into a path.join or path.resolve function. This could possibly lead to a path traversal vulnerability, where the attacker can access arbitrary files stored in the file system. Instead, be sure to sanitize or validate user input first. (link)
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `src/api/integrations/event/sqs/sqs.controller.ts:25` </location>
<code_context>
     }

-    new Promise<void>((resolve) => {
+    new Promise<void>(async (resolve) => {
       const awsConfig = configService.get<Sqs>('SQS');

</code_context>

<issue_to_address>
Using an async executor in a Promise is discouraged.

Refactor to avoid passing an async function to the Promise constructor, as this may cause unhandled rejections. Use an async function directly or restructure the logic.
</issue_to_address>

### Comment 2
<location> `src/config/env.config.ts:508` </location>
<code_context>
         SECRET_ACCESS_KEY: process.env.SQS_SECRET_ACCESS_KEY || '',
         ACCOUNT_ID: process.env.SQS_ACCOUNT_ID || '',
         REGION: process.env.SQS_REGION || '',
+        MAX_PAYLOAD_SIZE: Number.parseInt(process.env.SQS_MAX_PAYLOAD_SIZE) || 1048576,
+        EVENTS: {
+          APPLICATION_STARTUP: process.env?.SQS_GLOBAL_APPLICATION_STARTUP === 'true',
</code_context>

<issue_to_address>
Default MAX_PAYLOAD_SIZE may mask misconfiguration.

Log a warning if SQS_MAX_PAYLOAD_SIZE is missing or invalid to help detect configuration issues early.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
        MAX_PAYLOAD_SIZE: Number.parseInt(process.env.SQS_MAX_PAYLOAD_SIZE) || 1048576,
=======
        MAX_PAYLOAD_SIZE: (() => {
          const raw = process.env.SQS_MAX_PAYLOAD_SIZE;
          const parsed = Number.parseInt(raw ?? '');
          if (!raw || isNaN(parsed)) {
            console.warn(
              '[config] Warning: SQS_MAX_PAYLOAD_SIZE is missing or invalid. Using default value 1048576.'
            );
            return 1048576;
          }
          return parsed;
        })(),
>>>>>>> REPLACE

</suggested_fix>

## Security Issues

### Issue 1
<location> `src/api/integrations/event/sqs/sqs.controller.ts:156` </location>

<issue_to_address>
**security (javascript.lang.security.audit.path-traversal.path-join-resolve-traversal):** Detected possible user input going into a `path.join` or `path.resolve` function. This could possibly lead to a path traversal vulnerability,  where the attacker can access arbitrary files stored in the file system. Instead, be sure to sanitize or validate user input first.

*Source: opengrep*
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

}

new Promise<void>((resolve) => {
new Promise<void>(async (resolve) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: Using an async executor in a Promise is discouraged.

Refactor to avoid passing an async function to the Promise constructor, as this may cause unhandled rejections. Use an async function directly or restructure the logic.

SECRET_ACCESS_KEY: process.env.SQS_SECRET_ACCESS_KEY || '',
ACCOUNT_ID: process.env.SQS_ACCOUNT_ID || '',
REGION: process.env.SQS_REGION || '',
MAX_PAYLOAD_SIZE: Number.parseInt(process.env.SQS_MAX_PAYLOAD_SIZE) || 1048576,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Default MAX_PAYLOAD_SIZE may mask misconfiguration.

Log a warning if SQS_MAX_PAYLOAD_SIZE is missing or invalid to help detect configuration issues early.

Suggested change
MAX_PAYLOAD_SIZE: Number.parseInt(process.env.SQS_MAX_PAYLOAD_SIZE) || 1048576,
MAX_PAYLOAD_SIZE: (() => {
const raw = process.env.SQS_MAX_PAYLOAD_SIZE;
const parsed = Number.parseInt(raw ?? '');
if (!raw || isNaN(parsed)) {
console.warn(
'[config] Warning: SQS_MAX_PAYLOAD_SIZE is missing or invalid. Using default value 1048576.'
);
return 1048576;
}
return parsed;
})(),

const fileName = `${instanceName}_${eventFormatted}_${Date.now()}.json`;
const fullName = join(
'messages',
fileName
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security (javascript.lang.security.audit.path-traversal.path-join-resolve-traversal): Detected possible user input going into a path.join or path.resolve function. This could possibly lead to a path traversal vulnerability, where the attacker can access arbitrary files stored in the file system. Instead, be sure to sanitize or validate user input first.

Source: opengrep

Comment on lines 181 to 203
if (err) {
this.logger.error({
local: `${origin}.sendData-SQS`,
params: JSON.stringify(message),
sqsUrl: sqsUrl,
message: err?.message,
hostName: err?.hostname,
code: err?.code,
stack: err?.stack,
name: err?.name,
url: queueName,
server_url: serverUrl,
});
} else {
if (configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
const logData = {
local: `${origin}.sendData-SQS`,
...message,
};

this.logger.log(logData);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): Merge else clause's nested if statement into else if (merge-else-if)

Suggested change
if (err) {
this.logger.error({
local: `${origin}.sendData-SQS`,
params: JSON.stringify(message),
sqsUrl: sqsUrl,
message: err?.message,
hostName: err?.hostname,
code: err?.code,
stack: err?.stack,
name: err?.name,
url: queueName,
server_url: serverUrl,
});
} else {
if (configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
const logData = {
local: `${origin}.sendData-SQS`,
...message,
};
this.logger.log(logData);
}
}
if (err) {
this.logger.error({
local: `${origin}.sendData-SQS`,
params: JSON.stringify(message),
sqsUrl: sqsUrl,
message: err?.message,
hostName: err?.hostname,
code: err?.code,
stack: err?.stack,
name: err?.name,
url: queueName,
server_url: serverUrl,
});
}
else if (configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
const logData = {
local: `${origin}.sendData-SQS`,
...message,
};
this.logger.log(logData);
}


ExplanationFlattening if statements nested within else clauses generates code that is
easier to read and expand upon.

@DavidsonGomes DavidsonGomes changed the base branch from main to develop September 1, 2025 13:47
Copy link
Contributor Author

@nolramaf nolramaf left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I’ve reviewed and implemented the suggested adjustments

@nolramaf nolramaf closed this Sep 1, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant