Skip to content

feat: service state#667

Merged
basmasking merged 16 commits intomainfrom
561-add-grace-period-to-health-check-system
Jul 18, 2025
Merged

feat: service state#667
basmasking merged 16 commits intomainfrom
561-add-grace-period-to-health-check-system

Conversation

@petermasking
Copy link
Copy Markdown
Member

@petermasking petermasking commented Jul 14, 2025

Fixes #561
Fixes #565

Changes proposed in this pull request:

  • All service types maintain state (starting, available, unavailable, stopping, stopped)
  • Workers push their state to the gateway
  • The gateway removes nodes that do not report their state frequently
  • Fine-grained monitoring configuration

@MaskingTechnology/jitar

@petermasking petermasking requested a review from basmasking as a code owner July 14, 2025 13:17
@petermasking petermasking linked an issue Jul 14, 2025 that may be closed by this pull request
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jul 14, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a scheduling system for periodic tasks, including a new scheduling package.
    • Added lifecycle and availability state management for gateways, workers, repositories, and services.
    • Workers now report their state to the gateway, supporting custom thresholds for availability and stoppage.
    • Added request pooling for managing concurrent request execution.
    • Enhanced configuration options for worker reporting intervals and remote worker monitoring thresholds.
    • Improved documentation with new examples and migration guides.
  • Bug Fixes

    • Worker selection now only chooses available workers.
  • Refactor

    • Replaced internal worker monitoring with explicit state reporting and scheduling.
    • Unified lifecycle management across services for more robust state handling.
    • Updated configuration property names for clarity (e.g., monitormonitorInterval).
  • Chores

    • Added new and updated test fixtures to support health, scheduling, and state management.
    • Removed deprecated worker monitoring components and related tests.

Summary by CodeRabbit

  • New Features

    • Introduced a scheduling system for periodic tasks, including new scheduling and scheduled task management capabilities.
    • Added explicit lifecycle and state management to core services, workers, gateways, and repositories, with improved availability and health tracking.
    • Enabled configurable intervals for worker status reporting and gateway monitoring, including new thresholds for remote worker availability.
    • Added APIs for reporting and updating worker state and availability.
    • Enhanced documentation with configuration examples and migration guidance for new and renamed properties.
  • Bug Fixes

    • Worker selection now only includes available workers, improving reliability in load balancing.
  • Chores

    • Added new test fixtures and updated test setups to align with new health and scheduling dependencies.
    • Removed deprecated worker monitoring logic and related tests.
    • Updated package dependencies to include new scheduling modules.

Walkthrough

This update introduces a major refactor of the health check and worker monitoring system. It replaces the gateway's pull-based health monitoring with a push-based system, where workers report their state to the gateway. New scheduling and state management components are added, configuration options are updated, and extensive changes are made across service interfaces, lifecycle management, and documentation.

Changes

File(s) Change Summary
documentation/docs/deploy/health-checks.md, documentation/docs/fundamentals/runtime-services.md, migrations/migrate-from-0.9.x-to-0.10.0.md Updated documentation to clarify push-based health checks, new configuration options, and migration steps.
packages/configuration/src/server/definitions/GatewayConfiguration.ts, .../RemoteWorkerConfiguration.ts, .../ServerConfiguration.ts, .../WorkerConfiguration.ts, .../index.ts, .../fixtures/configuration.fixture.ts Added/renamed configuration properties for monitoring/reporting intervals and thresholds; updated exports and validation.
packages/health/src/HealthManager.ts, .../definitions/States.ts, .../index.ts Introduced explicit lifecycle state management in HealthManager and added state definitions/exports.
packages/http/src/HttpRemote.ts, .../HttpServer.ts Added endpoint and client method for workers to report their state to the gateway.
packages/middleware/src/MiddlewareManager.ts, .../definitions/States.ts, .../index.ts Added lifecycle state management to MiddlewareManager and exported new state definitions.
packages/runtime/src/client/Client.ts, .../ClientBuilder.ts Integrated health and schedule managers, request pooling, and updated client lifecycle logic.
packages/runtime/src/server/Server.ts, .../ServerBuilder.ts, .../types/ReportWorkerRequest.ts Refactored server to use push-based worker state reporting, new RemoteWorkerBuilder, and updated worker handling logic.
packages/services/package.json, .../src/Service.ts, .../common/Remote.ts, .../common/ReportedStateManager.ts, .../common/RequestPool.ts, .../common/StateManager.ts, .../common/definitions/States.ts, .../dummy/DummyProvider.ts, .../dummy/DummyRunner.ts Added new state and request pooling classes, extended interfaces for state reporting, and updated dummy implementations.
packages/services/src/gateway/Gateway.ts, .../LocalGateway.ts, .../RemoteGateway.ts, .../WorkerBalancer.ts, .../WorkerManager.ts, .../WorkerMonitor.ts (deleted), .../index.ts Replaced pull-based WorkerMonitor with push-based reporting, updated gateway/worker manager logic, and changed exports.
packages/services/src/proxy/LocalProxy.ts, .../repository/LocalRepository.ts, .../repository/RemoteRepository.ts Refactored proxies and repositories to use new state management and health integration.
packages/services/src/worker/LocalWorker.ts, .../RemoteWorker.ts, .../RemoteWorkerBuilder.ts, .../Worker.ts Refactored workers to support push-based state reporting, scheduling, and new state management.
packages/services/test/gateway/LocalGateway.spec.ts, .../repository/LocalRepository.spec.ts, .../worker/LocalWorker.spec.ts Added TODO comments for future state tests.
packages/services/test/gateway/fixtures/healthManager.fixture.ts, .../localGateways.fixture.ts, .../remoteWorkers.fixture.ts, .../remotes.fixture.ts, .../sourcingManager.fixture.ts, .../scheduleManager.fixture.ts, .../workerManagers.fixture.ts, .../workerMonitors.fixture.ts (deleted), .../index.ts Updated or added test fixtures to match new dependencies and removed obsolete worker monitor fixtures.
packages/services/test/repository/fixtures/healthManager.fixture.ts, .../localRepositories.fixture.ts Updated repository test fixtures for health manager integration.
packages/services/test/worker/fixtures/executionManager.fixture.ts, .../healthManager.fixture.ts, .../localWorkers.fixture.ts, .../sourcingManager.fixture.ts, .../scheduleManager.fixture.ts Updated/added worker test fixtures for new dependencies.
packages/runtime/package.json, packages/scheduling/CHANGELOG.md, .../README.md, .../package.json, .../src/ScheduleManager.ts, .../src/ScheduledTask.ts, .../src/index.ts, .../src/types/Task.ts, .../test/dummy.spec.ts, .../tsconfig.json, .../vite.config.ts Introduced new scheduling package with manager, task, and configuration files.
packages/services/src/common/errors/RequestCancelled.ts Added new error type for cancelled requests.

Sequence Diagram(s)

sequenceDiagram
    participant Worker
    participant Gateway
    participant HealthManager
    participant ScheduleManager

    loop Periodic State Report
        Worker->>Gateway: reportWorker(id, state)
        Gateway->>WorkerManager: reportWorker(id, state)
        WorkerManager->>Worker: reportState(state)
    end

    Note over Worker,Gateway: Worker pushes state to Gateway instead of Gateway polling Worker
Loading

Suggested reviewers

  • basmasking

Poem

In the warren of code, the rabbits convene,
Pushing health states, keeping systems serene.
No more will the gateway chase after the crowd—
Now workers report in, honest and proud.
Schedules are ticking, states are in sync,
This pushy new system is sleeker, I think!
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e641dfe and 846c248.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (1)
  • packages/scheduling/README.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/scheduling/README.md

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
Copy Markdown

@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: 19

🔭 Outside diff range comments (1)
packages/services/test/gateway/fixtures/remotes.fixture.ts (1)

22-25: The provide() method is inconsistent with other methods

While all other methods in this test fixture have been updated to return resolved promises, the provide() method still throws NotImplemented. This inconsistency could cause unexpected test failures when this method is called.

Apply this diff to maintain consistency:

-    provide(filename: string): Promise<File>
-    {
-        throw new NotImplemented();
-    }
+    provide(filename: string): Promise<File>
+    {
+        // Return a dummy file for testing
+        return Promise.resolve(new File(filename, ''));
+    }

Note: You'll need to verify that the File constructor accepts these parameters or adjust accordingly.

♻️ Duplicate comments (1)
packages/middleware/src/definitions/States.ts (1)

2-8: Duplicate definition – keep in sync with shared source.

