Skip to content

feat: make saveLastProcessedEvent part of transaction #60

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 10, 2025

Conversation

0xnigir1
Copy link
Collaborator

@0xnigir1 0xnigir1 commented Jan 27, 2025

🤖 Linear

Closes GIT-232

Description

We want to make last processed event part of the transaction on the happy path, so we increase reliability and error handling of the system.
For this we are:

  • deprecating the InMemoryCache of EventRegistry
  • work directly with IEventRegistryRepository implementations
  • add optional txConnection to saveLastProcessedEvent method

Checklist before requesting a review

  • I have conducted a self-review of my code.
  • I have conducted a QA.
  • If it is a core feature, I have included comprehensive tests.

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced event registry handling with improved transaction support.
    • Added new processed event changeset type for more flexible event management.
    • Introduced processed event handlers for managing application-related operations.
  • Improvements

    • Simplified event processing logic in orchestrators.
    • Updated data loader to support more comprehensive event handling.
    • Improved error handling for event processing workflows.
  • Technical Updates

    • Refactored event registry interfaces and implementations.
    • Updated type definitions for better type safety and flexibility.
    • Expanded test coverage for processed event handlers and orchestrator functionalities.

Copy link

linear bot commented Jan 27, 2025

Copy link

coderabbitai bot commented Jan 27, 2025

📝 Walkthrough

Walkthrough

The pull request introduces a comprehensive refactoring of event registry handling across multiple packages in the project. The changes focus on replacing the in-memory cached event registry with a direct database-backed event registry implementation.

Key modifications include updating the ProcessingService, Orchestrator, and RetroactiveProcessor to use the new IEventRegistryRepository interface. A new ProcessedEventChangeset type is introduced to handle processed event operations, and the DataLoader is enhanced to incorporate event registry functionality.

The changes streamline event processing by removing the caching layer and providing more flexible transaction handling. The modifications span several packages, including data-flow, repository, and processing services, with updates to interfaces, repositories, and type definitions to support the new event registry approach.

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (4)
packages/data-flow/src/orchestrator.ts (2)

Line range hint 99-121: Consider aligning property naming for consistency.
Within the constructor, you define eventsRegistry: IEventRegistryRepository but use eventRegistry in the DataLoader configuration. Consider keeping the naming consistent to avoid confusion:

-                eventRegistry: this.eventsRegistry,
+                eventsRegistry: this.eventsRegistry,

157-172: Apply changesets efficiently.
The logic to apply changesets and then insert the processed event is clear. As a small optimization, consider directly pushing the InsertProcessedEvent changeset to the array before calling applyChanges. This slightly reduces the spread operation overhead in tight loops.

const changesets = await this.handleEvent(event!);
if (changesets) {
+    changesets.push({
+        type: "InsertProcessedEvent",
+        args: {
+            chainId: this.chainId,
+            processedEvent: {
+                ...event!,
+                rawEvent: event
+            },
+        },
+    });
    await this.dataLoader.applyChanges(changesets);
}
packages/data-flow/src/data-loader/handlers/processedEvent.handlers.ts (1)

8-14: Enhance JSDoc comments for ProcessedEventHandlers type.

The current JSDoc comment incorrectly refers to "Application" operations instead of "ProcessedEvent" operations.

 /**
- * Collection of handlers for application-related operations.
- * Each handler corresponds to a specific Application changeset type.
+ * Collection of handlers for processed event operations.
+ * Each handler corresponds to a specific ProcessedEvent changeset type.
+ * @template K - The type of ProcessedEventChangeset
  */
packages/data-flow/src/retroactiveProcessor.ts (1)

Line range hint 71-81: Update JSDoc for constructor parameters.

The JSDoc for the registries parameter should be updated to reflect that eventsRegistry is now of type IEventRegistryRepository.

 * @param registries - Event and strategy registries for tracking processing state
+ * @param registries.eventsRegistry - Repository for managing processed events
 * @param registries.strategyRegistry - Registry for tracking strategy processing state
 * @param registries.checkpointRepository - Repository for managing processing checkpoints
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2494cb6 and 37b42cb.

📒 Files selected for processing (11)
  • apps/processing/src/services/processing.service.ts (2 hunks)
  • packages/data-flow/src/data-loader/dataLoader.ts (4 hunks)
  • packages/data-flow/src/data-loader/handlers/index.ts (1 hunks)
  • packages/data-flow/src/data-loader/handlers/processedEvent.handlers.ts (1 hunks)
  • packages/data-flow/src/orchestrator.ts (8 hunks)
  • packages/data-flow/src/retroactiveProcessor.ts (4 hunks)
  • packages/data-flow/test/data-loader/dataLoader.spec.ts (3 hunks)
  • packages/repository/src/external.ts (1 hunks)
  • packages/repository/src/interfaces/eventsRepository.interface.ts (2 hunks)
  • packages/repository/src/repositories/kysely/eventRegistry.repository.ts (2 hunks)
  • packages/repository/src/types/changeset.types.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
packages/data-flow/src/data-loader/handlers/index.ts (1)

Pattern **/*.ts: Review TypeScript files for adherence to the following guidelines:
- Avoid over-abstraction; prioritize composition over inheritance.
- Use dependency injection and follow SOLID principles.
- Avoid any; use unknown when necessary.
- Use runtime type-checking for environment variables (e.g., Zod).
- Prevent circular dependencies with the internal module pattern.
- Libraries should have an external.ts file explicitly listing public exports.
- Use bigint as-is; cast to Number only when exposing values via APIs.
- Document all code with JSDoc.
- Encourage static async factory functions for constructors.

  • Avoid overly nitpicky feedback beyond these best practices.
packages/repository/src/external.ts (1)

Pattern **/*.ts: Review TypeScript files for adherence to the following guidelines:
- Avoid over-abstraction; prioritize composition over inheritance.
- Use dependency injection and follow SOLID principles.
- Avoid any; use unknown when necessary.
- Use runtime type-checking for environment variables (e.g., Zod).
- Prevent circular dependencies with the internal module pattern.
- Libraries should have an external.ts file explicitly listing public exports.
- Use bigint as-is; cast to Number only when exposing values via APIs.
- Document all code with JSDoc.
- Encourage static async factory functions for constructors.

  • Avoid overly nitpicky feedback beyond these best practices.
packages/repository/src/types/changeset.types.ts (1)

Pattern **/*.ts: Review TypeScript files for adherence to the following guidelines:
- Avoid over-abstraction; prioritize composition over inheritance.
- Use dependency injection and follow SOLID principles.
- Avoid any; use unknown when necessary.
- Use runtime type-checking for environment variables (e.g., Zod).
- Prevent circular dependencies with the internal module pattern.
- Libraries should have an external.ts file explicitly listing public exports.
- Use bigint as-is; cast to Number only when exposing values via APIs.
- Document all code with JSDoc.
- Encourage static async factory functions for constructors.

  • Avoid overly nitpicky feedback beyond these best practices.
packages/data-flow/test/data-loader/dataLoader.spec.ts (2)

Pattern **/*.ts: Review TypeScript files for adherence to the following guidelines:
- Avoid over-abstraction; prioritize composition over inheritance.
- Use dependency injection and follow SOLID principles.
- Avoid any; use unknown when necessary.
- Use runtime type-checking for environment variables (e.g., Zod).
- Prevent circular dependencies with the internal module pattern.
- Libraries should have an external.ts file explicitly listing public exports.
- Use bigint as-is; cast to Number only when exposing values via APIs.
- Document all code with JSDoc.
- Encourage static async factory functions for constructors.

  • Avoid overly nitpicky feedback beyond these best practices.

Pattern **/*.spec.ts: Review the unit test files with the following guidelines:
- Avoid using the word "should" in test descriptions.
- Ensure descriptive test names convey the intent of each test.
- Validate adherence to the Mocha/Chai/Jest test library best practices.

  • Be concise and avoid overly nitpicky feedback outside of these best practices.
apps/processing/src/services/processing.service.ts (2)

Pattern **/*.ts: Review TypeScript files for adherence to the following guidelines:
- Avoid over-abstraction; prioritize composition over inheritance.
- Use dependency injection and follow SOLID principles.
- Avoid any; use unknown when necessary.
- Use runtime type-checking for environment variables (e.g., Zod).
- Prevent circular dependencies with the internal module pattern.
- Libraries should have an external.ts file explicitly listing public exports.
- Use bigint as-is; cast to Number only when exposing values via APIs.
- Document all code with JSDoc.
- Encourage static async factory functions for constructors.

  • Avoid overly nitpicky feedback beyond these best practices.

Pattern **/services/**/*.ts: Review service files with the following considerations:
- A Service encapsulates a broader business workflow and might orchestrate various components or interact with multiple data sources or APIs.
- Ensure proper composability: Services should use Providers for data/resource access and apply business/orchestration logic.
- Validate naming conventions for aggregating services (e.g., AggregatorService or domain-specific names like MetricsService).
- path: "/providers//*.ts"
instructions: |
Review provider files for the following:
- Providers should supply narrowly scoped data/resources.
- Ensure classes interacting with metadata sources (e.g., GitHub, JSON files, IPFS) implement the IMetadataProvider interface and follow naming conventions (e.g., GithubProvider, JsonFileProvider).

  • Be concise and avoid overly nitpicky feedback outside of these best practices.
packages/data-flow/src/data-loader/dataLoader.ts (1)

Pattern **/*.ts: Review TypeScript files for adherence to the following guidelines:
- Avoid over-abstraction; prioritize composition over inheritance.
- Use dependency injection and follow SOLID principles.
- Avoid any; use unknown when necessary.
- Use runtime type-checking for environment variables (e.g., Zod).
- Prevent circular dependencies with the internal module pattern.
- Libraries should have an external.ts file explicitly listing public exports.
- Use bigint as-is; cast to Number only when exposing values via APIs.
- Document all code with JSDoc.
- Encourage static async factory functions for constructors.

  • Avoid overly nitpicky feedback beyond these best practices.
packages/repository/src/interfaces/eventsRepository.interface.ts (1)

Pattern **/*.ts: Review TypeScript files for adherence to the following guidelines:
- Avoid over-abstraction; prioritize composition over inheritance.
- Use dependency injection and follow SOLID principles.
- Avoid any; use unknown when necessary.
- Use runtime type-checking for environment variables (e.g., Zod).
- Prevent circular dependencies with the internal module pattern.
- Libraries should have an external.ts file explicitly listing public exports.
- Use bigint as-is; cast to Number only when exposing values via APIs.
- Document all code with JSDoc.
- Encourage static async factory functions for constructors.

  • Avoid overly nitpicky feedback beyond these best practices.
packages/data-flow/src/data-loader/handlers/processedEvent.handlers.ts (1)

Pattern **/*.ts: Review TypeScript files for adherence to the following guidelines:
- Avoid over-abstraction; prioritize composition over inheritance.
- Use dependency injection and follow SOLID principles.
- Avoid any; use unknown when necessary.
- Use runtime type-checking for environment variables (e.g., Zod).
- Prevent circular dependencies with the internal module pattern.
- Libraries should have an external.ts file explicitly listing public exports.
- Use bigint as-is; cast to Number only when exposing values via APIs.
- Document all code with JSDoc.
- Encourage static async factory functions for constructors.

  • Avoid overly nitpicky feedback beyond these best practices.
packages/repository/src/repositories/kysely/eventRegistry.repository.ts (1)

Pattern **/*.ts: Review TypeScript files for adherence to the following guidelines:
- Avoid over-abstraction; prioritize composition over inheritance.
- Use dependency injection and follow SOLID principles.
- Avoid any; use unknown when necessary.
- Use runtime type-checking for environment variables (e.g., Zod).
- Prevent circular dependencies with the internal module pattern.
- Libraries should have an external.ts file explicitly listing public exports.
- Use bigint as-is; cast to Number only when exposing values via APIs.
- Document all code with JSDoc.
- Encourage static async factory functions for constructors.

  • Avoid overly nitpicky feedback beyond these best practices.
packages/data-flow/src/orchestrator.ts (1)

Pattern **/*.ts: Review TypeScript files for adherence to the following guidelines:
- Avoid over-abstraction; prioritize composition over inheritance.
- Use dependency injection and follow SOLID principles.
- Avoid any; use unknown when necessary.
- Use runtime type-checking for environment variables (e.g., Zod).
- Prevent circular dependencies with the internal module pattern.
- Libraries should have an external.ts file explicitly listing public exports.
- Use bigint as-is; cast to Number only when exposing values via APIs.
- Document all code with JSDoc.
- Encourage static async factory functions for constructors.

  • Avoid overly nitpicky feedback beyond these best practices.
packages/data-flow/src/retroactiveProcessor.ts (1)

Pattern **/*.ts: Review TypeScript files for adherence to the following guidelines:
- Avoid over-abstraction; prioritize composition over inheritance.
- Use dependency injection and follow SOLID principles.
- Avoid any; use unknown when necessary.
- Use runtime type-checking for environment variables (e.g., Zod).
- Prevent circular dependencies with the internal module pattern.
- Libraries should have an external.ts file explicitly listing public exports.
- Use bigint as-is; cast to Number only when exposing values via APIs.
- Document all code with JSDoc.
- Encourage static async factory functions for constructors.

  • Avoid overly nitpicky feedback beyond these best practices.
🔇 Additional comments (19)
packages/data-flow/src/orchestrator.ts (7)

10-15: Imports look consistent and aligned with the new repository usage.
No concerns with the updated import statements for Changeset, IEventRegistryRepository, RoundNotFound, and RoundNotFoundForId.


37-37: Type imports are properly declared.
The usage of IEventsFetcher and IStrategyRegistry via type imports is correct and follows best practices.


80-80: Field declaration is consistent with the new interface.
Declaring private readonly eventsRegistry: IEventRegistryRepository; aligns with the updated repository-based approach. This is clear and maintains strong typing.


428-430: Return type provides flexibility.
Shifting from Promise<void> to Promise<Changeset[] | undefined> is consistent with storing processed changes downstream. This improves clarity and data flow orchestration.


448-448: Skipping unsupported strategy events.
Returning undefined here clearly indicates no changesets are generated for unrecognized strategy IDs.


