Skip to content

Unity native variables fetch #168

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 3 commits into from
Mar 27, 2025

Conversation

nzagorchev
Copy link
Contributor

@nzagorchev nzagorchev commented Mar 26, 2025

Overview

Implement Unity Native Variables Fetch. Trigger Variables Fetch callbacks.

Summary by CodeRabbit

  • New Features
    • Introduced enhanced variable fetching capabilities with improved event processing and callback tracking.
    • Standardized fetch event handling to ensure consistent processing and more robust data updates.
    • Added a new method for constructing fetch events with detailed properties.
  • Bug Fixes
    • Improved error handling for variable fetching to ensure platform variables are loaded correctly.

@nzagorchev nzagorchev requested a review from vasct March 26, 2025 17:23
Copy link

coderabbitai bot commented Mar 26, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This update adds support for fetching variables within the Unity native environment. A new private field is introduced to track a fetch callback ID, and the corresponding fetch logic is added and integrated into the event management system. New event constants and additional cases in the event builders and event queue enable the handling of a new "FetchEvent" type. Methods for constructing fetch events and processing them in the event manager have been added, with proper error handling in place when expected components are not available.

Changes

File(s) Change Summary
CleverTap/Runtime/Native/UnityNativePlatformVariable.cs, CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventManager.cs, CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventQueueManager.cs Added a fetch variables flow: Introduced fetchVariablesCallbackId and modified methods to assign callback IDs, added a new FetchVariables() method, and updated event queue processing to handle FetchEvent.
CleverTap/Runtime/Native/UnityNativeWrapper/Constants/UnityNativeConstants.cs Added new constants: EVENT_WZRK_FETCH and WZRK_FETCH_TYPE_VARIABLES to support the fetch event mechanism.
CleverTap/Runtime/Native/UnityNativeWrapper/EventBuilders/UnityNativeBaseEventBuilder.cs, CleverTap/Runtime/Native/UnityNativeWrapper/EventBuilders/UnityNativeRaisedEventBuilder.cs Enhanced event builders: Introduced a new switch case for FetchEvent in the event builder and added the BuildFetchEvent method to build an event dictionary for fetching variables.

Sequence Diagram(s)

sequenceDiagram
    participant UVP as UnityNativePlatformVariable
    participant UEM as UnityNativeEventManager
    participant URB as UnityNativeRaisedEventBuilder
    participant UEQM as UnityNativeEventQueueManager
    participant Logger as Logger/ErrorHandler

    UVP->>UEM: FetchVariables(callbackId)
    UEM->>URB: BuildFetchEvent(type)
    URB-->>UEM: Return eventDetails
    UEM->>UEQM: Queue FetchEvent(eventDetails)
    %% Event is processed by the event queue
    UEQM-->>UVP: TriggerVariablesFetched (includes callbackId)
    UVP->>Logger: Log success or errors if components missing
Loading

Possibly related PRs

  • EventQueue changes #159: Involves similar event queue management and processing modifications for the FetchEvent type, showing a direct code-level relationship.

Suggested reviewers

  • vasct

Poem

I’m a rabbit with code in my heart so light,
Hopping through events in the quiet of the night.
Fetching variables with a swift little skip,
My ears perk up with each new code tip.
Constants and callbacks dance in delight,
Celebrating fresh changes from morning to night!
🐰✨


🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@nzagorchev nzagorchev changed the base branch from unity_native_variables to unity_native_variables_responses March 27, 2025 13:15
@nzagorchev
Copy link
Contributor Author

@CodeRabbit review

Copy link

coderabbitai bot commented Mar 27, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
CleverTap/Runtime/Native/UnityNativeWrapper/EventBuilders/UnityNativeRaisedEventBuilder.cs (1)

55-67: Event builder method follows existing patterns, but lacks validation.

The BuildFetchEvent method correctly constructs an event for fetching variables, but unlike other builder methods in this class (such as Build and BuildChargedEvent), it doesn't perform any validation on the input type parameter.

Consider adding validation for the type parameter to ensure only valid types are processed:

internal UnityNativeEventBuilderResult<Dictionary<string, object>> BuildFetchEvent(int type) {
+    // Validate that type is a supported fetch type
+    if (type != UnityNativeConstants.Event.WZRK_FETCH_TYPE_VARIABLES) {
+        var validationError = new UnityNativeValidationResult(
+            UnityNativeValidationErrorCode.UnsupportedFetchType, 
+            $"Unsupported fetch type: {type}");
+        return new UnityNativeEventBuilderResult<Dictionary<string, object>>(
+            new List<UnityNativeValidationResult> { validationError }, 
+            null);
+    }
+    
    var eventDetails = new Dictionary<string, object> {
        { UnityNativeConstants.Event.EVENT_NAME, UnityNativeConstants.Event.EVENT_WZRK_FETCH }
    };

    var properties = new Dictionary<string, object> {
        { "t", type }
    };

    eventDetails.Add(UnityNativeConstants.Event.EVENT_DATA, properties);

    return new UnityNativeEventBuilderResult<Dictionary<string, object>>(new List<UnityNativeValidationResult>(), eventDetails);
}
CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventManager.cs (2)

388-405: Ensure error handling is robust for fetch operations.

The current implementation checks if eventBuilderResult.EventResult == null, but the BuildFetchEvent method doesn't include code paths that would return null results.

Either remove the null check if it's unnecessary or ensure the BuildFetchEvent method properly handles error cases that could return null:

internal void FetchVariables()
{
    if (ShouldDeferEvent(() =>
    {
        FetchVariables();
    }))
    {
        return;
    }

    var eventBuilderResult = new UnityNativeRaisedEventBuilder(_eventValidator)
        .BuildFetchEvent(UnityNativeConstants.Event.WZRK_FETCH_TYPE_VARIABLES);
-   if (eventBuilderResult.EventResult == null)
+   if (eventBuilderResult.EventResult == null || eventBuilderResult.ValidationResults.Any(vr => !vr.IsSuccess))
+   {
+       CleverTapLogger.LogError($"Failed to build fetch event: {string.Join(", ", eventBuilderResult.ValidationResults.Select(vr => vr.ErrorMsg))}");
        return;
+   }
    var eventDetails = eventBuilderResult.EventResult;
    UnityNativeEvent @event = BuildEvent(UnityNativeEventType.FetchEvent, eventDetails, true);
    _eventQueueManager.QueueEvent(@event);
}

400-400: Consider adding error logging for failed fetch attempts.

When a fetch event can't be created, the method silently returns without providing any feedback.

Add error logging to help with debugging:

if (eventBuilderResult.EventResult == null)
+   {
+       CleverTapLogger.LogError("Failed to build fetch event: result was null");
        return;
+   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0c2e5c7 and ece4b03.

📒 Files selected for processing (6)
  • CleverTap/Runtime/Native/UnityNativePlatformVariable.cs (3 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/Constants/UnityNativeConstants.cs (1 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/EventBuilders/UnityNativeBaseEventBuilder.cs (1 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/EventBuilders/UnityNativeRaisedEventBuilder.cs (1 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventManager.cs (1 hunks)
  • CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventQueueManager.cs (1 hunks)
🧰 Additional context used
🧬 Code Definitions (3)
CleverTap/Runtime/Native/UnityNativeWrapper/EventBuilders/UnityNativeBaseEventBuilder.cs (1)
CleverTap/Runtime/Native/UnityNativeWrapper/Constants/UnityNativeConstants.cs (2)
  • UnityNativeConstants (7-236)
  • Event (104-152)
CleverTap/Runtime/Native/UnityNativePlatformVariable.cs (6)
CleverTap/Runtime/Common/CleverTapPlatformVariable.cs (2)
  • FetchVariables (63-71)
  • FetchVariables (178-178)
CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventManager.cs (1)
  • FetchVariables (388-405)
CleverTap/Runtime/CleverTap.cs (1)
  • FetchVariables (576-577)
CleverTap/Runtime/IOS/IOSPlatformVariable.cs (1)
  • FetchVariables (14-15)
CleverTap/Runtime/Android/AndroidPlatformVariable.cs (1)
  • FetchVariables (15-16)
CTExample/Assets/Scripts/Variables/Variables.cs (1)
  • FetchVariables (172-178)
CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventManager.cs (4)
CleverTap/Runtime/Native/UnityNativeWrapper/EventBuilders/UnityNativeBaseEventBuilder.cs (3)
  • Dictionary (19-56)
  • Dictionary (58-63)
  • Dictionary (65-110)
CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeVarCache.cs (1)
  • Dictionary (206-209)
CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventQueueManager.cs (1)
  • QueueEvent (47-65)
CleverTap/Runtime/Native/UnityNativeWrapper/EventBuilders/UnityNativeRaisedEventBuilder.cs (2)
  • UnityNativeRaisedEventBuilder (7-128)
  • UnityNativeRaisedEventBuilder (10-12)
🔇 Additional comments (7)
CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventQueueManager.cs (1)

55-55: Appropriate event handling added

The addition of UnityNativeEventType.FetchEvent to be processed in the same way as RaisedEvent is correct. This ensures fetch events are properly queued in the _raisedEventsQueue for processing.

CleverTap/Runtime/Native/UnityNativePlatformVariable.cs (3)

21-21: Well-initialized fetch callback tracking

Good initialization of the callback ID to -1, which is an appropriate sentinel value indicating no active callback.


142-150: Successfully enhanced callback mechanism

The update to include the callbackId in the fetch response message is well-implemented. This ensures that the correct callback can be identified and triggered when the fetch completes.


193-204: Proper implementation with error handling

The implementation of FetchVariables correctly checks for null dependencies before proceeding and provides a clear error message if the platform variable isn't loaded. The method also properly stores the callback ID for later use.

CleverTap/Runtime/Native/UnityNativeWrapper/Constants/UnityNativeConstants.cs (1)

111-112: Consistent constants for fetch functionality

The added constants for fetch events are appropriate. Note that wzrk_fetch is already listed in the RESTRICTED_NAMES list (line 192), which is correct as these are system-reserved event names.

CleverTap/Runtime/Native/UnityNativeWrapper/EventBuilders/UnityNativeBaseEventBuilder.cs (1)

32-33: Consistent event type handling

Good approach to handle FetchEvent the same way as RaisedEvent by adding it to the case statement without a break in between. This ensures both event types are processed with the same logic, avoiding code duplication.

CleverTap/Runtime/Native/UnityNativeWrapper/UnityNativeEventManager.cs (1)

372-407: Good implementation of variables sync and fetch functionality.

The new Variables region organizes related functionality together and follows the established patterns for event handling. The FetchVariables method correctly uses the newly added BuildFetchEvent method and properly handles event queueing.

Base automatically changed from unity_native_variables_responses to unity_native_variables March 27, 2025 15:20
@nzagorchev nzagorchev force-pushed the unity_native_variables_fetch branch from ece4b03 to 6ec62ce Compare March 27, 2025 15:27
@nzagorchev
Copy link
Contributor Author

@CodeRabbit review

Copy link

coderabbitai bot commented Mar 27, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@nzagorchev nzagorchev merged commit fdaa867 into unity_native_variables Mar 27, 2025
1 check passed
@nzagorchev nzagorchev deleted the unity_native_variables_fetch branch March 27, 2025 16:54
nzagorchev added a commit that referenced this pull request Mar 31, 2025
* Merge pull request #153 from CleverTap/setup_tests

* Merge pull request #152 from CleverTap/unity_native_variables_define

* Merge pull request #156 from CleverTap/unity_native_variables_merge

* EventQueue changes (#159)

* Unity native variables sync (#160)

* Unity Native Variables - Handle Variables responses and Trigger Callbacks (#167)

* Unity native variables fetch (#168)

* Unity Native Variables - define and sync File variables (#169)

* Launch on Unity Native only (#170)

* Fix defineVars CORS issue (#174)
@coderabbitai coderabbitai bot mentioned this pull request Mar 31, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants