Skip to content

Conversation

@shivam-kumar-ts
Copy link
Contributor

@shivam-kumar-ts shivam-kumar-ts commented Oct 7, 2025

Add embed initialization state management and error handling

  • Introduced new error message for embed initialization failure.
  • Added InitStateChange event to track changes in embed initialization state.
  • Implemented InitState enum to represent various initialization states.
  • Updated TsEmbed class to manage initialization state and handle errors more gracefully during rendering.
  • Adjusted unit tests to reflect changes in error handling and initialization state checks.

ALREADY REMOVED THIS BUG IN TIS PR #152

@shivam-kumar-ts shivam-kumar-ts requested a review from a team as a code owner October 7, 2025 10:28
@mnk-blr
Copy link
Collaborator

mnk-blr commented Oct 7, 2025

🎉 Snyk checks have passed. No issues have been found so far.

security/snyk check is complete. No issues have been found. (View Details)

license/snyk check is complete. No issues have been found. (View Details)

@gemini-code-assist
Copy link

Summary of Changes

Hello @shivam-kumar-ts, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the embed's initialization process by introducing a comprehensive state management system. It allows embed instances to clearly communicate their readiness through defined states and events, enabling more robust and responsive integrations. This change ensures that embed components are only rendered when fully prepared, leading to a more stable and predictable user experience.

Highlights

  • Embed Initialization State Management: Introduced a new InitState enum (NotStarted, Initializing, Ready) to track the lifecycle of embed instances.
  • Initialization Event: Added EmbedEvent.InitStateChange to notify consumers about transitions between initialization states, including previous and current states, and a timestamp.
  • Asynchronous Initialization Handling: The TsEmbed class now includes initPromise, getInitState(), and waitForInit() methods, allowing developers to programmatically check the embed's readiness or await its full initialization.
  • Graceful Render Behavior: The render method has been updated to wait for the embed to be fully initialized before attempting to render, preventing errors from premature rendering and improving robustness.
  • New Error Message: A specific error message, EMBED_INITIALIZATION_FAILED, has been added for clarity when initialization encounters issues.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a state machine for managing the initialization of embedded components, which is a great improvement for robustness and developer experience. It adds InitState, getInitState(), waitForInit(), and the InitStateChange event. The implementation correctly transitions from Initializing to Ready upon successful global SDK initialization. However, there are a few critical areas for improvement. The current implementation does not handle initialization failures, which can lead to unhandled promise rejections and cause the application to hang. The InitState enum is also missing a failure state. Additionally, a new test suite has some confusing and unused variables. Addressing these points will make the new state management system more complete and robust.

Comment on lines 265 to 278
this.initPromise = new Promise((resolve) => {
this.initPromiseResolve = resolve;
});
this.setInitState(InitState.Initializing);

this.isReadyForRenderPromise = getInitPromise().then(async () => {
if (!embedConfig.authTriggerContainer && !embedConfig.useEventForSAMLPopup) {
this.embedConfig.authTriggerContainer = domSelector;
}
this.thoughtSpotHost = getThoughtSpotHost(embedConfig);
this.thoughtSpotV2Base = getV2BasePath(embedConfig);
this.shouldEncodeUrlQueryParams = embedConfig.shouldEncodeUrlQueryParams;
this.setInitState(InitState.Ready);
});

Choose a reason for hiding this comment

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

high

The promise returned by getInitPromise() can potentially reject if the global init() fails. This rejection is not handled here, which will result in an "unhandled promise rejection" error in the consumer's application. Furthermore, the embed instance's initPromise will never resolve or reject, causing any code awaiting it (like in renderIFrame) to hang indefinitely.

You should handle this rejection by rejecting the instance's initPromise. This will also make the try/catch block in renderIFrame functional.

To do this, you'll need to:

  1. Add a private initPromiseReject: (reason?: any) => void; property to the class (near initPromiseResolve).
  2. Update the constructor logic as suggested below to capture the reject function and add a .catch() block.
        this.initPromise = new Promise((resolve, reject) => {
            this.initPromiseResolve = resolve;
            this.initPromiseReject = reject;
        });
        this.setInitState(InitState.Initializing);

        this.isReadyForRenderPromise = getInitPromise().then(async () => {
            if (!embedConfig.authTriggerContainer && !embedConfig.useEventForSAMLPopup) {
                this.embedConfig.authTriggerContainer = domSelector;
            }
            this.thoughtSpotHost = getThoughtSpotHost(embedConfig);
            this.thoughtSpotV2Base = getV2BasePath(embedConfig);
            this.shouldEncodeUrlQueryParams = embedConfig.shouldEncodeUrlQueryParams;
            this.setInitState(InitState.Ready);
        }).catch((error) => {
            this.initPromiseReject(error);
        });

Comment on lines 5900 to 5913
export enum InitState {
/**
* Embed instance created but initialization not started
*/
NotStarted = 'not-started',
/**
* SDK initialization in progress
*/
Initializing = 'initializing',
/**
* SDK initialization completed successfully
*/
Ready = 'ready',
}

Choose a reason for hiding this comment

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

high

The InitState enum currently only accounts for success states (NotStarted, Initializing, Ready). It's missing a state to represent a failure during initialization. Without a failure state, if initialization fails, the component will be stuck in the Initializing state forever, which can lead to hangs and makes it difficult for consumers of the SDK to handle errors gracefully. Please add a state for failures, for example Error.

export enum InitState {
    /**
     * Embed instance created but initialization not started
     */
    NotStarted = 'not-started',
    /**
     * SDK initialization in progress  
     */
    Initializing = 'initializing',
    /**
     * SDK initialization completed successfully
     */
    Ready = 'ready',
    /**
     * SDK initialization failed
     */
    Error = 'error',
}

try {
await this.ensureInitialized();
} catch (error) {
this.handleError('Cannot render: initialization failed');

Choose a reason for hiding this comment

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

medium

You've added a new constant EMBED_INITIALIZATION_FAILED in src/errors.ts, which is great for maintainability. However, this hardcoded string is used here instead of the constant. Please use the constant to ensure consistency and make future changes easier.

            this.handleError(ERROR_MESSAGE.EMBED_INITIALIZATION_FAILED);

Comment on lines 1929 to 1931
mockInitPromise = new Promise<void>((resolve) => {
mockResolve = () => resolve();
});

Choose a reason for hiding this comment

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

medium

In the new 'Initialization State Management' test suite, the mockInitPromise and mockResolve variables are defined in beforeEach but are not actually connected to the TsEmbed instance under test. The test passes due to the side effect of the global init() call in beforeEach. This can be confusing and makes the test less explicit about what it's testing. To make the test more robust and clear, consider mocking getInitPromise from base.ts to directly control the initialization flow for the embed instance. This would allow you to test both success and failure scenarios more reliably.

@pkg-pr-new
Copy link

pkg-pr-new bot commented Oct 7, 2025

Open in StackBlitz

npm i https://pkg.pr.new/thoughtspot/visual-embed-sdk/@thoughtspot/visual-embed-sdk@325

commit: 9ae8462

@shivam-kumar-ts shivam-kumar-ts force-pushed the SCAL-236431 branch 4 times, most recently from f15ed82 to d1ca382 Compare October 7, 2025 11:33
@sonar-prod-ts
Copy link

sonar-prod-ts bot commented Oct 7, 2025

SonarQube Quality Gate

Quality Gate passed

Bug A 0 Bugs
Vulnerability A 0 Vulnerabilities
Security Hotspot A 0 Security Hotspots
Code Smell A 2 Code Smells

No Coverage information No Coverage information
0.0% 0.0% Duplication

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