452-452: Forwarding events to the processor.
The direct return of this.eventsProcessor.processEvent(event); is straightforward and maintains a clean separation of concerns between Orchestrator logic and event processing.


177-182: Verify partial-processing intent.
Saving the last processed event on error can skip a non-fully-processed event. Confirm if marking this event as processed is intended when an error occurs, as it may lead to data inconsistencies.

✅ Verification successful

Partial-processing behavior is intentional and correct
The current implementation correctly saves the last processed event to maintain processing order and prevent infinite loops on failed events. This is a standard pattern in event processing systems where progress tracking is separate from success/failure handling. The behavior is well-tested and changing it could lead to processing getting stuck.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify usage of saveLastProcessedEvent across the codebase
# to confirm partial-processing is intentional
rg -A 5 'saveLastProcessedEvent'

Length of output: 21701

packages/data-flow/src/data-loader/handlers/index.ts (1)

6-6: Exporting processed event handlers for a clearer API surface.
Exporting from processedEvent.handlers.js centralizes handler definitions and improves discoverability.

packages/repository/src/interfaces/eventsRepository.interface.ts (3)

3-3: Importing extended types for improved repository functionality.
Including TransactionConnection fosters type-safe transaction support across the repository layer.


5-7: Generic interface extension ensures flexible transaction handling.
Defining <TxConnection extends TransactionConnection = TransactionConnection> is a good pattern for extending or customizing transaction types in different environments.


20-24: Optional txConnection for transactional operations.
Allowing an optional txConnection parameter aligns with the PR’s goal of integrating last processed events into transactions without mandating it in all cases.

packages/data-flow/src/data-loader/handlers/processedEvent.handlers.ts (1)

22-32: Well-structured handler implementation with proper type safety!

The implementation is clean, type-safe, and follows dependency injection principles. Good use of the satisfies operator to ensure type compatibility.

packages/repository/src/repositories/kysely/eventRegistry.repository.ts (1)

Line range hint 31-57: Clean implementation of transaction support!

The changes effectively integrate transaction support while maintaining existing functionality:

  • Good use of TypeScript generics for transaction typing
  • Clean pattern for fallback to this.db when no transaction is provided
  • Comprehensive error handling with proper context
packages/repository/src/external.ts (1)

51-51: Clean addition of ProcessedEventChangeset export.

The export follows the established pattern and TypeScript guidelines for explicit public exports.

packages/data-flow/src/data-loader/dataLoader.ts (2)

Line range hint 77-77: Consider implementing Zod validation as mentioned in TODO.

The TODO comment suggests adding Zod validation for changeset args. This aligns with the TypeScript guidelines about runtime type-checking and would enhance type safety.

Would you like me to help implement the Zod validation schema for the ProcessedEventChangeset args?


Line range hint 46-59: Clean integration of event registry and handlers!

The changes effectively integrate the event registry:

  • Follows dependency injection pattern
  • Clean integration of new handlers
  • Maintains consistent structure with other repositories
packages/repository/src/types/changeset.types.ts (1)

170-176: LGTM! ProcessedEventChangeset type is well-defined.

The type follows the established changeset pattern and includes all necessary fields for tracking processed events.

apps/processing/src/services/processing.service.ts (1)

80-82: LGTM! Successfully removed InMemoryCache dependency.

The changes correctly implement direct usage of DatabaseEventRegistry, simplifying the event handling flow while maintaining proper dependency injection.

Also applies to: 93-96

packages/data-flow/src/retroactiveProcessor.ts (1)

65-65: LGTM! Type declarations properly updated.

The changes correctly update the event registry types and maintain proper dependency injection throughout the class.

Also applies to: 86-86, 109-109

Comment on lines +45 to +47
const mockEventRegistryRepository = {
saveLastProcessedEvent: vi.fn(),
} as unknown as IEventRegistryRepository;
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Add test cases for ProcessedEventChangeset handling in dataLoader.spec.ts

The review comment is valid. While saveLastProcessedEvent is mocked in the test file, there are no specific test cases verifying the DataLoader's handling of ProcessedEventChangeset. The handler implementation exists in processedEvent.handlers.ts, but its behavior needs to be tested.

Suggested test cases to add:

  • Successful processing of InsertProcessedEvent changeset
  • Error handling during event processing
  • Transaction handling with the repository
🔗 Analysis chain

Add test cases for ProcessedEventChangeset handling.

While the mock is correctly set up, there are no test cases verifying the behavior of saveLastProcessedEvent. Consider adding test cases for:

  • Successful processing of InsertProcessedEvent changeset
  • Error handling during event processing
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if there are any test cases for ProcessedEventChangeset
rg -A 5 "InsertProcessedEvent" "packages/data-flow/test/**/*.spec.ts"

Length of output: 146


Script:

#!/bin/bash
# Search for test files and relevant patterns
echo "=== Searching for saveLastProcessedEvent tests ==="
rg -A 5 "saveLastProcessedEvent" --type ts

echo -e "\n=== Searching for ProcessedEventChangeset tests ==="
rg -A 5 "ProcessedEventChangeset" --type ts

echo -e "\n=== Looking for related test files ==="
fd "dataLoader.spec.ts"

Length of output: 24168

@0xnigir1 0xnigir1 marked this pull request as ready for review February 6, 2025 15:22
@0xnigir1 0xnigir1 self-assigned this Feb 6, 2025
@0xnigir1 0xnigir1 changed the title feat(wip): make saveLastProcessedEvent part of transaction feat: make saveLastProcessedEvent part of transaction Feb 6, 2025
@0xnigir1
Copy link
Collaborator Author

0xnigir1 commented Feb 6, 2025

@coderabbitai full review

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (1)
packages/data-flow/src/orchestrator.ts (1)

475-476: Add error handling for missing strategyId after enhancement

After enhancing the event with strategyId, it's possible that strategyId may still be undefined if the strategy is not found. Consider adding error handling to manage this scenario gracefully.

Add a check for strategyId and handle accordingly:

 event.strategyId = strategyId;

+if (!event.strategyId) {
+    throw new Error(`Strategy ID could not be determined for strategy address ${strategyAddress}`);
+}

 return event;
🧹 Nitpick comments (5)
packages/repository/src/repositories/kysely/eventRegistry.repository.ts (2)

14-18: Add JSDoc comments to the class and constructor

To adhere to the project's coding guidelines and improve code documentation, please add JSDoc comments to the KyselyEventRegistryRepository class and its constructor. This will enhance maintainability and help other developers understand the purpose and usage of the class.

Here is a suggested addition:

+/**
+ * Repository for managing the events registry using Kysely.
+ */
 export class KyselyEventRegistryRepository implements IEventRegistryRepository<KyselyTransaction> {
     constructor(
         private readonly db: Kysely<Database>,
         private readonly schemaName: string,
+    ) {
+        /**
+         * Creates an instance of KyselyEventRegistryRepository.
+         * @param db - The Kysely database instance.
+         * @param schemaName - The schema name to use.
+         */
+    }
 }

31-35: Document the saveLastProcessedEvent method with JSDoc

The saveLastProcessedEvent method is missing JSDoc comments. Adding documentation will clarify the method's purpose, parameters, and usage, aligning with the coding guidelines.

Here is a suggested addition:

+    /**
+     * Saves the last processed event for a specific chain.
+     * @param chainId - The chain ID.
+     * @param event - The new processed event to save.
+     * @param txConnection - Optional transaction connection for the operation.
+     */
     async saveLastProcessedEvent(
         chainId: ChainId,
         event: NewProcessedEvent,
         txConnection?: KyselyTransaction,
     ): Promise<void> {
packages/data-flow/src/data-loader/dataLoader.ts (1)

41-60: Add JSDoc comments to the constructor and handlers mapping

The constructor and the handlers mapping within the DataLoader class lack documentation. Adding JSDoc comments will improve code readability and help others understand the dependencies and the purpose of the handlers.

Suggested addition:

     constructor(
         private readonly repositories: {
             project: IProjectRepository;
             round: IRoundRepository;
             application: IApplicationRepository;
             donation: IDonationRepository;
             applicationPayout: IApplicationPayoutRepository;
+            /**
+             * Repository for managing event registry.
+             */
             eventRegistry: IEventRegistryRepository;
         },
         private readonly transactionManager: ITransactionManager,
         private readonly logger: ILogger,
     ) {
+        /**
+         * Mapping of changeset types to their corresponding handler functions.
+         */
         this.handlers = {
             ...createProjectHandlers(repositories.project),
             ...createRoundHandlers(repositories.round),
             ...createApplicationHandlers(repositories.application),
             ...createDonationHandlers(repositories.donation),
             ...createApplicationPayoutHandlers(repositories.applicationPayout),
             ...createProcessedEventHandlers(repositories.eventRegistry),
         };
     }
packages/data-flow/src/orchestrator.ts (1)

428-453: Clarify the return value of handleEvent when skipping events

The handleEvent method returns undefined when an event is skipped due to an unsupported strategy ID. Ensure that the calling code properly handles this case to prevent unexpected behavior.

Consider explicitly checking for undefined and documenting the behavior:

 return this.retryHandler.execute(
     async () => {
         const changesets = await this.handleEvent(event);
         if (changesets && changesets.length > 0) {
             await this.dataLoader.applyChanges([
                 ...changesets,
                 {
                     type: "InsertProcessedEvent",
                     args: {
                         chainId: this.chainId,
                         processedEvent: {
                             ...event,
                             rawEvent: event,
                         },
                     },
                 },
             ]);
-        }
+        } else {
+            this.logger.debug("No changesets returned from handleEvent", {
+                event,
+                className: Orchestrator.name,
+                chainId: this.chainId,
+            });
+        }
     },
     { abortSignal: signal },
 );
packages/data-flow/test/unit/orchestrator.spec.ts (1)

253-278: Avoid duplication in error handling tests

In the test "saves event outside transaction when processing fails" (lines 253-278), consider refactoring common setup code shared with other tests to improve maintainability and reduce duplication.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2494cb6 and ad76488.

📒 Files selected for processing (14)
  • apps/processing/src/services/processing.service.ts (2 hunks)
  • apps/processing/test/unit/processing.service.spec.ts (0 hunks)
  • packages/data-flow/src/data-loader/dataLoader.ts (4 hunks)
  • packages/data-flow/src/data-loader/handlers/index.ts (1 hunks)
  • packages/data-flow/src/data-loader/handlers/processedEvent.handlers.ts (1 hunks)
  • packages/data-flow/src/orchestrator.ts (8 hunks)
  • packages/data-flow/src/retroactiveProcessor.ts (4 hunks)
  • packages/data-flow/test/data-loader/dataLoader.spec.ts (3 hunks)
  • packages/data-flow/test/data-loader/handlers/processedEvent.handlers.spec.ts (1 hunks)
  • packages/data-flow/test/unit/orchestrator.spec.ts (9 hunks)
  • packages/repository/src/external.ts (1 hunks)
  • packages/repository/src/interfaces/eventsRepository.interface.ts (2 hunks)
  • packages/repository/src/repositories/kysely/eventRegistry.repository.ts (2 hunks)
  • packages/repository/src/types/changeset.types.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • apps/processing/test/unit/processing.service.spec.ts
🧰 Additional context used
📓 Path-based instructions (3)
`**/*.ts`: Review TypeScript files for adherence to the fo...

**/*.ts: Review TypeScript files for adherence to the following guidelines:
- Avoid over-abstraction; prioritize composition over inheritance.
- Use dependency injection and follow SOLID principles.
- Avoid any; use unknown when necessary.
- Use runtime type-checking for environment variables (e.g., Zod).
- Prevent circular dependencies with the internal module pattern.
- Libraries should have an external.ts file explicitly listing public exports.
- Use bigint as-is; cast to Number only when exposing values via APIs.
- Document all code with JSDoc.
- Encourage static async factory functions for constructors.

  • Avoid overly nitpicky feedback beyond these best practices.
  • packages/repository/src/external.ts
  • packages/data-flow/src/data-loader/handlers/index.ts
  • apps/processing/src/services/processing.service.ts
  • packages/data-flow/src/data-loader/dataLoader.ts
  • packages/repository/src/types/changeset.types.ts
  • packages/data-flow/src/data-loader/handlers/processedEvent.handlers.ts
  • packages/data-flow/test/unit/orchestrator.spec.ts
  • packages/data-flow/test/data-loader/handlers/processedEvent.handlers.spec.ts
  • packages/repository/src/interfaces/eventsRepository.interface.ts
  • packages/repository/src/repositories/kysely/eventRegistry.repository.ts
  • packages/data-flow/test/data-loader/dataLoader.spec.ts
  • packages/data-flow/src/orchestrator.ts
  • packages/data-flow/src/retroactiveProcessor.ts
`**/services/**/*.ts`: Review service files with the followi...

**/services/**/*.ts: Review service files with the following considerations:
- A Service encapsulates a broader business workflow and might orchestrate various components or interact with multiple data sources or APIs.
- Ensure proper composability: Services should use Providers for data/resource access and apply business/orchestration logic.
- Validate naming conventions for aggregating services (e.g., AggregatorService or domain-specific names like MetricsService).

  • apps/processing/src/services/processing.service.ts
`**/*.spec.ts`: Review the unit test files with the followin...

**/*.spec.ts: Review the unit test files with the following guidelines:
- Avoid using the word "should" in test descriptions.
- Ensure descriptive test names convey the intent of each test.
- Validate adherence to the Mocha/Chai/Jest test library best practices.

  • Be concise and avoid overly nitpicky feedback outside of these best practices.
  • packages/data-flow/test/unit/orchestrator.spec.ts
  • packages/data-flow/test/data-loader/handlers/processedEvent.handlers.spec.ts
  • packages/data-flow/test/data-loader/dataLoader.spec.ts
🔇 Additional comments (29)
packages/repository/src/repositories/kysely/eventRegistry.repository.ts (1)

38-51: Ensure consistent use of transactions in database operations

While the optional txConnection parameter allows for transactional operations, it's important to ensure that all database interactions within the method respect the transaction context. Verify that any additional queries or operations within this method or future extensions use txConnection || this.db consistently to maintain transactional integrity.

packages/data-flow/src/data-loader/dataLoader.ts (1)

58-58: Confirm that the createProcessedEventHandlers function is correctly integrated

Verify that the createProcessedEventHandlers function from processedEvent.handlers.js is properly imported and integrated into the handlers mapping. Ensure that it correctly registers the necessary handlers for processing events.

packages/data-flow/src/orchestrator.ts (2)

80-82: Update the eventsRegistry type to match new interface

The type of eventsRegistry is changed from IEventsRegistry to IEventRegistryRepository. Ensure that all method calls and properties accessed on eventsRegistry are compatible with the new interface.


178-182: Ensure saveLastProcessedEvent correctly handles errors

In the catch block, the code attempts to save the last processed event even when an error occurs. Confirm that this behavior is intentional and does not result in inconsistent state, especially if the error is due to issues with the event data.

packages/data-flow/test/unit/orchestrator.spec.ts (10)

13-13: Approve addition of IEventRegistryRepository import

The import of IEventRegistryRepository at line 13 correctly brings in the necessary interface for the updated event registry usage in the tests.


18-18: Approve addition of RoundNotFoundForId import

Including RoundNotFoundForId in the imports allows the test suite to handle specific error cases related to rounds not found by ID.


39-39: Update import to include InvalidEvent

The import statement now includes InvalidEvent, which is required for handling and testing invalid event scenarios within the orchestrator.


63-63: Update mock to use IEventRegistryRepository

Changing mockEventsRegistry to type IEventRegistryRepository ensures consistency with the updated interface and allows for accurate mocking of event registry behavior.


188-189: Verify that applyChanges is called the correct number of times

The assertion at line 188 checks that applyChanges is called twice, which aligns with the two events being processed. The additional assertion at line 189 confirms that saveLastProcessedEvent is not called directly, ensuring that event saving is handled within the transaction.


212-251: Ensure test descriptions are clear and precise

The test case "includes InsertProcessedEvent changeset in transaction" (lines 212-251) clearly conveys the intent to check that the InsertProcessedEvent changeset is included within a transaction. The description aligns with best practices for test naming.


280-312: Approve transaction rollback test logic

The test "rolls back transaction on error" (lines 280-312) effectively verifies that the transaction is rolled back when an error occurs during applyChanges. The mock implementations and assertions accurately simulate and confirm the expected behavior.


375-377: Use expect.arrayContaining for flexible matching

The use of expect.arrayContaining(changesets) (lines 375-377) allows the test to verify that the expected changesets are included in the array without requiring an exact match of the entire array, improving test robustness.


494-516: Consistent inclusion of InsertProcessedEvent in changesets

In the tests starting at line 494, ensure that InsertProcessedEvent is correctly appended to the changesets when processing strategy events. This maintains consistency in how processed events are handled across different event types.


734-734: Correct verification of saveLastProcessedEvent call count

The assertion at line 734 confirms that saveLastProcessedEvent is called once, which is appropriate given the processing flow in the error handling test case.

packages/data-flow/src/data-loader/handlers/index.ts (1)

6-6: Include processedEvent.handlers.js in module exports

Adding export * from "./processedEvent.handlers.js"; ensures that the processedEvent handlers are exported and available for use, integrating the new handlers into the data loader module.

packages/repository/src/interfaces/eventsRepository.interface.ts (3)

3-3: Import TransactionConnection for transaction support

Including TransactionConnection in the imports (line 3) prepares the interface to handle transaction connections, which is necessary for the updated method signatures.


5-7: Enhance interface with generic TxConnection type parameter

Introducing a generic type parameter TxConnection (lines 5-7) to IEventRegistryRepository allows for greater flexibility in specifying the transaction connection type, adhering to SOLID principles.


20-24: Update saveLastProcessedEvent to accept optional transaction connection

Modifying the saveLastProcessedEvent method signature to include an optional txConnection parameter (lines 20-24) enables the method to participate in transactions when provided, enhancing the repository's transactional capabilities.

packages/data-flow/src/data-loader/handlers/processedEvent.handlers.ts (2)

12-14: LGTM! Well-structured type definition.

The use of mapped types ensures type safety and maintainability.


22-32: LGTM! Clean and type-safe implementation.

The implementation follows TypeScript best practices:

  • Uses dependency injection for the repository
  • Leverages the satisfies operator for type safety
  • Properly handles the optional transaction connection
packages/data-flow/test/data-loader/handlers/processedEvent.handlers.spec.ts (2)

18-41: LGTM! Comprehensive test for successful event saving.

The test properly verifies:

  • Repository method call with correct parameters
  • Transaction handling

43-67: LGTM! Thorough error handling test.

Good coverage of error propagation scenario.

packages/repository/src/external.ts (1)

51-51: LGTM! Consistent export pattern.

The new type export follows the established pattern for changeset types.

packages/repository/src/types/changeset.types.ts (3)

170-176: LGTM! Well-structured type definition.

The new ProcessedEventChangeset type follows the established pattern and includes all necessary fields.


178-184: LGTM! Proper type composition.

The Changeset union type is correctly updated to include the new ProcessedEventChangeset.


21-21: Consider addressing the TODO comment.

The comment suggests a potential refactoring of changeset types. Consider creating a tracking issue for this technical debt.

Would you like me to create an issue to track this refactoring task?

packages/data-flow/test/data-loader/dataLoader.spec.ts (1)

45-47: Add test cases for ProcessedEventChangeset handling.

While the mock is correctly set up, there are no test cases verifying the behavior of saveLastProcessedEvent. Consider adding test cases for:

  • Successful processing of InsertProcessedEvent changeset
  • Error handling during event processing
apps/processing/src/services/processing.service.ts (1)

80-81: LGTM! The changes improve reliability by removing the in-memory cache layer.

The direct use of DatabaseEventRegistry ensures data consistency and reduces complexity.

Also applies to: 93-94

packages/data-flow/src/retroactiveProcessor.ts (1)

65-65: LGTM! The changes are consistent with the new event registry interface.

The type changes from IEventsRegistry to IEventRegistryRepository are consistently applied across the class property, constructor parameter, and DataLoader integration.

Also applies to: 86-87, 109-110

Comment on lines +157 to 175
const changesets = await this.handleEvent(event!);
if (changesets) {
await this.dataLoader.applyChanges([
...changesets,
{
type: "InsertProcessedEvent",
args: {
chainId: this.chainId,
processedEvent: {
...event!,
rawEvent: event,
},
},
},
]);
}
},
{ abortSignal: signal },
);
Copy link

@coderabbitai coderabbitai bot Feb 6, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle potential null reference in event

There is a risk of a null or undefined reference when using event! in the async function passed to this.retryHandler.execute. Ensure that event is properly checked or handled to avoid runtime errors.

Apply this diff to add null checking:

 await this.retryHandler.execute(
     async () => {
-        const changesets = await this.handleEvent(event!);
+        if (!event) {
+            throw new Error("Event is undefined or null");
+        }
+        const changesets = await this.handleEvent(event);
         if (changesets) {
             await this.dataLoader.applyChanges([
                 ...changesets,
                 {
                     type: "InsertProcessedEvent",
                     args: {
                         chainId: this.chainId,
                         processedEvent: {
-                            ...event!,
+                            ...event,
                             rawEvent: event,
                         },
                     },
                 },
             ]);
         }
     },
     { abortSignal: signal },
 );
📝 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.

Suggested change
const changesets = await this.handleEvent(event!);
if (changesets) {
await this.dataLoader.applyChanges([
...changesets,
{
type: "InsertProcessedEvent",
args: {
chainId: this.chainId,
processedEvent: {
...event!,
rawEvent: event,
},
},
},
]);
}
},
{ abortSignal: signal },
);
await this.retryHandler.execute(
async () => {
if (!event) {
throw new Error("Event is undefined or null");
}
const changesets = await this.handleEvent(event);
if (changesets) {
await this.dataLoader.applyChanges([
...changesets,
{
type: "InsertProcessedEvent",
args: {
chainId: this.chainId,
processedEvent: {
...event,
rawEvent: event,
},
},
},
]);
}
},
{ abortSignal: signal },
);

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

look at the prior lines, if event is undefined or null, we continue the loop prior to the the retryHandler execute method. this doesn't need to be fixed

Copy link

Choose a reason for hiding this comment

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

@0xnigir1 You're absolutely right. I apologize for the unnecessary suggestion. The code already has a proper null check before the retryHandler.execute call, which ensures that event is never null or undefined at that point.


✏️ Learnings added
Learnt from: 0xnigir1
PR: defi-wonderland/grants-stack-indexer-v2#60
File: packages/data-flow/src/orchestrator.ts:157-175
Timestamp: 2025-02-06T15:32:39.661Z
Learning: In the Orchestrator class, when processing events in a loop, null checking is performed before the retryHandler.execute call. If the event is null/undefined, the loop continues, ensuring that event is always defined within the retry handler's execution block.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Copy link
Collaborator

@jahabeebs jahabeebs left a comment

Choose a reason for hiding this comment

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

great!

Copy link
Contributor

@0xkenj1 0xkenj1 left a comment

Choose a reason for hiding this comment

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

sweet

@0xnigir1 0xnigir1 merged commit 6ead1ef into dev Feb 10, 2025
7 checks passed
@0xnigir1 0xnigir1 deleted the feat/improve-event-checkpointing branch February 10, 2025 14:40
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.

3 participants