Skip to content

refactor(alert): uses a single table for all alerts#1320

Merged
ygrishajev merged 3 commits intomainfrom
feature/notifications
May 15, 2025
Merged

refactor(alert): uses a single table for all alerts#1320
ygrishajev merged 3 commits intomainfrom
feature/notifications

Conversation

@ygrishajev
Copy link
Contributor

@ygrishajev ygrishajev commented May 14, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a unified alerts API with endpoints for creating, retrieving, updating, and deleting alerts.
    • Added support for two alert types: chain message alerts and deployment balance alerts, each with specific validation and data schemas.
    • Enhanced alert management with advanced filtering, status tracking, and parameter handling.
  • Refactor

    • Consolidated alert-related services, repositories, and schemas into a unified structure, replacing previous raw and deployment balance alert modules.
    • Updated REST and database layers to use new alert schemas and repositories.
    • Improved test suites and data generators to align with the new alert architecture.
  • Bug Fixes

    • Adjusted data seeding and test logic to ensure consistent alert status values and parameter nesting.
  • Chores

    • Cleaned up deprecated files, schemas, and controllers related to previous alert implementations.

@ygrishajev ygrishajev requested a review from a team as a code owner May 14, 2025 15:46
@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 14, 2025

Walkthrough

These changes refactor and unify the notifications alert system. The schema for alerts is consolidated into a single, extensible model supporting multiple alert types. Old raw and deployment balance alert modules, repositories, and controllers are removed. New schemas, repositories, and a REST controller are introduced for the unified alert model, with all code, tests, and migrations updated accordingly.

Changes

File(s) Change Summary
apps/notifications/drizzle/0000_cultured_kingpin.sql, 0001_foamy_amazoness.sql, 0002_tiresome_power_man.sql, 0003_regular_ezekiel.sql, meta/0001_snapshot.json, meta/0002_snapshot.json, meta/0003_snapshot.json Deleted legacy SQL migrations and old schema snapshots for raw and deployment balance alerts.
apps/notifications/drizzle/0000_striped_vin_gonzales.sql Added new migration: creates unified alerts, contact_points, and block_cursor tables, with enums for alert type/status.
apps/notifications/drizzle/meta/0000_snapshot.json Updated schema snapshot to reflect unified alert model and new table structures.
apps/notifications/drizzle/meta/_journal.json Consolidated migration journal entries to reference the new migration.
apps/notifications/drizzle.config.ts Updated schema path and reformatted environment variable validation.
apps/notifications/src/interfaces/alert-events/handlers/chain-events/chain-events.handler.ts, .spec.ts Replaced RawAlertsService with ChainMessageAlertService in event handler and tests.
apps/notifications/src/interfaces/rest/controllers/raw-alert/raw-alert.controller.ts Deleted old raw alert REST controller and related schemas/types.
apps/notifications/src/interfaces/rest/controllers/alert/alert.controller.ts, .spec.ts Added new unified alert REST controller and updated tests to use it.
apps/notifications/src/interfaces/rest/http-schemas/alert.http-schema.ts Added Zod schemas for unified alert request/response validation.
apps/notifications/src/interfaces/rest/rest.module.ts Switched controller registration from RawAlertController to AlertController.
apps/notifications/src/main.ts Refactored string usage and variable naming for clarity; no logic changes.
apps/notifications/src/modules/alert/model-schemas/alert-base.schema.ts, deployment-balance-alert.schema.ts, raw-alert.schema.ts Deleted old alert schema modules for raw and deployment balance alerts.
apps/notifications/src/modules/alert/model-schemas/alert.schema.ts Added unified Alert schema with enums for type/status and all relevant fields.
apps/notifications/src/modules/alert/model-schemas/index.ts Updated exports to only expose unified alert schema.
apps/notifications/src/modules/alert/repositories/alert/alert-json-fields.schema.ts Added Zod schemas and types for alert JSON fields and conditions.
apps/notifications/src/modules/alert/repositories/alert/alert.repository.ts Added new AlertRepository to manage all alert types with unified logic and permissions.
apps/notifications/src/modules/alert/repositories/deployment-balance-alert/deployment-balance-alert.repository.ts Deleted old deployment balance alert repository and types.
apps/notifications/src/modules/alert/repositories/raw-alert/raw-alert.repository.ts Deleted old raw alert repository and types.
apps/notifications/src/modules/alert/services/chain-message-alert/chain-message-alert.service.ts, .spec.ts Renamed and refactored service from RawAlertsService to ChainMessageAlertService with new repository and types.
apps/notifications/src/modules/alert/services/deployment-balance-alerts/deployment-balance-alerts.service.ts, .spec.ts Updated to use new AlertRepository and unified alert types.
apps/notifications/src/modules/alert/alert.module.ts Updated providers/exports: removed old alert services/repositories, added new ones.
apps/notifications/test/functional/alert-crud.spec.ts Updated tests: switched from raw to unified alerts, changed endpoints, schemas, and assertions.
apps/notifications/test/functional/balance-alert.spec.ts Updated test data structure and schema usage for unified deployment balance alerts.
apps/notifications/test/functional/chain-message-alert.spec.ts Updated test and data generator to use unified chain message alert schema.
apps/notifications/test/seeders/akash-address.seeder.ts Changed mock Akash address generator to return lowercase strings.
apps/notifications/test/seeders/chain-message-alert.seeder.ts Renamed and refactored data generator for chain message alerts to use new types and schema.
apps/notifications/test/seeders/deployment-balance-alert.seeder.ts Refactored data generator: unified type, status casing, and nested params.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant AlertController
    participant AlertRepository
    participant Database

    Client->>AlertController: POST /alerts (create alert)
    AlertController->>AlertRepository: create(input)
    AlertRepository->>Database: INSERT INTO alerts ...
    Database-->>AlertRepository: alert record
    AlertRepository-->>AlertController: created alert
    AlertController-->>Client: alert response

    Client->>AlertController: GET /alerts/:id
    AlertController->>AlertRepository: findOneById(id)
    AlertRepository->>Database: SELECT * FROM alerts WHERE id=...
    Database-->>AlertRepository: alert record or null
    AlertRepository-->>AlertController: alert or undefined
    AlertController-->>Client: alert response or 404

    Client->>AlertController: PATCH /alerts/:id
    AlertController->>AlertRepository: updateById(id, patch)
    AlertRepository->>Database: UPDATE alerts SET ... WHERE id=...
    Database-->>AlertRepository: updated alert or null
    AlertRepository-->>AlertController: alert or undefined
    AlertController-->>Client: alert response or 404

    Client->>AlertController: DELETE /alerts/:id
    AlertController->>AlertRepository: deleteOneById(id)
    AlertRepository->>Database: DELETE FROM alerts WHERE id=...
    Database-->>AlertRepository: deleted alert or null
    AlertRepository-->>AlertController: alert or undefined
    AlertController-->>Client: alert response or 404