See comment on packages/health/src/definitions/States.ts; the same concerns (missing states & duplication) apply here.

🧹 Nitpick comments (15)
packages/health/src/definitions/States.ts (1)

10-12: Minor: inline type alias to drop the temporary Keys symbol.

You can shrink the code by skipping the intermediate Keys alias:

-type Keys = keyof typeof States;
-type State = typeof States[Keys];
+export type State = typeof States[keyof typeof States];

This removes an otherwise unused type.

packages/middleware/src/definitions/States.ts (1)

10-12: Apply the streamlined type alias pattern here as well.

See earlier nitpick for a concise State declaration.

packages/services/test/repository/LocalRepository.spec.ts (1)

37-38: Tests for the new state behaviour are still TODO – risk of un-covered regressions.

The repository gained lifecycle/state logic; without dedicated tests we can’t guarantee correct state transitions or health reporting.

Action items:

  1. Add positive/negative cases (e.g. .start() twice should not change state, .stop() before .start() rejects, etc.).
  2. Include state assertions in existing file-provide scenarios if state affects behaviour.
packages/services/test/gateway/LocalGateway.spec.ts (1)

48-49: Gateway state handling lacks test coverage.

Similar to the repository suite, the gateway’s new state machine (and worker-reported state handling) isn’t exercised. Missing tests will hide contract breaks between gateway and workers.

Recommend mirroring the critical paths:
start → addWorker → reportWorker → stop happy-path
• illegal transitions (e.g. addWorker when STOPPED)
• worker eviction when no reports received

packages/services/test/worker/LocalWorker.spec.ts (1)

69-69: Address the missing test coverage for state functionality.

The TODO comment indicates that tests for the new state management functionality are missing. Given that the PR introduces significant state management changes to LocalWorker (including HealthManager, StateManager, and ReportManager), comprehensive test coverage is essential to ensure the reliability of the state reporting system.

Would you like me to generate test cases for the state management functionality, including state transitions, health reporting, and integration with the gateway?

packages/services/test/gateway/fixtures/remoteWorkers.fixture.ts (1)

35-45: Consider avoiding implicit state transitions in fixtures.

Manually mutating worker.state changes internal ReportedStateManager counters without exercising the normal start() / stop() flow.
For behaviour-driven tests this is fine, but for integration-style tests it may hide lifecycle regressions.

migrations/migrate-from-0.9.x-to-0.10.0.md (1)

17-27: Minor wording nit – “After” reads clearer than “Current”.

“Before / After” is the conventional pair for migration docs.

-**Current**:
+**After**:
packages/services/test/worker/fixtures/sourcingManager.fixture.ts (1)

2-4: Resolve the manager path relative to the fixture file to avoid brittle ./ resolution.

Running tests from a different CWD can break this fixture.

-import { LocalSourcingManager } from '@jitar/sourcing';
-export const sourcingManager = new LocalSourcingManager('./');
+import path from 'node:path';
+import { LocalSourcingManager } from '@jitar/sourcing';
+
+const root = path.resolve(__dirname, '../../../..'); // adjust as needed
+export const sourcingManager = new LocalSourcingManager(root);
packages/services/src/worker/RemoteWorkerBuilder.ts (1)

11-16: Consider adding threshold validation.

The constructor should validate that thresholds are positive numbers to prevent potential issues with state management.

 constructor(remoteBuilder: RemoteBuilder, unavailableThreshold?: number, stoppedThreshold?: number)
 {
     this.#remoteBuilder = remoteBuilder;
+    
+    if (unavailableThreshold !== undefined && unavailableThreshold <= 0)
+    {
+        throw new Error('unavailableThreshold must be a positive number');
+    }
+    
+    if (stoppedThreshold !== undefined && stoppedThreshold <= 0)
+    {
+        throw new Error('stoppedThreshold must be a positive number');
+    }
+    
     this.#unavailableThreshold = unavailableThreshold;
     this.#stoppedThreshold = stoppedThreshold;
 }
packages/services/src/common/RequestPool.ts (1)

41-49: Consider adding queue size limits to prevent unbounded growth.

The queue can grow without limits, potentially causing memory issues under high load.

Consider adding a maximum queue size parameter and rejecting requests when the limit is reached:

+const DEFAULT_MAX_QUEUE_SIZE = 1000;
+
 export default class RequestPool implements Runner
 {
     readonly #runner: Runner;
     readonly #size: number;
+    readonly #maxQueueSize: number;
 
     readonly #queue: QueueItem[] = [];
 
     #started = false;
     #activeCount = 0;
 
-    constructor(runner: Runner, size = DEFAULT_POOL_SIZE)
+    constructor(runner: Runner, size = DEFAULT_POOL_SIZE, maxQueueSize = DEFAULT_MAX_QUEUE_SIZE)
     {
         this.#runner = runner;
         this.#size = size;
+        this.#maxQueueSize = maxQueueSize;
     }

Then in the run method, check the queue size before adding.

packages/runtime/src/client/Client.ts (1)

49-49: Consider error handling for RequestPool lifecycle

The start() and stop() methods manage the RequestPool lifecycle, but there's no error handling if RequestPool.start() or RequestPool.stop() fail.

Consider wrapping the RequestPool operations in try-catch blocks or ensuring they're included in the Promise.all error handling:

 async start(): Promise<void>
 {
     await this.#setUp();
 
-    this.#requestPool.start();
+    try {
+        await this.#requestPool.start();
+    } catch (error) {
+        await this.#tearDown();
+        throw error;
+    }
 }

Also applies to: 54-54

packages/health/src/HealthManager.ts (1)

17-17: Consider thread safety for state transitions

While the state management is well structured, there could be race conditions if start() and stop() are called concurrently. The state transitions are not atomic.

Consider adding a mutex or similar synchronization mechanism to ensure state transitions are atomic:

private stateMutex = new Mutex(); // You'd need to implement or import a Mutex

async start(): Promise<void>
{
    await this.stateMutex.acquire();
    try {
        if (this.#state !== States.STOPPED)
        {
            return;
        }
        this.#state = States.STARTING;
    } finally {
        this.stateMutex.release();
    }
    
    await this.#loadHealthChecks();
    
    this.#state = States.STARTED;
}

Also applies to: 38-38, 52-52

packages/services/src/gateway/WorkerMonitor.ts (1)

39-42: Consider preventing overlapping monitor operations

The synchronous #monitor method spawns async operations via #checkWorker. If the monitoring interval is shorter than the time it takes to check all workers, operations could overlap.

Consider adding a flag to prevent overlapping operations:

+private isMonitoring = false;
+
 #monitor(): void
 {
+    if (this.isMonitoring) {
+        return;
+    }
+    
+    this.isMonitoring = true;
     this.#workerManager.workers.forEach(worker => this.#checkWorker(worker));
+    
+    // Reset flag after all checks complete
+    Promise.all(
+        Array.from(this.#workerManager.workers).map(worker => this.#checkWorker(worker))
+    ).finally(() => {
+        this.isMonitoring = false;
+    });
 }
packages/services/src/repository/RemoteRepository.ts (1)

72-77: Consider adding state validation in updateState().

The method can be called at any time, potentially causing unexpected state transitions (e.g., from "stopping" to "available").

Add state validation to prevent inappropriate transitions:

 async updateState(): Promise<State>
 {
+    if (this.#stateManager.isNotStarted())
+    {
+        return this.#stateManager.state;
+    }
+
     const healthy = await this.isHealthy();

     return this.#stateManager.setAvailability(healthy);
 }
packages/runtime/src/server/Server.ts (1)

324-334: Consider optimizing state validation for better performance.

The method recreates the states array on each call. Consider using a Set constant for faster lookup:

+const VALID_STATES = new Set(Object.values(States));
+
 #translateState(state: string): State
 {
-    const states = Object.values(States) as string[];
-
-    if (states.includes(state) === false)
+    if (!VALID_STATES.has(state))
     {
         throw new BadRequest('Invalid state value');
     }
 
     return state as State;
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7582412 and db15376.

📒 Files selected for processing (60)
  • documentation/docs/deploy/health-checks.md (1 hunks)
  • documentation/docs/fundamentals/runtime-services.md (4 hunks)
  • migrations/migrate-from-0.9.x-to-0.10.0.md (1 hunks)
  • packages/configuration/src/server/definitions/GatewayConfiguration.ts (1 hunks)
  • packages/configuration/src/server/definitions/RemoteWorkerConfiguration.ts (1 hunks)
  • packages/configuration/src/server/definitions/ServerConfiguration.ts (3 hunks)
  • packages/configuration/src/server/definitions/WorkerConfiguration.ts (2 hunks)
  • packages/configuration/src/server/index.ts (1 hunks)
  • packages/configuration/test/server/fixtures/configuration.fixture.ts (3 hunks)
  • packages/health/src/HealthManager.ts (2 hunks)
  • packages/health/src/definitions/States.ts (1 hunks)
  • packages/health/src/index.ts (1 hunks)
  • packages/http/src/HttpRemote.ts (2 hunks)
  • packages/http/src/HttpServer.ts (2 hunks)
  • packages/middleware/src/MiddlewareManager.ts (1 hunks)
  • packages/middleware/src/definitions/States.ts (1 hunks)
  • packages/middleware/src/index.ts (1 hunks)
  • packages/runtime/src/client/Client.ts (6 hunks)
  • packages/runtime/src/client/ClientBuilder.ts (2 hunks)
  • packages/runtime/src/server/Server.ts (10 hunks)
  • packages/runtime/src/server/ServerBuilder.ts (5 hunks)
  • packages/runtime/src/server/types/ReportWorkerRequest.ts (1 hunks)
  • packages/services/package.json (1 hunks)
  • packages/services/src/Service.ts (1 hunks)
  • packages/services/src/common/Remote.ts (2 hunks)
  • packages/services/src/common/ReportedStateManager.ts (1 hunks)
  • packages/services/src/common/RequestPool.ts (1 hunks)
  • packages/services/src/common/StateManager.ts (1 hunks)
  • packages/services/src/common/definitions/States.ts (1 hunks)
  • packages/services/src/dummy/DummyProvider.ts (3 hunks)
  • packages/services/src/dummy/DummyRunner.ts (3 hunks)
  • packages/services/src/gateway/Gateway.ts (1 hunks)
  • packages/services/src/gateway/LocalGateway.ts (4 hunks)
  • packages/services/src/gateway/RemoteGateway.ts (5 hunks)
  • packages/services/src/gateway/WorkerBalancer.ts (2 hunks)
  • packages/services/src/gateway/WorkerManager.ts (3 hunks)
  • packages/services/src/gateway/WorkerMonitor.ts (1 hunks)
  • packages/services/src/index.ts (2 hunks)
  • packages/services/src/proxy/LocalProxy.ts (4 hunks)
  • packages/services/src/repository/LocalRepository.ts (3 hunks)
  • packages/services/src/repository/RemoteRepository.ts (4 hunks)
  • packages/services/src/worker/LocalWorker.ts (6 hunks)
  • packages/services/src/worker/RemoteWorker.ts (3 hunks)
  • packages/services/src/worker/RemoteWorkerBuilder.ts (1 hunks)
  • packages/services/src/worker/ReportManager.ts (1 hunks)
  • packages/services/src/worker/Worker.ts (1 hunks)
  • packages/services/test/gateway/LocalGateway.spec.ts (1 hunks)
  • packages/services/test/gateway/fixtures/healthManager.fixture.ts (1 hunks)
  • packages/services/test/gateway/fixtures/localGateways.fixture.ts (1 hunks)
  • packages/services/test/gateway/fixtures/remoteWorkers.fixture.ts (2 hunks)
  • packages/services/test/gateway/fixtures/remotes.fixture.ts (2 hunks)
  • packages/services/test/gateway/fixtures/sourcingManager.fixture.ts (1 hunks)
  • packages/services/test/repository/LocalRepository.spec.ts (1 hunks)
  • packages/services/test/repository/fixtures/healthManager.fixture.ts (1 hunks)
  • packages/services/test/repository/fixtures/localRepositories.fixture.ts (1 hunks)
  • packages/services/test/worker/LocalWorker.spec.ts (1 hunks)
  • packages/services/test/worker/fixtures/executionManager.fixture.ts (1 hunks)
  • packages/services/test/worker/fixtures/healthManager.fixture.ts (1 hunks)
  • packages/services/test/worker/fixtures/localWorkers.fixture.ts (1 hunks)
  • packages/services/test/worker/fixtures/sourcingManager.fixture.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (6)
packages/services/test/worker/fixtures/sourcingManager.fixture.ts (1)
Learnt from: basmasking
PR: MaskingTechnology/jitar#638
File: packages/runtime/src/server/ServerBuilder.ts:7-8
Timestamp: 2025-05-13T18:15:31.425Z
Learning: In the Jitar codebase, always import the `Proxy` class from `@jitar/services` as `LocalProxy` to avoid shadowing the built-in JavaScript `Proxy` global object.
packages/services/test/gateway/fixtures/sourcingManager.fixture.ts (1)
Learnt from: basmasking
PR: MaskingTechnology/jitar#638
File: packages/runtime/src/server/ServerBuilder.ts:7-8
Timestamp: 2025-05-13T18:15:31.425Z
Learning: In the Jitar codebase, always import the `Proxy` class from `@jitar/services` as `LocalProxy` to avoid shadowing the built-in JavaScript `Proxy` global object.
packages/services/src/index.ts (1)
Learnt from: basmasking
PR: MaskingTechnology/jitar#638
File: packages/runtime/src/server/ServerBuilder.ts:7-8
Timestamp: 2025-05-13T18:15:31.425Z
Learning: In the Jitar codebase, always import the `Proxy` class from `@jitar/services` as `LocalProxy` to avoid shadowing the built-in JavaScript `Proxy` global object.
packages/services/src/proxy/LocalProxy.ts (1)
Learnt from: basmasking
PR: MaskingTechnology/jitar#638
File: packages/runtime/src/server/ServerBuilder.ts:7-8
Timestamp: 2025-05-13T18:15:31.425Z
Learning: In the Jitar codebase, always import the `Proxy` class from `@jitar/services` as `LocalProxy` to avoid shadowing the built-in JavaScript `Proxy` global object.
packages/runtime/src/server/Server.ts (1)
Learnt from: basmasking
PR: MaskingTechnology/jitar#638
File: packages/runtime/src/server/ServerBuilder.ts:7-8
Timestamp: 2025-05-13T18:15:31.425Z
Learning: In the Jitar codebase, always import the `Proxy` class from `@jitar/services` as `LocalProxy` to avoid shadowing the built-in JavaScript `Proxy` global object.
packages/runtime/src/server/ServerBuilder.ts (1)
Learnt from: basmasking
PR: MaskingTechnology/jitar#638
File: packages/runtime/src/server/ServerBuilder.ts:7-8
Timestamp: 2025-05-13T18:15:31.425Z
Learning: In the Jitar codebase, always import the `Proxy` class from `@jitar/services` as `LocalProxy` to avoid shadowing the built-in JavaScript `Proxy` global object.
🧬 Code Graph Analysis (19)
packages/services/test/gateway/fixtures/remoteWorkers.fixture.ts (1)
packages/services/src/worker/RemoteWorker.ts (1)
  • RemoteWorker (20-108)
packages/services/test/worker/fixtures/executionManager.fixture.ts (2)
packages/execution/src/ExecutionManager.ts (1)
  • ExecutionManager (25-160)
packages/services/test/worker/fixtures/sourcingManager.fixture.ts (1)
  • sourcingManager (4-4)
packages/services/test/repository/fixtures/healthManager.fixture.ts (2)
packages/health/src/HealthManager.ts (1)
  • HealthManager (15-160)
packages/services/test/gateway/fixtures/sourcingManager.fixture.ts (1)
  • sourcingManager (4-4)
packages/services/src/worker/Worker.ts (4)
packages/services/src/worker/LocalWorker.ts (4)
  • id (60-60)
  • id (62-62)
  • state (64-64)
  • state (66-66)
packages/services/src/worker/RemoteWorker.ts (4)
  • id (39-39)
  • id (41-41)
  • state (43-43)
  • state (45-45)
packages/services/src/common/StateManager.ts (2)
  • state (9-9)
  • state (11-11)
packages/services/src/common/definitions/States.ts (1)
  • State (15-15)
packages/services/test/worker/fixtures/sourcingManager.fixture.ts (2)
packages/services/test/gateway/fixtures/sourcingManager.fixture.ts (1)
  • sourcingManager (4-4)
packages/sourcing/src/LocalSourcingManager.ts (1)
  • LocalSourcingManager (7-16)
packages/services/src/Service.ts (1)
packages/services/src/common/definitions/States.ts (1)
  • State (15-15)
packages/services/test/gateway/fixtures/sourcingManager.fixture.ts (2)
packages/services/test/worker/fixtures/sourcingManager.fixture.ts (1)
  • sourcingManager (4-4)
packages/sourcing/src/LocalSourcingManager.ts (1)
  • LocalSourcingManager (7-16)
packages/services/src/gateway/WorkerBalancer.ts (2)
packages/services/src/gateway/WorkerMonitor.ts (2)
  • workers (39-42)
  • worker (44-52)
packages/services/src/gateway/WorkerManager.ts (1)
  • workers (18-21)
packages/services/test/worker/fixtures/healthManager.fixture.ts (2)
packages/health/src/HealthManager.ts (1)
  • HealthManager (15-160)
packages/services/test/worker/fixtures/sourcingManager.fixture.ts (1)
  • sourcingManager (4-4)
packages/runtime/src/client/ClientBuilder.ts (2)
packages/runtime/src/client/Client.ts (1)
  • Client (19-94)
packages/health/src/HealthManager.ts (1)
  • HealthManager (15-160)
packages/services/src/worker/ReportManager.ts (1)
packages/services/src/worker/LocalWorker.ts (1)
  • LocalWorker (30-287)
packages/services/test/worker/fixtures/localWorkers.fixture.ts (1)
packages/services/src/worker/LocalWorker.ts (1)
  • LocalWorker (30-287)
packages/http/src/HttpRemote.ts (3)
packages/services/src/worker/RemoteWorker.ts (4)
  • id (39-39)
  • id (41-41)
  • state (43-43)
  • state (45-45)
packages/runtime/src/server/Server.ts (1)
  • state (324-334)
packages/services/src/index.ts (1)
  • State (5-5)
packages/services/test/gateway/fixtures/healthManager.fixture.ts (2)
packages/health/src/HealthManager.ts (1)
  • HealthManager (15-160)
packages/services/test/gateway/fixtures/sourcingManager.fixture.ts (1)
  • sourcingManager (4-4)
packages/services/test/gateway/fixtures/localGateways.fixture.ts (2)
packages/services/src/gateway/LocalGateway.ts (4)
  • url (43-43)
  • trustKey (47-47)
  • trustKey (144-147)
  • LocalGateway (24-148)
packages/services/test/gateway/fixtures/values.fixture.ts (1)
  • VALUES (2-8)
packages/services/src/common/ReportedStateManager.ts (2)
packages/services/src/common/StateManager.ts (3)
  • StateManager (5-64)
  • state (9-9)
  • state (11-11)
packages/services/src/common/definitions/States.ts (1)
  • State (15-15)
packages/services/src/gateway/WorkerManager.ts (5)
packages/services/src/worker/LocalWorker.ts (4)
  • id (60-60)
  • id (62-62)
  • state (64-64)
  • state (66-66)
packages/services/src/worker/RemoteWorker.ts (4)
  • id (39-39)
  • id (41-41)
  • state (43-43)
  • state (45-45)
packages/services/src/common/StateManager.ts (2)
  • state (9-9)
  • state (11-11)
packages/services/src/common/definitions/States.ts (1)
  • State (15-15)
packages/services/src/gateway/WorkerMonitor.ts (1)
  • worker (44-52)
packages/services/src/proxy/LocalProxy.ts (2)
packages/services/src/common/StateManager.ts (1)
  • StateManager (5-64)
packages/services/src/common/definitions/States.ts (1)
  • State (15-15)
packages/runtime/src/server/Server.ts (3)
packages/services/src/worker/RemoteWorkerBuilder.ts (1)
  • RemoteWorkerBuilder (5-27)
packages/services/src/gateway/LocalGateway.ts (2)
  • state (45-45)
  • LocalGateway (24-148)
packages/services/src/common/definitions/States.ts (1)
  • State (15-15)
🔇 Additional comments (73)
packages/health/src/definitions/States.ts (1)

2-8: Same constant defined in at least two packages – centralise to remove duplication.

States is copy-pasted here and in packages/middleware/.... Duplicates invite drift (and already did – see previous comment).
Consider publishing one source of truth (e.g. @jitar/core-states) and re-exporting from the consuming packages.

[ suggest_optional_refactor ]

packages/services/package.json (1)

21-21: Wildcard dependency on @jitar/health jeopardises reproducible builds.

Using "*" means any future breaking change in @jitar/health can silently break services. Pin with a caret or exact version after verifying compatibility, e.g.:

-    "@jitar/health": "*",
+    "@jitar/health": "^0.7.0",

Also consider enabling Renovate/Dependabot to automate upgrades with CI safety nets.

packages/middleware/src/index.ts (1)

2-2: LGTM: Well-structured export statement.

The export statement correctly follows TypeScript conventions by exporting both the default export as States and the type export for State. This provides consumers with access to both the state constants and the type definition, which is consistent with the state management pattern implemented across packages.

packages/health/src/index.ts (1)

2-2: LGTM: Consistent export pattern.

The export statement follows the same pattern as other packages in the codebase, providing both the default export as States and the type export for State. This consistency across packages helps maintain a uniform API for state management.

packages/services/src/worker/Worker.ts (2)

3-3: LGTM: Appropriate import for state management.

The import of State type from the common definitions is correctly placed and necessary for the interface extension.


11-11: LGTM: Well-designed interface extension.

The addition of the state setter to the Worker interface is well-designed. Based on the relevant code snippets, different worker implementations handle state setting differently:

  • LocalWorker sets state directly: this.#stateManager.state = state
  • RemoteWorker reports state: this.#stateManager.report(state)

This interface design allows for implementation-specific state management strategies while maintaining a consistent API.

packages/services/test/worker/fixtures/localWorkers.fixture.ts (2)

5-5: LGTM: Appropriate fixture dependency.

The import of healthManager from the fixture file is correct and necessary to support the new LocalWorker constructor requirements.


11-12: LGTM: Consistent dependency injection.

The addition of healthManager to both LocalWorker constructor calls is consistent and correct. This ensures that both the public and protected worker instances have the necessary health management capabilities for the new state management system.

packages/services/test/gateway/fixtures/remoteWorkers.fixture.ts (1)

3-3: Import of States is valid – States.ts uses export default States. No changes needed.

packages/configuration/src/server/index.ts (1)

7-7: LGTM – new export is correctly wired.

No issues found; keeps public API in sync with new configuration type.

documentation/docs/deploy/health-checks.md (1)

16-16: Good terminology clarification!

The change from "health" to "availability status" better reflects the architectural shift where health checks provide input data for availability determination, rather than being the availability itself. This aligns well with the new state management system introduced in this PR.

packages/configuration/src/server/definitions/GatewayConfiguration.ts (2)

6-6: Good naming improvement with proper breaking change handling.

The rename from monitor to monitorInterval significantly improves clarity about what this configuration property controls. The change is consistently applied to both the type definition and validation scheme.


14-14: Validation scheme correctly updated.

The validation scheme is properly updated to match the renamed property, maintaining consistency between the type definition and validation rules.

packages/services/test/gateway/fixtures/healthManager.fixture.ts (1)

1-6: Well-structured test fixture!

The fixture follows the established pattern for test fixtures, properly importing dependencies and creating a reusable HealthManager instance. The implementation is clean and focused on its single responsibility.

packages/services/test/gateway/fixtures/localGateways.fixture.ts (2)

4-4: Proper integration of healthManager dependency.

The import of healthManager from the new fixture file is clean and follows the established pattern for test fixtures.


10-11: Consistent healthManager integration across gateway instances.

Both public and protected gateway instances now properly receive the healthManager dependency, maintaining consistency with the updated LocalGateway constructor requirements.

packages/services/src/Service.ts (3)

2-2: Appropriate import for state management.

The import of State type from the common definitions is properly scoped and supports the new state management functionality.


8-8: Well-designed state property addition.

The readonly state property provides a clean way to access the current service state without allowing external mutation. This is a good design pattern for state management.


18-18: Proper async state update method.

The updateState() method returning Promise<State> is well-designed for asynchronous state updates. This allows services to refresh their state based on health checks or other factors and return the updated state.

packages/services/test/repository/fixtures/healthManager.fixture.ts (1)

1-6: LGTM! Clean fixture implementation.

The fixture correctly instantiates HealthManager with the required sourcingManager dependency, following the established fixture pattern in the codebase.

packages/services/src/common/Remote.ts (2)

5-5: Good addition of State type import.

The import is correctly placed and necessary for the new reportWorker method signature.


21-21: LGTM! Worker state reporting method added.

The reportWorker method signature is consistent with the interface pattern and correctly accepts worker ID and state parameters for the new push-based health monitoring system.

packages/services/test/repository/fixtures/localRepositories.fixture.ts (2)

4-4: Good integration of healthManager dependency.

The import correctly adds the required healthManager fixture for the LocalRepository constructor updates.


12-13: LGTM! Constructor calls updated with healthManager.

Both repository instances now correctly receive the healthManager parameter, maintaining consistency with the new LocalRepository constructor signature.

packages/configuration/src/server/definitions/WorkerConfiguration.ts (2)

9-9: Good addition of reportInterval configuration property.

The optional reportInterval property correctly supports the new worker state reporting feature with proper typing.


19-19: LGTM! Validation scheme updated correctly.

The validation scheme properly defines reportInterval as an optional integer, maintaining consistency with the type definition.

packages/services/test/worker/fixtures/healthManager.fixture.ts (1)

1-6: LGTM! Consistent fixture implementation for worker tests.

The fixture correctly creates a HealthManager instance for worker tests, maintaining consistency with the repository fixture pattern while providing proper test isolation.

packages/services/test/gateway/fixtures/sourcingManager.fixture.ts (1)

1-5: LGTM! Clean fixture implementation.

The fixture follows established patterns and provides a proper LocalSourcingManager instance for testing. The use of './' as the location parameter is appropriate for test contexts.

packages/services/test/worker/fixtures/executionManager.fixture.ts (1)

5-7: LGTM! Proper dependency injection.

The addition of sourcingManager parameter to the ExecutionManager constructor is correct and aligns with the constructor signature requirements. The import and usage are properly implemented.

packages/services/src/dummy/DummyProvider.ts (3)

6-7: LGTM! Proper imports for state management.

The imports for States and State type are correctly added to support the new state management functionality.


16-19: LGTM! Appropriate state getter implementation.

The state getter returning States.AVAILABLE is appropriate for a dummy provider implementation that should always report as available.


41-44: LGTM! Consistent updateState implementation.

The updateState method returning States.AVAILABLE is consistent with the state getter and appropriate for a dummy provider that maintains a constant available state.

packages/configuration/src/server/definitions/ServerConfiguration.ts (3)

9-9: LGTM! Proper import for new configuration type.

The import of RemoteWorkerConfiguration and its validation scheme is correctly added to support the new remote worker configuration feature.


24-24: LGTM! Consistent optional configuration property.

The addition of remoteWorker?: RemoteWorkerConfiguration follows the same pattern as other optional service configurations in the type definition.


41-42: LGTM! Proper validation scheme update.

The validation scheme is correctly updated to include the new remoteWorker field with proper group validation using the imported remoteWorkerValidationScheme.

packages/configuration/test/server/fixtures/configuration.fixture.ts (4)

2-2: LGTM! Proper import update.

The import statement is correctly updated to include the new RemoteWorkerConfiguration type along with existing configuration types.


12-12: LGTM! Consistent property renaming.

The renaming from monitor to monitorInterval aligns with the broader configuration updates mentioned in the AI summary and maintains consistency across the codebase.


17-17: LGTM! Appropriate test configuration values.

The remoteWorkerConfiguration constant with unavailableThreshold: 6000 and stoppedThreshold: 18000 provides reasonable test values for the new remote worker monitoring thresholds.


31-32: LGTM! Proper configuration extension.

The SERVER_CONFIGURATION is correctly extended to include the new remoteWorker configuration, completing the integration of the new remote worker configuration feature.

packages/services/src/gateway/Gateway.ts (1)

10-12: LGTM! Interface changes align with push-based state management.

The updated interface correctly reflects the shift to ID-based worker management and adds the necessary reportWorker method for state reporting. The changes are consistent with the broader architecture updates.

packages/services/src/dummy/DummyRunner.ts (2)

16-19: LGTM! Appropriate dummy implementation.

The dummy implementation correctly returns a constant AVAILABLE state, which is suitable for testing scenarios where predictable behavior is needed.


46-49: LGTM! Consistent with state getter implementation.

The updateState method appropriately returns the same constant state as the getter, maintaining consistency in the dummy implementation.

packages/http/src/HttpRemote.ts (1)

107-119: LGTM! Well-implemented HTTP state reporting.

The implementation follows established patterns in the class:

  • Uses the #callRemote helper for consistent error handling
  • Proper JSON serialization of the state
  • Correct HTTP method and content-type headers
  • Endpoint structure is consistent with other worker operations
packages/services/src/worker/RemoteWorkerBuilder.ts (1)

18-26: LGTM! Clean builder implementation.

The build method is well-structured:

  • Proper delegation to RemoteBuilder
  • Efficient conversion of procedures array to Set
  • Clean parameter passing to RemoteWorker constructor
packages/http/src/HttpServer.ts (2)

66-66: LGTM: Route registration follows established pattern.

The new route is properly registered alongside other worker-related endpoints in the #setupRoutes method.


193-223: LGTM: Implementation follows established patterns.

The #reportWorker method correctly follows the same validation, error handling, and response transformation patterns used by other methods in the class.

packages/runtime/src/client/ClientBuilder.ts (2)

4-4: LGTM: Import added for health management integration.

The HealthManager import is properly added to support the new health management functionality.


34-34: LGTM: Health manager integration follows established pattern.

The implementation correctly follows the same pattern as other builder methods:

  • Creates the health manager using the sourcing manager
  • Passes it to the Client constructor
  • Maintains consistent method naming and structure

Also applies to: 38-38, 41-44

packages/services/src/common/definitions/States.ts (1)

2-15: LGTM: Well-structured state definition following TypeScript best practices.

The implementation correctly uses:

  • as const assertion to ensure literal types
  • Descriptive state names covering the full lifecycle
  • Standard export pattern with default and named exports
  • Proper TypeScript type derivation for Keys and State
packages/services/src/gateway/WorkerManager.ts (3)

4-4: LGTM: State type import added for worker state management.

The State type import is properly added to support the new worker state reporting functionality.


68-73: LGTM: Worker state reporting method correctly implemented.

The reportWorker method properly:

  • Uses the existing getWorker method for ID validation and retrieval
  • Sets the worker's state, which triggers internal state manager updates
  • Follows the established error handling pattern (throws UnknownWorker for invalid IDs)

75-94: LGTM: Worker removal by ID is properly implemented.

The updated removeWorker method correctly:

  • Changes signature to accept ID string instead of Worker instance
  • Returns the removed Worker object for caller use
  • Uses existing getWorker method for validation and retrieval
  • Maintains the same cleanup logic for balancers

This change aligns with the ID-based worker management approach shown in the WorkerMonitor usage.

packages/configuration/src/server/definitions/RemoteWorkerConfiguration.ts (1)

1-19: LGTM! Clean configuration type definition.

The type definition and validation scheme are well-structured and consistent. Good use of as const for the validation scheme.

packages/services/src/common/ReportedStateManager.ts (2)

26-47: Discard thread-safety concern for report() and update()

JavaScript’s single-threaded event loop means there are no simultaneous in-method executions—report() and update() cannot truly run concurrently. If you need specific ordering between them in async flows, enforce it at the call site (e.g. via await or chaining), but no additional locking or synchronization is required here.

Likely an incorrect or invalid review comment.


33-47: Fix incorrect interval calculation in update() method.

The current interval calculation this.#lastUpdate - this.#lastReport doesn't represent the time since the last report. This will cause incorrect state transitions.

 update(): State
 {
-    this.#lastUpdate = Date.now();
+    const now = Date.now();
+    const interval = now - this.#lastReport;
 
-    const interval = this.#lastUpdate - this.#lastReport;
-
     if (interval >= this.#unavailableThreshold)
     {
         this.state = interval >= this.#stoppedThreshold
             ? States.STOPPED
             : States.UNAVAILABLE;
     }
 
     return this.state;
 }

Likely an incorrect or invalid review comment.

packages/services/src/index.ts (1)

2-6: LGTM! Export reorganization looks good.

The exports are properly organized and follow the established patterns. Good adherence to the LocalProxy naming convention to avoid shadowing the built-in Proxy.

Also applies to: 22-22

packages/services/test/gateway/fixtures/remotes.fixture.ts (1)

6-7: Good integration of state management

The import path updates and the addition of the reportWorker method properly align with the new state management architecture.

Also applies to: 43-47

packages/runtime/src/client/Client.ts (2)

45-72: Clean integration of health management and request pooling

The changes properly integrate the HealthManager and RequestPool into the Client lifecycle. The async modifications to start(), stop(), and runInternal() methods align well with the new architecture.


24-24: Verify Client implements the Runner interface

Please ensure that the Client class you’re passing into new RequestPool(this) satisfies the Runner interface imported from @jitar/execution. In particular:

  • Confirm the exact method signatures of Runner (e.g., return types for start(), stop(), and run(request)).
  • Verify that Client defines each required method with matching names and types:
    • start(): …
    • stop(): …
    • run(request: Request): Promise<Response>
  • If there’s a mismatch (for example, Client.start() returning Promise<void> vs. void), adjust either the interface implementation or the Client methods accordingly so TypeScript enforces the correct contract.
packages/services/src/common/StateManager.ts (1)

5-64: Well-structured state management implementation

The StateManager class provides a clean and focused implementation for lifecycle state management. The state transition methods are clearly named, and the helper methods provide useful abstractions for state checking.

packages/health/src/HealthManager.ts (1)

33-43: Excellent state management integration

The addition of state checks and transitions in the start() and stop() methods prevents redundant operations and provides clear lifecycle management. The pattern of checking current state, transitioning through intermediate states, and setting final states is well implemented.

Also applies to: 47-57

packages/services/src/gateway/WorkerMonitor.ts (1)

3-3: Clean refactoring to state-based monitoring

The refactoring from frequency-based health checks to state-based monitoring aligns well with the new architecture. The naming changes from "frequency" to "interval" improve clarity.

Also applies to: 7-7, 12-12, 16-16, 19-19, 26-26, 31-31, 36-36

packages/services/src/gateway/RemoteGateway.ts (2)

98-101: LGTM! Clean delegation pattern for worker state reporting.

The new reportWorker method properly delegates to the remote service.


103-106: removeWorker signature change is safe to merge

All call sites across the repo have been updated to use a string id, and there are no remaining invocations that pass a Worker object. No further action is needed.

packages/runtime/src/server/Server.ts (1)

196-218: LGTM! Well-structured worker reporting implementation.

The new reportWorker method correctly validates the state and delegates to the gateway. The error handling and logging are appropriate.

packages/services/src/gateway/LocalGateway.ts (2)

49-64: Well-implemented lifecycle management with proper state transitions.

The start method correctly:

  • Guards against redundant starts
  • Sets appropriate state transitions
  • Starts dependencies in parallel for efficiency
  • Updates availability state based on health

117-127: LGTM! Clean separation of concerns for worker management.

The worker reporting and removal methods properly delegate to the WorkerManager and ensure proper cleanup by stopping the worker after removal.

packages/services/src/repository/LocalRepository.ts (1)

50-93: Consistent implementation of state and health management.

The LocalRepository correctly implements the same lifecycle and health management pattern as other services, ensuring consistency across the codebase.

packages/services/src/worker/LocalWorker.ts (3)

72-99: Excellent lifecycle management with proper sequencing.

The start method correctly:

  • Guards against redundant starts
  • Starts core services in parallel
  • Properly sequences gateway registration before starting the report manager
  • Updates availability state based on health

101-128: Proper cleanup sequence prevents race conditions.

The stop method correctly stops the ReportManager before removing the worker from the gateway, preventing potential race conditions where reports might be sent after deregistration.


157-165: Safe implementation of gateway reporting.

The method properly guards against missing gateway or worker ID, making it safe to call in all scenarios.

packages/runtime/src/server/ServerBuilder.ts (2)

25-42: Clean integration of health management across all services.

The build method correctly creates the HealthManager early and consistently passes it to all local services, ensuring uniform health monitoring capabilities.


167-173: LGTM! Proper handling of optional configuration values.

The method correctly extracts the optional threshold values from the configuration and creates the RemoteWorkerBuilder instance.

Comment thread packages/health/src/definitions/States.ts
Comment thread packages/runtime/src/server/types/ReportWorkerRequest.ts
Comment thread packages/services/src/gateway/WorkerBalancer.ts Outdated
Comment thread packages/services/src/worker/ReportManager.ts Outdated
Comment thread packages/services/src/worker/ReportManager.ts Outdated
Comment thread packages/services/src/proxy/LocalProxy.ts
Comment thread packages/services/src/proxy/LocalProxy.ts
Comment thread documentation/docs/fundamentals/runtime-services.md Outdated
Comment thread packages/services/src/gateway/RemoteGateway.ts
Comment thread packages/runtime/src/server/Server.ts
Copy link
Copy Markdown

@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: 3

🧹 Nitpick comments (4)
packages/scheduling/test/dummy.spec.ts (1)

6-6: Address the TODO comment for comprehensive test coverage.

Consider adding actual tests for the scheduling functionality to ensure the ScheduleManager and ScheduledTask classes work correctly.

Would you like me to help generate unit tests for the scheduling package functionality?

packages/runtime/src/client/ClientBuilder.ts (1)

34-34: Consider making the log level configurable.

The logger is hardcoded to use WARN level. Consider making this configurable through the ClientConfiguration to allow different logging levels for different environments.

type ClientConfiguration =
{
    remoteUrl: string;
    middleware?: Middleware[];
    segments?: Segment[];
+   logLevel?: LogLevels;
};
-        const logger = new Logger(LogLevels.WARN);
+        const logger = new Logger(configuration.logLevel ?? LogLevels.WARN);
packages/services/src/gateway/WorkerManager.ts (1)

145-160: Consider error handling in the monitoring logic.

The monitoring methods look well-structured, but consider adding error handling for the worker state updates, especially if updateState() or removeWorker() can throw exceptions.

    async #checkWorker(worker: Worker): Promise<void>
    {
+       try
+       {
            const state = await worker.updateState();
            
            if (state === States.STOPPED)
            {
                this.removeWorker(worker.id as string);
            }
+       }
+       catch (error)
+       {
+           // Log error but continue monitoring other workers
+           console.warn(`Failed to check worker ${worker.id}:`, error);
+       }
    }
packages/services/src/common/StateManager.ts (1)

36-57: Consider the error handling in stop method.

The stop method sets the state to UNAVAILABLE on error, which may not be semantically correct. If stopping fails, the service might still be running but in an unknown state.

Consider keeping the state as STOPPING on error or adding a new ERROR state to better represent the failure condition:

        catch (error: unknown)
        {
-           this.setUnavailable();
+           // Keep as STOPPING to indicate incomplete shutdown
+           // this.setStopping();
+           // Or consider adding an ERROR state
            
            throw error;
        }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between db15376 and 4de96bd.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (42)
  • documentation/docs/fundamentals/runtime-services.md (5 hunks)
  • packages/health/src/HealthManager.ts (2 hunks)
  • packages/middleware/src/MiddlewareManager.ts (1 hunks)
  • packages/runtime/package.json (1 hunks)
  • packages/runtime/src/client/Client.ts (4 hunks)
  • packages/runtime/src/client/ClientBuilder.ts (3 hunks)
  • packages/runtime/src/server/ServerBuilder.ts (5 hunks)
  • packages/scheduling/CHANGELOG.md (1 hunks)
  • packages/scheduling/README.md (1 hunks)
  • packages/scheduling/package.json (1 hunks)
  • packages/scheduling/src/ScheduleManager.ts (1 hunks)
  • packages/scheduling/src/ScheduledTask.ts (1 hunks)
  • packages/scheduling/src/index.ts (1 hunks)
  • packages/scheduling/src/types/Task.ts (1 hunks)
  • packages/scheduling/test/dummy.spec.ts (1 hunks)
  • packages/scheduling/tsconfig.json (1 hunks)
  • packages/scheduling/vite.config.ts (1 hunks)
  • packages/services/package.json (1 hunks)
  • packages/services/src/common/RequestPool.ts (1 hunks)
  • packages/services/src/common/StateManager.ts (1 hunks)
  • packages/services/src/common/errors/RequestCancelled.ts (1 hunks)
  • packages/services/src/gateway/LocalGateway.ts (3 hunks)
  • packages/services/src/gateway/RemoteGateway.ts (5 hunks)
  • packages/services/src/gateway/WorkerBalancer.ts (1 hunks)
  • packages/services/src/gateway/WorkerManager.ts (6 hunks)
  • packages/services/src/gateway/WorkerMonitor.ts (0 hunks)
  • packages/services/src/index.ts (2 hunks)
  • packages/services/src/proxy/LocalProxy.ts (4 hunks)
  • packages/services/src/repository/LocalRepository.ts (3 hunks)
  • packages/services/src/repository/RemoteRepository.ts (4 hunks)
  • packages/services/src/worker/LocalWorker.ts (6 hunks)
  • packages/services/src/worker/RemoteWorker.ts (3 hunks)
  • packages/services/src/worker/Worker.ts (1 hunks)
  • packages/services/test/gateway/WorkerMonitor.spec.ts (0 hunks)
  • packages/services/test/gateway/fixtures/index.ts (0 hunks)
  • packages/services/test/gateway/fixtures/localGateways.fixture.ts (1 hunks)
  • packages/services/test/gateway/fixtures/remoteWorkers.fixture.ts (2 hunks)
  • packages/services/test/gateway/fixtures/scheduleManager.fixture.ts (1 hunks)
  • packages/services/test/gateway/fixtures/workerManagers.fixture.ts (1 hunks)
  • packages/services/test/gateway/fixtures/workerMonitors.fixture.ts (0 hunks)
  • packages/services/test/worker/fixtures/localWorkers.fixture.ts (1 hunks)
  • packages/services/test/worker/fixtures/scheduleManager.fixture.ts (1 hunks)
💤 Files with no reviewable changes (4)
  • packages/services/test/gateway/fixtures/index.ts
  • packages/services/test/gateway/WorkerMonitor.spec.ts
  • packages/services/test/gateway/fixtures/workerMonitors.fixture.ts
  • packages/services/src/gateway/WorkerMonitor.ts
✅ Files skipped from review due to trivial changes (11)
  • packages/scheduling/CHANGELOG.md
  • packages/services/src/common/errors/RequestCancelled.ts
  • packages/runtime/package.json
  • packages/services/test/worker/fixtures/scheduleManager.fixture.ts
  • packages/scheduling/src/types/Task.ts
  • packages/scheduling/src/index.ts
  • packages/scheduling/vite.config.ts
  • packages/scheduling/README.md
  • packages/scheduling/package.json
  • packages/scheduling/tsconfig.json
  • packages/services/test/gateway/fixtures/scheduleManager.fixture.ts
🚧 Files skipped from review as they are similar to previous changes (16)
  • packages/services/package.json
  • packages/services/test/worker/fixtures/localWorkers.fixture.ts
  • packages/services/test/gateway/fixtures/localGateways.fixture.ts
  • packages/services/test/gateway/fixtures/remoteWorkers.fixture.ts
  • packages/services/src/gateway/WorkerBalancer.ts
  • packages/services/src/repository/RemoteRepository.ts
  • packages/middleware/src/MiddlewareManager.ts
  • packages/services/src/worker/RemoteWorker.ts
  • packages/services/src/index.ts
  • documentation/docs/fundamentals/runtime-services.md
  • packages/health/src/HealthManager.ts
  • packages/runtime/src/client/Client.ts
  • packages/services/src/common/RequestPool.ts
  • packages/services/src/proxy/LocalProxy.ts
  • packages/services/src/repository/LocalRepository.ts
  • packages/services/src/gateway/RemoteGateway.ts
🧰 Additional context used
🧠 Learnings (6)
📓 Common learnings
Learnt from: petermasking
PR: MaskingTechnology/jitar#667
File: packages/health/src/definitions/States.ts:2-8
Timestamp: 2025-07-14T13:50:01.152Z
Learning: In the Jitar codebase, there are different state enums for different purposes:
- Health manager states (packages/health/src/definitions/States.ts) track health check initialization: STARTING, STARTED, STOPPING, STOPPED
- Service states (packages/services/src/common/definitions/States.ts) track service availability: STARTING, AVAILABLE, UNAVAILABLE, STOPPING, STOPPED
- The health manager's STARTED state indicates health checks are loaded/initialized, not that the service is available
- Service availability is determined by the service layer based on health check results, not by the health manager's state
packages/services/src/worker/Worker.ts (1)
Learnt from: petermasking
PR: MaskingTechnology/jitar#667
File: packages/health/src/definitions/States.ts:2-8
Timestamp: 2025-07-14T13:50:01.152Z
Learning: In the Jitar codebase, there are different state enums for different purposes:
- Health manager states (packages/health/src/definitions/States.ts) track health check initialization: STARTING, STARTED, STOPPING, STOPPED
- Service states (packages/services/src/common/definitions/States.ts) track service availability: STARTING, AVAILABLE, UNAVAILABLE, STOPPING, STOPPED
- The health manager's STARTED state indicates health checks are loaded/initialized, not that the service is available
- Service availability is determined by the service layer based on health check results, not by the health manager's state
packages/services/src/common/StateManager.ts (1)
Learnt from: petermasking
PR: MaskingTechnology/jitar#667
File: packages/health/src/definitions/States.ts:2-8
Timestamp: 2025-07-14T13:50:01.152Z
Learning: In the Jitar codebase, there are different state enums for different purposes:
- Health manager states (packages/health/src/definitions/States.ts) track health check initialization: STARTING, STARTED, STOPPING, STOPPED
- Service states (packages/services/src/common/definitions/States.ts) track service availability: STARTING, AVAILABLE, UNAVAILABLE, STOPPING, STOPPED
- The health manager's STARTED state indicates health checks are loaded/initialized, not that the service is available
- Service availability is determined by the service layer based on health check results, not by the health manager's state
packages/services/src/worker/LocalWorker.ts (1)
Learnt from: petermasking
PR: MaskingTechnology/jitar#667
File: packages/health/src/definitions/States.ts:2-8
Timestamp: 2025-07-14T13:50:01.152Z
Learning: In the Jitar codebase, there are different state enums for different purposes:
- Health manager states (packages/health/src/definitions/States.ts) track health check initialization: STARTING, STARTED, STOPPING, STOPPED
- Service states (packages/services/src/common/definitions/States.ts) track service availability: STARTING, AVAILABLE, UNAVAILABLE, STOPPING, STOPPED
- The health manager's STARTED state indicates health checks are loaded/initialized, not that the service is available
- Service availability is determined by the service layer based on health check results, not by the health manager's state
packages/services/src/gateway/LocalGateway.ts (1)
Learnt from: petermasking
PR: MaskingTechnology/jitar#667
File: packages/health/src/definitions/States.ts:2-8
Timestamp: 2025-07-14T13:50:01.152Z
Learning: In the Jitar codebase, there are different state enums for different purposes:
- Health manager states (packages/health/src/definitions/States.ts) track health check initialization: STARTING, STARTED, STOPPING, STOPPED
- Service states (packages/services/src/common/definitions/States.ts) track service availability: STARTING, AVAILABLE, UNAVAILABLE, STOPPING, STOPPED
- The health manager's STARTED state indicates health checks are loaded/initialized, not that the service is available
- Service availability is determined by the service layer based on health check results, not by the health manager's state
packages/runtime/src/server/ServerBuilder.ts (2)
Learnt from: petermasking
PR: MaskingTechnology/jitar#667
File: packages/health/src/definitions/States.ts:2-8
Timestamp: 2025-07-14T13:50:01.152Z
Learning: In the Jitar codebase, there are different state enums for different purposes:
- Health manager states (packages/health/src/definitions/States.ts) track health check initialization: STARTING, STARTED, STOPPING, STOPPED
- Service states (packages/services/src/common/definitions/States.ts) track service availability: STARTING, AVAILABLE, UNAVAILABLE, STOPPING, STOPPED
- The health manager's STARTED state indicates health checks are loaded/initialized, not that the service is available
- Service availability is determined by the service layer based on health check results, not by the health manager's state
Learnt from: basmasking
PR: MaskingTechnology/jitar#638
File: packages/runtime/src/server/ServerBuilder.ts:7-8
Timestamp: 2025-05-13T18:15:31.425Z
Learning: In the Jitar codebase, always import the `Proxy` class from `@jitar/services` as `LocalProxy` to avoid shadowing the built-in JavaScript `Proxy` global object.
🧬 Code Graph Analysis (3)
packages/scheduling/src/ScheduledTask.ts (1)
packages/logging/src/Logger.ts (1)
  • Logger (5-125)
packages/services/test/gateway/fixtures/workerManagers.fixture.ts (3)
packages/services/src/gateway/WorkerManager.ts (1)
  • WorkerManager (13-161)
packages/services/test/gateway/fixtures/scheduleManager.fixture.ts (1)
  • scheduleManager (5-5)
packages/services/test/gateway/fixtures/remoteWorkers.fixture.ts (1)
  • REMOTE_WORKERS (47-56)
packages/scheduling/src/ScheduleManager.ts (2)
packages/scheduling/src/ScheduledTask.ts (1)
  • ScheduledTask (8-67)
packages/logging/src/Logger.ts (1)
  • Logger (5-125)
🔇 Additional comments (44)
packages/services/src/worker/Worker.ts (1)

11-13: Well-designed interface extension for state management.

The new methods isAvailable() and reportState() align perfectly with the PR objectives of enabling push-based state reporting. The method signatures are appropriate and the State type import ensures type safety.

packages/services/test/gateway/fixtures/workerManagers.fixture.ts (1)

5-9: Correctly updated fixture to match new WorkerManager constructor.

The changes properly integrate the scheduleManager dependency required by the updated WorkerManager constructor, ensuring tests continue to work with the new scheduling functionality.

packages/scheduling/src/ScheduledTask.ts (2)

40-54: Excellent recursive scheduling approach.

The use of setTimeout with recursive scheduling is a good design choice that prevents overlapping task executions and provides better control over timing compared to setInterval.


56-66: Proper error handling implementation.

The error handling in #executeTask correctly catches exceptions and logs them without interrupting the scheduling cycle, which is essential for maintaining system reliability.

packages/scheduling/src/ScheduleManager.ts (3)

19-26: Well-designed task creation method.

The create method properly instantiates ScheduledTask with the shared logger and adds it to the collection. The pattern of returning the created task enables fluent usage.


28-38: Robust task removal implementation.

The remove method correctly handles the case where the task doesn't exist by checking the index before removal. This prevents errors and maintains collection integrity.


40-48: Efficient bulk operations for lifecycle management.

The startAll and stopAll methods provide convenient bulk operations for managing all scheduled tasks, which is essential for coordinated lifecycle management.

packages/runtime/src/client/ClientBuilder.ts (4)

4-7: LGTM! Clean integration of new dependencies.

The imports are properly organized and the new dependencies (HealthManager, Logger, LogLevels, ScheduleManager) are correctly imported from their respective packages.


38-41: Good refactoring of manager creation order.

The managers are created in the correct dependency order, and the schedule manager is appropriately created after the sourcing manager setup.


69-72: LGTM! Clean implementation of schedule manager builder.

The new private method follows the same pattern as other builder methods and correctly instantiates the ScheduleManager with the provided logger.


43-43: No positional parameters—order check unnecessary

The Client constructor accepts a single Configuration object (not six positional args), so passing

new Client({ remoteUrl, remote, healthManager, middlewareManager, executionManager, scheduleManager });

is correct and property order is irrelevant.

Likely an incorrect or invalid review comment.

packages/services/src/gateway/WorkerManager.ts (5)

3-6: LGTM! Clean import organization.

The imports are properly organized and include all necessary types for the new scheduling and state management functionality.


19-24: Good integration with ScheduleManager.

The constructor properly initializes the monitoring task with the provided schedule manager and interval. The task creation follows the expected pattern.


33-41: LGTM! Clear lifecycle management methods.

The start/stop methods provide clear control over the monitoring task lifecycle, which is essential for proper resource management.


86-91: Good addition of state reporting functionality.

The reportWorker method properly retrieves the worker and updates its state, which is essential for the new push-based monitoring system.


93-112: removeWorker return type change is internal and non-breaking

The signature change from void to Worker only affects WorkerManager and is consumed by LocalGateway, which still returns Promise<void>. All external callers invoke Gateway.removeWorker and remain unaffected.

packages/services/src/common/StateManager.ts (5)

5-5: LGTM! Clean type definition.

The Task type clearly defines the expected signature for async operations used in start/stop methods.


15-34: Good implementation of start method with proper error handling.

The start method correctly prevents multiple starts and handles errors by reverting to STOPPED state. The early return for already started services is a good optimization.


59-62: Good implementation of isStarted method.

The method correctly identifies a service as started when it's not in STOPPED state, which aligns with the service lifecycle.


89-94: LGTM! Useful utility method.

The setAvailability method provides a clean way to set availability based on a boolean condition and returns the new state for convenience.


106-114: Clean implementation of state checking helpers.

The private helper methods provide a clean abstraction for state checking operations and follow the single responsibility principle.

packages/services/src/gateway/LocalGateway.ts (7)

4-7: LGTM! Clean import organization.

The imports are properly organized and include all necessary types for the new state management functionality.


19-21: Good dependency injection refactoring.

The configuration now requires healthManager and workerManager instances, which promotes better testability and follows dependency injection principles.


30-42: Clean state management integration.

The StateManager is properly initialized and the state getter provides clean access to the current gateway state.


48-57: Good coordinated start sequence.

The start method properly coordinates starting both health and worker managers concurrently, followed by state updates. Using Promise.all for concurrent starts is efficient.


80-85: LGTM! Clean state update logic.

The updateState method properly determines availability based on health status and updates the state manager accordingly.


94-96: Good integration with worker lifecycle.

Starting the worker before adding it to the manager ensures proper initialization order.


104-114: Clean separation of worker reporting and removal.

The split of functionality into reportWorker for state updates and removeWorker for lifecycle management is a good architectural decision that aligns with the new push-based system.

packages/services/src/worker/LocalWorker.ts (8)

3-8: LGTM! Clean import organization.

The imports are properly organized and include all necessary types for the new state management, health monitoring, and scheduling functionality.


25-44: Good dependency injection and task setup.

The constructor properly accepts the new dependencies and sets up the scheduled reporting task with the provided interval. The StateManager initialization is consistent with other components.


67-67: LGTM! Clean state access.

The state getter provides clean access to the current worker state from the StateManager.


75-96: Good coordinated start sequence.

The start method properly coordinates starting execution and health managers, handles gateway registration, and starts the reporting task. The sequential operations are well-structured.


100-119: Clean stop sequence with proper cleanup.

The stop method properly stops the reporting task, handles gateway deregistration, and stops the managers in the correct order. The cleanup sequence is well-designed.


131-144: Good health method delegation.

The health-related methods properly delegate to the HealthManager, maintaining clean separation of concerns.


146-161: LGTM! Clean state management methods.

The updateState and reportState methods provide clean interfaces for state management and reporting. The guard clauses in reportState prevent unnecessary operations.


284-289: Good implementation of scheduled reporting.

The private #report method cleanly orchestrates the state update and reporting cycle for the scheduled task.

packages/runtime/src/server/ServerBuilder.ts (8)

7-8: LGTM: Clean integration of new dependencies.

The import statements correctly add the required ScheduleManager and new service components. The LocalProxy import follows the established pattern to avoid shadowing the built-in JavaScript Proxy object.


35-37: LGTM: Well-structured manager initialization.

The early initialization of both managers follows good practices and ensures they're available for all service builders. The dependency injection pattern is cleanly implemented.


42-44: LGTM: Proper integration of RemoteWorkerBuilder.

The extraction of the remote worker builder construction into a separate method and its integration into the Server constructor is well-structured and maintains clean separation of concerns.


47-53: LGTM: Consistent manager propagation across service builders.

The systematic passing of both managers to all relevant service builders (except repository which only needs health manager) is consistent and aligns with the new state management architecture.


85-88: LGTM: Proper configuration property migration and WorkerManager integration.

The rename from monitor to monitorInterval maintains backward compatibility expectations, and the WorkerManager construction with both scheduleManager and monitorInterval correctly implements the push-based worker monitoring system described in the PR objectives.


102-106: LGTM: Comprehensive worker configuration integration.

The addition of reportInterval configuration and passing of both managers to the LocalWorker constructor properly implements the worker state reporting mechanism. The systematic integration maintains consistency with the existing codebase patterns.


171-174: LGTM: Simple and correct ScheduleManager factory method.

The #buildScheduleManager method follows the established pattern used by other manager builders in the class and correctly passes the logger dependency.


176-182: LGTM: Proper RemoteWorkerBuilder configuration extraction.

The method correctly extracts optional configuration properties using safe optional chaining and constructs the RemoteWorkerBuilder with appropriate parameters. The threshold configurations align with the fine-grained monitoring mentioned in the PR objectives.

Comment thread packages/scheduling/src/ScheduledTask.ts Outdated
Comment thread packages/scheduling/src/ScheduledTask.ts Outdated
Comment thread packages/services/src/gateway/LocalGateway.ts Outdated
Comment thread packages/scheduling/README.md Outdated
@@ -0,0 +1,9 @@

# Jitar Build
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Jitar Scheduling

@sonarqubecloud
Copy link
Copy Markdown

@basmasking basmasking merged commit 69b1de1 into main Jul 18, 2025
23 checks passed
@basmasking basmasking deleted the 561-add-grace-period-to-health-check-system branch July 18, 2025 20:01
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.

Refactor health checks from pull to push system Add grace period to health check system

2 participants