Loading

Suggested reviewers

  • baktun14

Poem

In the warren of code, a change takes root,
Old alerts retire, new schemas commute.
With enums and types, conditions abound,
The alert system unified, robust, and sound.
From chain to balance, all in one place—
A hop forward for rabbits, and code’s interface!
🐇✨

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 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 bf4abd4 and ebf7e6e.

📒 Files selected for processing (39)
  • apps/notifications/drizzle.config.ts (1 hunks)
  • apps/notifications/drizzle/0000_cultured_kingpin.sql (0 hunks)
  • apps/notifications/drizzle/0000_striped_vin_gonzales.sql (1 hunks)
  • apps/notifications/drizzle/0001_foamy_amazoness.sql (0 hunks)
  • apps/notifications/drizzle/0002_tiresome_power_man.sql (0 hunks)
  • apps/notifications/drizzle/0003_regular_ezekiel.sql (0 hunks)
  • apps/notifications/drizzle/meta/0000_snapshot.json (5 hunks)
  • apps/notifications/drizzle/meta/0001_snapshot.json (0 hunks)
  • apps/notifications/drizzle/meta/0002_snapshot.json (0 hunks)
  • apps/notifications/drizzle/meta/0003_snapshot.json (0 hunks)
  • apps/notifications/drizzle/meta/_journal.json (1 hunks)
  • apps/notifications/src/interfaces/alert-events/handlers/chain-events/chain-events.handler.spec.ts (3 hunks)
  • apps/notifications/src/interfaces/alert-events/handlers/chain-events/chain-events.handler.ts (2 hunks)
  • apps/notifications/src/interfaces/rest/controllers/alert/alert.controller.spec.ts (1 hunks)
  • apps/notifications/src/interfaces/rest/controllers/alert/alert.controller.ts (1 hunks)
  • apps/notifications/src/interfaces/rest/controllers/raw-alert/raw-alert.controller.ts (0 hunks)
  • apps/notifications/src/interfaces/rest/http-schemas/alert.http-schema.ts (1 hunks)
  • apps/notifications/src/interfaces/rest/rest.module.ts (1 hunks)
  • apps/notifications/src/main.ts (1 hunks)
  • apps/notifications/src/modules/alert/alert.module.ts (1 hunks)
  • apps/notifications/src/modules/alert/model-schemas/alert-base.schema.ts (0 hunks)
  • apps/notifications/src/modules/alert/model-schemas/alert.schema.ts (1 hunks)
  • apps/notifications/src/modules/alert/model-schemas/deployment-balance-alert.schema.ts (0 hunks)
  • apps/notifications/src/modules/alert/model-schemas/index.ts (1 hunks)
  • apps/notifications/src/modules/alert/model-schemas/raw-alert.schema.ts (0 hunks)
  • apps/notifications/src/modules/alert/repositories/alert/alert-json-fields.schema.ts (1 hunks)
  • apps/notifications/src/modules/alert/repositories/alert/alert.repository.ts (1 hunks)
  • apps/notifications/src/modules/alert/repositories/deployment-balance-alert/deployment-balance-alert.repository.ts (0 hunks)
  • apps/notifications/src/modules/alert/repositories/raw-alert/raw-alert.repository.ts (0 hunks)
  • apps/notifications/src/modules/alert/services/chain-message-alert/chain-message-alert.service.spec.ts (12 hunks)
  • apps/notifications/src/modules/alert/services/chain-message-alert/chain-message-alert.service.ts (2 hunks)
  • apps/notifications/src/modules/alert/services/deployment-balance-alerts/deployment-balance-alerts.service.spec.ts (11 hunks)
  • apps/notifications/src/modules/alert/services/deployment-balance-alerts/deployment-balance-alerts.service.ts (5 hunks)
  • apps/notifications/test/functional/alert-crud.spec.ts (3 hunks)
  • apps/notifications/test/functional/balance-alert.spec.ts (2 hunks)
  • apps/notifications/test/functional/chain-message-alert.spec.ts (4 hunks)
  • apps/notifications/test/seeders/akash-address.seeder.ts (1 hunks)
  • apps/notifications/test/seeders/chain-message-alert.seeder.ts (2 hunks)
  • apps/notifications/test/seeders/deployment-balance-alert.seeder.ts (3 hunks)
💤 Files with no reviewable changes (13)
  • apps/notifications/src/modules/alert/model-schemas/raw-alert.schema.ts
  • apps/notifications/drizzle/0001_foamy_amazoness.sql
  • apps/notifications/src/modules/alert/model-schemas/alert-base.schema.ts
  • apps/notifications/drizzle/0003_regular_ezekiel.sql
  • apps/notifications/src/modules/alert/model-schemas/deployment-balance-alert.schema.ts
  • apps/notifications/drizzle/meta/0002_snapshot.json
  • apps/notifications/drizzle/meta/0003_snapshot.json
  • apps/notifications/drizzle/0002_tiresome_power_man.sql
  • apps/notifications/src/modules/alert/repositories/raw-alert/raw-alert.repository.ts
  • apps/notifications/drizzle/0000_cultured_kingpin.sql
  • apps/notifications/src/modules/alert/repositories/deployment-balance-alert/deployment-balance-alert.repository.ts
  • apps/notifications/src/interfaces/rest/controllers/raw-alert/raw-alert.controller.ts
  • apps/notifications/drizzle/meta/0001_snapshot.json
✅ Files skipped from review due to trivial changes (1)
  • apps/notifications/src/modules/alert/model-schemas/index.ts
🚧 Files skipped from review as they are similar to previous changes (21)
  • apps/notifications/src/interfaces/alert-events/handlers/chain-events/chain-events.handler.spec.ts
  • apps/notifications/test/seeders/akash-address.seeder.ts
  • apps/notifications/drizzle.config.ts
  • apps/notifications/drizzle/meta/_journal.json
  • apps/notifications/test/functional/chain-message-alert.spec.ts
  • apps/notifications/src/main.ts
  • apps/notifications/src/interfaces/alert-events/handlers/chain-events/chain-events.handler.ts
  • apps/notifications/src/modules/alert/alert.module.ts
  • apps/notifications/test/seeders/chain-message-alert.seeder.ts
  • apps/notifications/src/interfaces/rest/rest.module.ts
  • apps/notifications/src/modules/alert/services/deployment-balance-alerts/deployment-balance-alerts.service.ts
  • apps/notifications/test/functional/balance-alert.spec.ts
  • apps/notifications/src/modules/alert/services/chain-message-alert/chain-message-alert.service.spec.ts
  • apps/notifications/test/seeders/deployment-balance-alert.seeder.ts
  • apps/notifications/src/modules/alert/services/deployment-balance-alerts/deployment-balance-alerts.service.spec.ts
  • apps/notifications/test/functional/alert-crud.spec.ts
  • apps/notifications/src/modules/alert/services/chain-message-alert/chain-message-alert.service.ts
  • apps/notifications/src/modules/alert/repositories/alert/alert-json-fields.schema.ts
  • apps/notifications/drizzle/0000_striped_vin_gonzales.sql
  • apps/notifications/src/modules/alert/model-schemas/alert.schema.ts
  • apps/notifications/src/interfaces/rest/http-schemas/alert.http-schema.ts
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: validate-notifications
🔇 Additional comments (29)
apps/notifications/src/interfaces/rest/controllers/alert/alert.controller.spec.ts (8)

8-10: Updated imports align with the new unified alert model

The imports have been updated to reflect the architectural change from separate alert types to a unified alert model. The AlertRepository and AlertController now replace what used to be specific to raw alerts.


13-13: Import uses appropriate test seeder for chain message alerts

Correctly updated to use the chain message alert seeder instead of the previous raw alert seeder, supporting the new unified alert model.


15-15: Test suite properly renamed to reflect new controller

The test suite name is updated to use the new AlertController name consistent with the architectural changes.


17-29: Creation test correctly uses the unified alert model

Test case properly updated to use alertRepository and chainMessageCreateInputSchema instead of the previous raw alert counterparts. The method calls and assertion patterns match the new unified repository interface.


32-61: Update test cases correctly use the new repository and schema

The patch alert tests have been properly updated to use the unified alert repository and appropriate chain message schemas. Both the success and error handling test cases maintain the same validation patterns while adapting to the new model.


64-91: Get alert tests properly adapted to the unified model

The get alert test cases correctly use the new repository methods while maintaining the same validation logic for both success and not found cases.


94-121: Delete alert tests correctly updated for the new repository

The delete alert test cases properly use the unified repository's methods while maintaining the same test assertions and error handling for both success and not found cases.


124-137: Setup function correctly initializes the unified controller and repository

The test setup function has been properly updated to create and return instances of the new AlertController and AlertRepository instead of their raw alert predecessors.

apps/notifications/src/interfaces/rest/controllers/alert/alert.controller.ts (7)

1-13: Imports correctly set up for the new unified controller

The imports properly include all necessary dependencies for the new controller, including NestJS decorators, ts-results types, and the new alert schemas and repository.


14-19: Controller is properly configured for RESTful alert management

The controller is correctly versioned as "1" and mapped to the "alerts" path (no longer under a "/raw" path), which aligns with the unified alert model approach. The dependency injection for AlertRepository is properly set up.


21-30: Create endpoint properly validates input and returns typed responses

The POST endpoint correctly uses ValidateHttp for request validation with the appropriate schemas. The implementation calls the repository's create method and returns a properly typed Result.


32-39: Get endpoint properly retrieves and validates single alerts

The GET endpoint is correctly implemented with parameter validation and proper typing. It uses the repository's findOneById method and the helper toResponse method to handle not found cases appropriately.


41-52: Patch endpoint properly validates input and handles not found cases

The PATCH endpoint is correctly implemented with proper parameter and body validation. It uses the repository's updateById method and the helper toResponse method for consistent error handling.


54-61: Delete endpoint properly handles success and not found cases

The DELETE endpoint is correctly implemented with proper validation. It uses the repository's deleteOneById method and the helper toResponse method to handle not found cases appropriately.


63-65: Helper method provides consistent error handling

The private toResponse method effectively centralizes the logic for converting repository results to HTTP responses, ensuring consistent error handling across all endpoints.

apps/notifications/src/modules/alert/repositories/alert/alert.repository.ts (10)

1-14: Repository imports necessary dependencies for unified alert handling

The imports correctly include CASL for authorization, Drizzle for ORM, NestJS for dependency injection, and local schema definitions. This sets up the repository for handling all alert types with proper authorization and database access.


15-39: Type definitions properly model the unified alert system

The type definitions create a well-structured type system for the unified alert model, with:

  • Clear mapping between alert types and their specific input/output types
  • Proper type inheritance and specialization for each alert type
  • Type safety for operations that depend on the alert type

This ensures type safety throughout the application when working with different alert types.


41-48: Repository properly set up with dependency injection

The repository is correctly set up as an injectable class with proper dependency injection for the Drizzle database connection. This follows the NestJS patterns for dependency injection.


50-62: Authorization methods properly implemented for access control

The repository correctly implements CASL-based access control with methods to:

  • Filter queries based on user abilities
  • Create a new repository instance with abilities applied
  • Apply ability constraints to where clauses

This ensures proper access control throughout the repository methods.


63-70: Create method properly enforces permissions and handles transactions

The create method correctly:

  • Enforces permissions before attempting database operations
  • Uses a transaction for data consistency
  • Converts the raw database result to the appropriate typed output
  • Uses generic type parameters to ensure type safety based on alert type

This provides type safety while maintaining proper authorization controls.


72-82: Update method properly applies permissions and handles transactions

The updateById method correctly:

  • Uses a transaction for data consistency
  • Applies permission filters to the query
  • Returns the updated alert or undefined if not found
  • Converts the raw result to the appropriate typed output

This ensures proper access control and data consistency for updates.


84-90: Find method properly applies permissions

The findOneById method correctly applies permission filters to the query and converts the result to the appropriate typed output.


92-101: Delete method properly applies permissions and handles transactions

The deleteOneById method correctly:

  • Uses a transaction for data consistency
  • Applies permission filters to the query
  • Returns the deleted alert or undefined if not found
  • Converts the raw result to the appropriate typed output

This ensures proper access control and data consistency for deletions.


103-139: Pagination implementation is robust and supports filtering

The paginate method correctly implements cursor-based pagination with:

  • Type-safe filtering by alert type
  • Optional block height filtering
  • Proper handling of the last ID for continuation
  • Batch processing with a callback pattern
  • Clean loop termination when no more results are available

This provides an efficient way to process large sets of alerts.


141-164: Type conversion methods ensure type safety

The toOutputList and toOutput methods correctly:

  • Convert raw database records to strongly typed outputs
  • Parse JSON fields according to the alert type schema
  • Handle different alert types with type-specific parsing
  • Throw a clear error for unknown alert types

This ensures type safety when working with the database's JSON fields.

apps/notifications/drizzle/meta/0000_snapshot.json (4)

7-119: Unified alerts table schema correctly implements the new data model

The new alerts table replaces the separate alert tables (deployment_balance_alerts and raw_alerts) with a consolidated schema that:

  • Maintains all necessary fields from the previous tables
  • Adds a type discriminator to differentiate alert types
  • Includes status tracking (NORMAL, FIRING, FIRED)
  • Uses JSONB fields for flexible conditions and parameters
  • Includes proper foreign key relationships with contact points
  • Tracks block height for blockchain-related processing

This schema design supports the unified alert model approach while keeping all the functionality from the previous separate models.


120-180: Contact points table correctly updated for the unified model

The contact_points table has been properly updated to:

  • Remove deprecated columns
  • Add a non-null type column of enum contact_point_type
  • Maintain proper constraints and relationships

This aligns with the unified alert model approach.


181-220: Block cursor table properly defined for tracking blockchain state

The block_cursor table is correctly designed to track the last processed block, which is essential for blockchain-related alert processing. The schema includes appropriate defaults and constraints.


223-247: Enum types properly defined for the unified alert model

The enum definitions correctly support the unified alert model with:

  • AlertStatus: NORMAL, FIRING, FIRED - tracking alert states
  • AlertType: CHAIN_MESSAGE, DEPLOYMENT_BALANCE - supporting multiple alert types in a single table
  • ContactPointType: Supporting different notification methods

These enums provide the necessary type safety and constraints for the database schema.

✨ Finishing Touches
  • 📝 Generate Docstrings

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.

@codecov
Copy link

codecov bot commented May 14, 2025

Codecov Report

Attention: Patch coverage is 94.57364% with 7 lines in your changes missing coverage. Please review.

Project coverage is 32.78%. Comparing base (42a56ba) to head (d449beb).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...dules/alert/repositories/alert/alert.repository.ts 89.83% 6 Missing ⚠️
...ns/src/modules/alert/model-schemas/alert.schema.ts 87.50% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1320      +/-   ##
==========================================
- Coverage   32.81%   32.78%   -0.04%     
==========================================
  Files         758      757       -1     
  Lines       18890    18876      -14     
  Branches     3538     3537       -1     
==========================================
- Hits         6199     6188      -11     
+ Misses      11939    11936       -3     
  Partials      752      752              
Flag Coverage Δ *Carryforward flag
api 62.37% <ø> (ø) Carriedforward from d67df1d
deploy-web 12.53% <ø> (ø) Carriedforward from d67df1d
notifications 89.49% <94.57%> (+0.15%) ⬆️
provider-proxy 80.09% <ø> (ø) Carriedforward from d67df1d

*This pull request uses carry forward flags. Click here to find out more.

Files with missing lines Coverage Δ
...ents/handlers/chain-events/chain-events.handler.ts 100.00% <100.00%> (ø)
...erfaces/rest/controllers/alert/alert.controller.ts 100.00% <100.00%> (ø)
.../interfaces/rest/http-schemas/alert.http-schema.ts 100.00% <100.00%> (ø)
...ert/repositories/alert/alert-json-fields.schema.ts 100.00% <100.00%> (ø)
...chain-message-alert/chain-message-alert.service.ts 100.00% <100.00%> (ø)
...alance-alerts/deployment-balance-alerts.service.ts 96.15% <100.00%> (ø)
...ns/src/modules/alert/model-schemas/alert.schema.ts 87.50% <87.50%> (ø)
...dules/alert/repositories/alert/alert.repository.ts 89.83% <89.83%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@ygrishajev ygrishajev force-pushed the feature/notifications branch from 5513bb6 to bf4abd4 Compare May 14, 2025 15:49
Copy link
Contributor

@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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 6

🔭 Outside diff range comments (1)
apps/notifications/src/interfaces/alert-events/handlers/chain-events/chain-events.handler.spec.ts (1)

19-27: 🛠️ Refactor suggestion

Update variable names to match the new service type

The variable name rawAlertsService is still being used in the test body, but it now refers to an instance of ChainMessageAlertService. For clarity and consistency, you should update all references to match the new service type.

- const { controller, rawAlertsService, brokerService } = await setup();
+ const { controller, chainMessageAlertService, brokerService } = await setup();

  const mockEvent = generateMock(MsgCloseDeploymentDto.schema);
  const alertMessage = generateAlertMessage({});
- rawAlertsService.alertFor.mockImplementation((_, callback) => callback(alertMessage));
+ chainMessageAlertService.alertFor.mockImplementation((_, callback) => callback(alertMessage));

  await controller.processDeploymentClosed(mockEvent);

- expect(rawAlertsService.alertFor).toHaveBeenCalledWith(mockEvent, expect.any(Function));
+ expect(chainMessageAlertService.alertFor).toHaveBeenCalledWith(mockEvent, expect.any(Function));
🧹 Nitpick comments (14)
apps/notifications/src/main.ts (2)

6-6: Avoid shadowing the built-in module
Naming the constant module can be misleading since Node.js exposes a global module object. Consider a more descriptive name (e.g. interfaceName or interfaceKey) to improve readability and avoid potential confusion.


12-13: Improve missing-module detection
Relying on error.message.includes("Cannot find module") is brittle across Node versions/locales. A more robust approach is to check error.code === "ERR_MODULE_NOT_FOUND" (or inspect error.code) when detecting a missing dynamic import.

apps/notifications/src/interfaces/rest/rest.module.ts (1)

8-8: Inconsistent directory and controller naming.

The controller has been renamed to AlertController but is still located in the controllers/raw-alert/ directory. Consider renaming the directory to controllers/alert/ to maintain consistency with the new unified alert structure.

apps/notifications/src/interfaces/alert-events/handlers/chain-events/chain-events.handler.ts (1)

13-13: Property name doesn't match its type.

The property is still named rawAlertsService but its type is now ChainMessageAlertService. For clarity and consistency, consider renaming the property to match its type.

-  private readonly rawAlertsService: ChainMessageAlertService,
+  private readonly chainMessageAlertService: ChainMessageAlertService,

Don't forget to update all references to this property in the class methods.

packages/http-sdk/src/deployment/deployment-http.service.ts (1)

144-145: Consider using a structured logging approach instead of console.log

While adding debug logging is helpful, using direct console.log statements is generally not recommended for production code. Consider using a proper logging framework or a centralized logging utility that supports:

  1. Log levels (debug, info, warn, error)
  2. Conditional logging based on environment
  3. Structured log format for easier parsing

This would make logs more consistent and manageable across the codebase.

- console.log("DEBUG owner", owner);
- console.log("DEBUG dseq", dseq);
+ logger.debug('Finding deployment', { owner, dseq });
apps/notifications/src/modules/alert/model-schemas/alert.schema.ts (1)

26-28: Consider an index on min_block_height, type, status, enabled

These columns are used as filters in the repository (lte(min_block_height, …), eq(type, …) etc.).
Adding a composite or individual indexes will keep alert polling snappy when the table grows.

apps/notifications/src/modules/alert/repositories/alert/alert-json-fields.schema.ts (1)

38-41: Nit: export a reusable AlertTypeSchema

You already need the union of alert types in multiple places (HTTP schema, repository, etc.).
Exporting a single constant prevents drift:

-const chainMessageTypeSchema = z.literal("CHAIN_MESSAGE");
-const deploymentBalanceTypeSchema = z.literal("DEPLOYMENT_BALANCE");
-export const alertTypeSchema = z.union([chainMessageTypeSchema, deploymentBalanceTypeSchema]);
+export const chainMessageTypeSchema      = z.literal("CHAIN_MESSAGE");
+export const deploymentBalanceTypeSchema = z.literal("DEPLOYMENT_BALANCE");
+export const alertTypeSchema             = z.union([
+  chainMessageTypeSchema,
+  deploymentBalanceTypeSchema
+]);
apps/notifications/src/modules/alert/repositories/alert/alert.repository.ts (1)

141-147: toOutputList double-injects type; avoid data mutation

{ ...alert, type } overwrites the DB value and might mask data corruption (e.g., record stored with wrong type).
Safer:

-return alerts.map(alert => this.toOutput({ ...alert, type }));
+return alerts.map(alert => this.toOutput(alert as InternalAlertOutput & { type: T }));

That way the method trusts the source of truth (DB) and preserves defensive checks inside toOutput.

apps/notifications/drizzle/0000_striped_vin_gonzales.sql (3)

4-4: Consider future extensibility of contact point types.

The contact_point_type enum currently only has one value ('email'). While this works for the immediate implementation, consider whether additional contact methods (like SMS, push notifications, webhooks, etc.) might be needed in the future.


5-19: Good consolidation of alert tables with appropriate structure.

The unified alerts table properly captures the shared fields between different alert types while allowing type-specific data in the conditions and params fields. This consolidation will simplify schema management and queries.

Consider adding an index on user_id for performance if users will frequently query their own alerts:

CREATE TABLE "alerts" (
	"id" uuid PRIMARY KEY DEFAULT uuid_generate_v4() NOT NULL,
	"user_id" uuid NOT NULL,
	"contact_point_id" uuid NOT NULL,
	"summary" text NOT NULL,
	"description" text NOT NULL,
	"conditions" jsonb NOT NULL,
	"enabled" boolean DEFAULT true NOT NULL,
	"type" "alert_type" NOT NULL,
	"status" "alert_status" DEFAULT 'NORMAL' NOT NULL,
	"params" jsonb,
	"min_block_height" integer DEFAULT 0 NOT NULL,
	"created_at" timestamp DEFAULT now() NOT NULL,
	"updated_at" timestamp DEFAULT now() NOT NULL
);
+CREATE INDEX alerts_user_id_idx ON "alerts" ("user_id");

38-38: Consider ON DELETE CASCADE behavior for contact_point_id.

The current foreign key relationship uses ON DELETE no action, which prevents deletion of contact points that have alerts. If the intent is to delete alerts when their contact point is deleted, consider using ON DELETE CASCADE instead.

-ALTER TABLE "alerts" ADD CONSTRAINT "alerts_contact_point_id_contact_points_id_fk" FOREIGN KEY ("contact_point_id") REFERENCES "public"."contact_points"("id") ON DELETE no action ON UPDATE no action;
+ALTER TABLE "alerts" ADD CONSTRAINT "alerts_contact_point_id_contact_points_id_fk" FOREIGN KEY ("contact_point_id") REFERENCES "public"."contact_points"("id") ON DELETE CASCADE ON UPDATE no action;
apps/notifications/src/interfaces/rest/http-schemas/alert.http-schema.ts (2)

35-39: Consider type-specific patch schemas for better validation.

The current patch schema combines conditions from both alert types using a union. Consider creating separate patch schemas for each alert type to maintain type-specific validations and ensure consistency.

-export const alertPatchInputSchema = alertCreateCommonInputSchema
-  .extend({
-    conditions: z.union([chainMessageConditionsSchema, deploymentBalanceConditionsSchema])
-  })
-  .partial();
+export const chainMessagePatchInputSchema = chainMessageCreateInputSchema.partial();
+export const deploymentBalancePatchInputSchema = deploymentBalanceCreateInputSchema.partial();
+export const alertPatchInputSchema = z.discriminatedUnion("type", [
+  chainMessagePatchInputSchema,
+  deploymentBalancePatchInputSchema
+]);

44-44: Consider using enum for status instead of string.

The status field in the output schema is defined as z.string() but should match the alert_status enum defined in the database schema. Consider using a more specific validation.

-  status: z.string(),
+  status: z.enum(['NORMAL', 'FIRING', 'FIRED']),
apps/notifications/drizzle/meta/0000_snapshot.json (1)

99-112: Consider index on alerts.user_id for query performance.

While the foreign key relationship is correctly set up, consider adding an index on the user_id column in the alerts table if users will frequently query their own alerts. This would improve query performance for those operations.

🛑 Comments failed to post (6)
apps/notifications/src/interfaces/alert-events/handlers/chain-events/chain-events.handler.spec.ts (1)

47-62: 🛠️ Refactor suggestion

Update the return object property name to match the variable name in tests

The setup function returns an object with a property named rawAlertsService that contains the ChainMessageAlertService mock. For consistency with the return type annotation and the test usage, update the property name.

async function setup(): Promise<{
  controller: ChainEventsHandler;
  rawAlertsService: MockProxy<ChainMessageAlertService>;
  deploymentBalanceAlertsService: MockProxy<DeploymentBalanceAlertsService>;
  brokerService: MockProxy<BrokerService>;
}> {
  const module: TestingModule = await Test.createTestingModule({
    providers: [MockProvider(BrokerService), ChainEventsHandler, MockProvider(ChainMessageAlertService), MockProvider(DeploymentBalanceAlertsService)]
  }).compile();

  return {
    controller: module.get<ChainEventsHandler>(ChainEventsHandler),
-   rawAlertsService: module.get<MockProxy<ChainMessageAlertService>>(ChainMessageAlertService),
+   rawAlertsService: module.get<MockProxy<ChainMessageAlertService>>(ChainMessageAlertService), // Either rename this to chainMessageAlertService...
    deploymentBalanceAlertsService: module.get<MockProxy<DeploymentBalanceAlertsService>>(DeploymentBalanceAlertsService),
    brokerService: module.get<MockProxy<BrokerService>>(BrokerService)
  };
}

Alternatively, you could update the return type annotation instead:

async function setup(): Promise<{
  controller: ChainEventsHandler;
- rawAlertsService: MockProxy<ChainMessageAlertService>;
+ chainMessageAlertService: MockProxy<ChainMessageAlertService>; // ...or update the type annotation to match the existing property name
  deploymentBalanceAlertsService: MockProxy<DeploymentBalanceAlertsService>;
  brokerService: MockProxy<BrokerService>;
}> {

Committable suggestion skipped: line range outside the PR's diff.

apps/notifications/src/modules/alert/services/chain-message-alert/chain-message-alert.service.spec.ts (1)

35-35: 💡 Verification agent

🧩 Analysis chain

Type casting could be improved for better type safety

The as any type casting is used multiple times to work around type compatibility issues between the repository callback and the test data. Consider creating a proper type guard or interface alignment to avoid using any.

- options.callback(alerts as any);
+ options.callback(alerts as AlertOutput[]);

Also applies to: 70-70, 97-97, 158-158, 213-213


🌐 Web query:

TypeScript type assertion best practices vs using 'any'

💡 Result:

When working with TypeScript, choosing between type assertion and using the any type has important implications for code safety and maintainability. Here’s a comparison and best practices for each:

Type Assertion

Type assertion is a way to tell the TypeScript compiler to treat a value as a certain type, without performing type checking or restructuring. It’s done using the as keyword or angle-bracket syntax.

Best Practices:

  1. Use sparingly and only when certain: Use type assertion when you are confident about the type of a value but TypeScript cannot infer it correctly, such as when interacting with third-party libraries or DOM elements.
  2. Avoid forcing incorrect types: Don’t use assertions to silence type errors by forcing incompatible types; this can lead to runtime errors.
  3. Prefer more specific types: Assert the most specific type possible rather than a broad type.
  4. Validate data externally: When data comes from outside TypeScript’s control (like JSON APIs), validate it first before asserting its type.
  5. Avoid any fallback: Using assertions is better than using any blindly, as it keeps type information more explicit.
const inputElement = document.querySelector('input') as HTMLInputElement;

Using any

any disables type checking for that variable, essentially opting out of TypeScript’s type system.

Best Practices:

  1. Avoid using any if possible: Using any defeats the purpose of TypeScript, making your code less safe and more prone to bugs.
  2. Use for gradual typing: any can be useful temporarily during migration from JavaScript to TypeScript or in prototypes.
  3. Replace any ASAP: Aim to narrow any down to a more specific type as soon as you can.
  4. Consider alternatives: Use unknown if you want to accept any value but enforce type checks before use.
  5. Use linters: Configure linters to warn on undesired use of any to maintain code quality.
let data: any = fetchData();

Summary

Aspect Type Assertion any
Compiler Checks Bypasses checks on asserted type No checks; disables safety
Safety Safer if used carefully Unsafe, can hide bugs
Code Documentation Provides explicit type info No type info
Use Cases Interfacing with external APIs, DOM Temporary, gradual typing
Best Practice Validate data, be specific Minimize use, prefer unknown

If you want, I can help you with example scenarios or guidelines for your specific project!


🏁 Script executed:

#!/bin/bash
# Search for the AlertOutput type definition across the repo
rg 'type AlertOutput|interface AlertOutput' -n

# Inspect the test file for alerts declaration and usage of options.callback
rg -n 'chain-message-alert.service.spec.ts' -C3 -F 'alerts'

# Locate the callback signature in the service file to confirm its expected parameter type
rg -n 'callback(' -C3 -F 'callback' apps/notifications/src/modules/alert/services/chain-message-alert/chain-message-alert.service.ts

Length of output: 763


🏁 Script executed:

#!/bin/bash
# Locate the spec file
spec_file=$(fd chain-message-alert.service.spec.ts)

# Show lines 1-100 of the spec to inspect alerts declaration and usage
sed -n '1,100p' "$spec_file"

# Locate the service file
service_file=$(fd chain-message-alert.service.ts)

# Show callback signature and surrounding context in the service file
grep -R -n 'callback' -C3 "$service_file"

Length of output: 5310


Remove unnecessary any casts in tests

The alerts array is already declared as AlertOutput[], so there’s no need to bypass type checking with as any. You can invoke the callback directly and preserve full type safety:

- alertRepository.paginate.mockImplementation(async options => {
-   options.callback(alerts as any);
- });
+ alertRepository.paginate.mockImplementation(async options => {
+   options.callback(alerts);
+ });

Please update all occurrences in
apps/notifications/src/modules/alert/services/chain-message-alert/chain-message-alert.service.spec.ts
at lines 35, 70, 97, 158, and 213.

apps/notifications/src/modules/alert/model-schemas/alert.schema.ts (1)

15-18: 🛠️ Refactor suggestion

Add explicit FK & cascade on userId / contactPointId for referential integrity

userId is declared as a plain uuid without a FK; contactPointId has a FK but no onDelete('cascade').
If either a user / contact point is removed you may orphan alerts or run into FK-violations at runtime.

- userId: uuid("user_id").notNull(),
+ userId: uuid("user_id")
+   .notNull()
+   .references(() => Users.id, { onDelete: "cascade" }),
+
- contactPointId: uuid("contact_point_id")
-   .notNull()
-   .references(() => ContactPoint.id),
+ contactPointId: uuid("contact_point_id")
+   .notNull()
+   .references(() => ContactPoint.id, { onDelete: "cascade" }),

(Replace Users with the actual users table.)
This prevents dangling records and eliminates manual cleanup.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

  userId: uuid("user_id")
    .notNull()
    .references(() => Users.id, { onDelete: "cascade" }),
  contactPointId: uuid("contact_point_id")
    .notNull()
    .references(() => ContactPoint.id, { onDelete: "cascade" }),
apps/notifications/src/modules/alert/repositories/alert/alert-json-fields.schema.ts (1)

4-15: ⚠️ Potential issue

toCompound is not truly recursive – nested AND/OR clauses fail validation

Inside the generated "and" | "or" branch the array elements are restricted to the base schema, so a payload like
{ operator: "and", value: [{ operator: "or", value:[…] }, { … }] } will be rejected.

A classic trick is a lazy schema:

-const toCompound = <T extends { operator: any; value: any; field: any }>(schema: ZodObject<T>) =>
-  z.union([
-    z.object({ operator: z.literal("and"), value: z.array(schema).min(2) }),
-    z.object({ operator: z.literal("or"),  value: z.array(schema).min(2) }),
-    schema
-  ]);
+const toCompound = <T extends ZodRawShape>(base: ZodObject<T>) => {
+  const lazy: z.ZodTypeAny = z.lazy(() =>
+    z.union([
+      z.object({ operator: z.literal("and"), value: z.array(lazy).min(2) }),
+      z.object({ operator: z.literal("or"),  value: z.array(lazy).min(2) }),
+      base
+    ])
+  );
+  return lazy as unknown as z.ZodType<T>;
+};

This permits arbitrarily deep logical trees while keeping type-safety.

apps/notifications/src/modules/alert/repositories/alert/alert.repository.ts (1)

120-124: ⚠️ Potential issue

paginate bypasses CASL checks – potential privilege escalation

All other CRUD methods apply whereAccessibleBy, but paginate builds its own clauses and never invokes the ability filter.
A user could call the polling endpoint and retrieve alerts they are not authorised to see.

-      const where = lastId ? and(...clauses, gt(schema.Alert.id, lastId)) : and(...clauses);
+      const base   = lastId ? and(...clauses, gt(schema.Alert.id, lastId)) : and(...clauses);
+      const where  = this.whereAccessibleBy(base);

Failing to do so undermines the RBAC layer.

apps/notifications/src/interfaces/rest/http-schemas/alert.http-schema.ts (1)

9-16: 💡 Verification agent

🧩 Analysis chain

Address the TODO comment about user authentication.

The code has a TODO comment about getting the userId from authentication instead of from the request body. This would improve security by ensuring users can only create alerts for themselves.


🏁 Script executed:

#!/bin/bash
# Check if there's authentication middleware that could be used

# Look for auth-related code
rg -A 3 "auth|authentication|middleware" --type ts | grep -v node_modules

# Check if the controller extracts user info from request
rg -A 5 "controller.*alert" --type ts

Length of output: 118897


Enforce authentication and source userId from auth context

The alert‐creation endpoint must not accept a userId in the request body—clients could create alerts on behalf of other users. Remove userId from the input schema, apply your auth middleware, and pull currentUser.id in the controller.

• Modify apps/notifications/src/interfaces/rest/http-schemas/alert.http-schema.ts:

 export const alertCreateCommonInputSchema = z.object({
-  userId: z.string().uuid(),
   contactPointId: z.string().uuid(),
   enabled: z.boolean().optional().default(true),
   summary: z.string().min(3),
   description: z.string().min(3)
 });

• In the alert controller (e.g. src/interfaces/rest/http-controllers/alert.controller.ts), register and invoke your authentication middleware, then use context.currentUser.id (or equivalent) instead of body.userId.
• Ensure the notifications service’s app entrypoint (e.g. src/app.ts) mounts the auth middleware before the alert routes.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

export const alertCreateCommonInputSchema = z.object({
  // TODO: receive user from the auth instead
  contactPointId: z.string().uuid(),
  enabled: z.boolean().optional().default(true),
  summary: z.string().min(3),
  description: z.string().min(3)
});

Copy link
Contributor

@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

🔭 Outside diff range comments (1)
apps/notifications/drizzle/meta/0000_snapshot.json (1)

120-180: ⚠️ Potential issue

Revisit the unique constraint on contact_points.user_id.
Enforcing user_id as unique prevents a user from having multiple contact points (e.g. email, SMS, webhook). If multi‐channel support is intended, change this to a composite unique key on (user_id, type).

🧹 Nitpick comments (1)
apps/notifications/drizzle/meta/0000_snapshot.json (1)

7-119: Optimize the new alerts table schema.
– Consider adding B-tree indexes on user_id and contact_point_id for faster lookups by user or contact point.
– Evaluate altering the foreign‐key to ON DELETE CASCADE if you want alerts cleaned up automatically when a contact point is removed.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5513bb6 and bf4abd4.

📒 Files selected for processing (40)
  • apps/notifications/drizzle.config.ts (1 hunks)
  • apps/notifications/drizzle/0000_cultured_kingpin.sql (0 hunks)
  • apps/notifications/drizzle/0000_striped_vin_gonzales.sql (1 hunks)
  • apps/notifications/drizzle/0001_foamy_amazoness.sql (0 hunks)
  • apps/notifications/drizzle/0002_tiresome_power_man.sql (0 hunks)
  • apps/notifications/drizzle/0003_regular_ezekiel.sql (0 hunks)
  • apps/notifications/drizzle/meta/0000_snapshot.json (5 hunks)
  • apps/notifications/drizzle/meta/0001_snapshot.json (0 hunks)
  • apps/notifications/drizzle/meta/0002_snapshot.json (0 hunks)
  • apps/notifications/drizzle/meta/0003_snapshot.json (0 hunks)
  • apps/notifications/drizzle/meta/_journal.json (1 hunks)
  • apps/notifications/src/interfaces/alert-events/handlers/chain-events/chain-events.handler.spec.ts (3 hunks)
  • apps/notifications/src/interfaces/alert-events/handlers/chain-events/chain-events.handler.ts (2 hunks)
  • apps/notifications/src/interfaces/rest/controllers/raw-alert/alert.controller.spec.ts (1 hunks)
  • apps/notifications/src/interfaces/rest/controllers/raw-alert/alert.controller.ts (1 hunks)
  • apps/notifications/src/interfaces/rest/controllers/raw-alert/raw-alert.controller.ts (0 hunks)
  • apps/notifications/src/interfaces/rest/http-schemas/alert.http-schema.ts (1 hunks)
  • apps/notifications/src/interfaces/rest/rest.module.ts (1 hunks)
  • apps/notifications/src/main.ts (1 hunks)
  • apps/notifications/src/modules/alert/alert.module.ts (1 hunks)
  • apps/notifications/src/modules/alert/model-schemas/alert-base.schema.ts (0 hunks)
  • apps/notifications/src/modules/alert/model-schemas/alert.schema.ts (1 hunks)
  • apps/notifications/src/modules/alert/model-schemas/deployment-balance-alert.schema.ts (0 hunks)
  • apps/notifications/src/modules/alert/model-schemas/index.ts (1 hunks)
  • apps/notifications/src/modules/alert/model-schemas/raw-alert.schema.ts (0 hunks)
  • apps/notifications/src/modules/alert/repositories/alert/alert-json-fields.schema.ts (1 hunks)
  • apps/notifications/src/modules/alert/repositories/alert/alert.repository.ts (1 hunks)
  • apps/notifications/src/modules/alert/repositories/deployment-balance-alert/deployment-balance-alert.repository.ts (0 hunks)
  • apps/notifications/src/modules/alert/repositories/raw-alert/raw-alert.repository.ts (0 hunks)
  • apps/notifications/src/modules/alert/services/chain-message-alert/chain-message-alert.service.spec.ts (12 hunks)
  • apps/notifications/src/modules/alert/services/chain-message-alert/chain-message-alert.service.ts (2 hunks)
  • apps/notifications/src/modules/alert/services/deployment-balance-alerts/deployment-balance-alerts.service.spec.ts (11 hunks)
  • apps/notifications/src/modules/alert/services/deployment-balance-alerts/deployment-balance-alerts.service.ts (5 hunks)
  • apps/notifications/test/functional/alert-crud.spec.ts (3 hunks)
  • apps/notifications/test/functional/balance-alert.spec.ts (2 hunks)
  • apps/notifications/test/functional/chain-message-alert.spec.ts (4 hunks)
  • apps/notifications/test/seeders/akash-address.seeder.ts (1 hunks)
  • apps/notifications/test/seeders/chain-message-alert.seeder.ts (2 hunks)
  • apps/notifications/test/seeders/deployment-balance-alert.seeder.ts (3 hunks)
  • packages/http-sdk/src/deployment/deployment-http.service.ts (1 hunks)
💤 Files with no reviewable changes (13)
  • apps/notifications/src/modules/alert/model-schemas/raw-alert.schema.ts
  • apps/notifications/drizzle/0001_foamy_amazoness.sql
  • apps/notifications/drizzle/0002_tiresome_power_man.sql
  • apps/notifications/src/modules/alert/model-schemas/deployment-balance-alert.schema.ts
  • apps/notifications/src/modules/alert/model-schemas/alert-base.schema.ts
  • apps/notifications/src/interfaces/rest/controllers/raw-alert/raw-alert.controller.ts
  • apps/notifications/drizzle/0000_cultured_kingpin.sql
  • apps/notifications/drizzle/0003_regular_ezekiel.sql
  • apps/notifications/drizzle/meta/0002_snapshot.json
  • apps/notifications/src/modules/alert/repositories/raw-alert/raw-alert.repository.ts
  • apps/notifications/src/modules/alert/repositories/deployment-balance-alert/deployment-balance-alert.repository.ts
  • apps/notifications/drizzle/meta/0003_snapshot.json
  • apps/notifications/drizzle/meta/0001_snapshot.json
🚧 Files skipped from review as they are similar to previous changes (26)
  • apps/notifications/drizzle.config.ts
  • apps/notifications/drizzle/meta/_journal.json
  • apps/notifications/test/functional/chain-message-alert.spec.ts
  • apps/notifications/src/modules/alert/alert.module.ts
  • apps/notifications/test/seeders/akash-address.seeder.ts
  • apps/notifications/src/interfaces/rest/rest.module.ts
  • apps/notifications/src/interfaces/alert-events/handlers/chain-events/chain-events.handler.ts
  • apps/notifications/src/modules/alert/model-schemas/index.ts
  • apps/notifications/src/interfaces/alert-events/handlers/chain-events/chain-events.handler.spec.ts
  • apps/notifications/test/functional/balance-alert.spec.ts
  • packages/http-sdk/src/deployment/deployment-http.service.ts
  • apps/notifications/src/main.ts
  • apps/notifications/test/seeders/chain-message-alert.seeder.ts
  • apps/notifications/src/interfaces/rest/controllers/raw-alert/alert.controller.spec.ts
  • apps/notifications/src/modules/alert/model-schemas/alert.schema.ts
  • apps/notifications/src/modules/alert/services/deployment-balance-alerts/deployment-balance-alerts.service.ts
  • apps/notifications/src/modules/alert/repositories/alert/alert.repository.ts
  • apps/notifications/test/seeders/deployment-balance-alert.seeder.ts
  • apps/notifications/src/modules/alert/services/deployment-balance-alerts/deployment-balance-alerts.service.spec.ts
  • apps/notifications/test/functional/alert-crud.spec.ts
  • apps/notifications/src/modules/alert/repositories/alert/alert-json-fields.schema.ts
  • apps/notifications/src/modules/alert/services/chain-message-alert/chain-message-alert.service.ts
  • apps/notifications/src/modules/alert/services/chain-message-alert/chain-message-alert.service.spec.ts
  • apps/notifications/src/interfaces/rest/controllers/raw-alert/alert.controller.ts
  • apps/notifications/drizzle/0000_striped_vin_gonzales.sql
  • apps/notifications/src/interfaces/rest/http-schemas/alert.http-schema.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: validate-api
  • GitHub Check: validate-notifications
  • GitHub Check: test-deploy-web-build
🔇 Additional comments (3)
apps/notifications/drizzle/meta/0000_snapshot.json (3)

2-5: Verify migration snapshot version alignment.
The version is bumped to "7" and the snapshot id changed—please confirm these values match your newest migration files and ordering to avoid drift in schema versioning.


181-220: Block_cursor table design looks solid.
Use of a single-row primary key (id = 'latest') plus timestamped last_processed_block effectively tracks state. No changes needed here.


223-246: Validate enum coverage for alert and contact point types.
Make sure public.alert_type and public.alert_status include all runtime values your code handles, and confirm public.contact_point_type covers every contact channel (e.g. SMS, webhook) if those are supported.

@ygrishajev ygrishajev force-pushed the feature/notifications branch from bf4abd4 to ebf7e6e Compare May 14, 2025 16:00
@ygrishajev ygrishajev merged commit fd738d6 into main May 15, 2025
8 checks passed
@ygrishajev ygrishajev deleted the feature/notifications branch May 15, 2025 07:12
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

Comments