Skip to content

[Components] scalr #13481 #16663

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

[Components] scalr #13481 #16663

wants to merge 2 commits into from

Conversation

lcaresia
Copy link
Collaborator

@lcaresia lcaresia commented May 14, 2025

WHY

Summary by CodeRabbit

  • New Features
    • Added new event sources for Scalr runs: "New Run Completed," "New Run Errored," and "New Run Needs Attention," each emitting real-time events based on run status.
    • Introduced webhook management to enable automated event notifications from Scalr.
  • Chores
    • Updated package configuration and dependencies for the Scalr integration.
    • Removed the previous Scalr app integration, replacing it with a redesigned module offering enhanced API interaction and webhook support.

@lcaresia lcaresia self-assigned this May 14, 2025
Copy link

vercel bot commented May 14, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

3 Skipped Deployments
Name Status Preview Comments Updated (UTC)
docs-v2 ⬜️ Ignored (Inspect) Visit Preview May 15, 2025 7:38pm
pipedream-docs ⬜️ Ignored (Inspect) May 15, 2025 7:38pm
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) May 15, 2025 7:38pm

Copy link
Contributor

coderabbitai bot commented May 14, 2025

Walkthrough

The changes replace the previous Scalr app integration with a new implementation that includes comprehensive API methods for managing webhooks, accounts, and events. Several new source components are added to emit events on specific run statuses, all extending a common webhook management module. The package metadata is adjusted, and the old app file and .gitignore are removed.

Changes

File(s) Change Summary
components/scalr/app/scalr.app.ts Deleted the old Scalr app integration file, removing its default export and the authKeys method.
components/scalr/scalr.app.mjs Added a new Scalr app integration module with methods for API requests, webhook management, account retrieval, and event fetching.
components/scalr/sources/common/common.mjs Added a common module managing webhook lifecycle and event handling, requiring overrides for event type and event emission.
components/scalr/sources/new-run-completed/new-run-completed.mjs Added a source component emitting events on new completed runs, extending the common module.
components/scalr/sources/new-run-errored/new-run-errored.mjs Added a source component emitting events on new errored runs, extending the common module.
components/scalr/sources/new-run-needs-attention/new-run-needs-attention.mjs Added a source component emitting events when runs need attention, extending the common module.
components/scalr/package.json Downgraded version, changed main entry point, removed "files" field, fixed "publishConfig" bracket, and added dependency on "@pipedream/platform".
components/scalr/.gitignore Deleted the .gitignore file removing ignore rules for .js, .mjs, and dist directory.

Poem

A webhook’s call, a run’s new tale,
From common roots, the sources sail.
Events that hop from error to done,
Scalr’s new dance has just begun.
With code refreshed and packages tight,
The rabbit leaps into the night!
🐰🌙✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

components/scalr/sources/common/common.mjs

Oops! Something went wrong! :(

ESLint: 8.57.1

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonc-eslint-parser' imported from /eslint.config.mjs
at packageResolve (node:internal/modules/esm/resolve:839:9)
at moduleResolve (node:internal/modules/esm/resolve:908:18)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

components/scalr/sources/new-run-errored/new-run-errored.mjs

Oops! Something went wrong! :(

ESLint: 8.57.1

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonc-eslint-parser' imported from /eslint.config.mjs
at packageResolve (node:internal/modules/esm/resolve:839:9)
at moduleResolve (node:internal/modules/esm/resolve:908:18)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

components/scalr/scalr.app.mjs

Oops! Something went wrong! :(

ESLint: 8.57.1

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonc-eslint-parser' imported from /eslint.config.mjs
at packageResolve (node:internal/modules/esm/resolve:839:9)
at moduleResolve (node:internal/modules/esm/resolve:908:18)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

  • 2 others

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ 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.

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

@lcaresia lcaresia linked an issue May 14, 2025 that may be closed by this pull request
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

🧹 Nitpick comments (1)
components/scalr/package.json (1)

15-17: Add runtime dependency on @pipedream/platform.
This dependency is required for the component runtime. If you expect the host to provide @pipedream/platform, you may want to declare it as a peerDependency instead of bundling it.

Here’s a diff to switch it to a peerDependency:

-  "dependencies": {
-    "@pipedream/platform": "^3.0.3"
-  }
+  "peerDependencies": {
+    "@pipedream/platform": "^3.0.3"
+  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0129ef7 and 9969779.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (2)
  • components/scalr/app/scalr.app.ts (0 hunks)
  • components/scalr/package.json (1 hunks)
💤 Files with no reviewable changes (1)
  • components/scalr/app/scalr.app.ts
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Verify TypeScript components
  • GitHub Check: pnpm publish
  • GitHub Check: Publish TypeScript components
  • GitHub Check: Lint Code Base
🔇 Additional comments (3)
components/scalr/package.json (3)

14-14: PublishConfig block closure restored.
The missing closing brace for the publishConfig object has been added correctly.


5-5:

❓ Verification inconclusive

Ensure the new entry point exists post-build.
The "main" field now points to scalr.app.mjs at the package root—verify that your build step emits this file in the package, and consider adding a "files" array to restrict published contents.

You can confirm its presence with:


🏁 Script executed:

fd scalr.app.mjs

Length of output: 18


Verify new entry point and locked‐down package contents
We weren’t able to locate scalr.app.mjs in the repo—please ensure your build step emits this file at the package root (or update "main" to the correct path if it lands elsewhere). Also consider adding a "files" array to limit what’s published.

• Run your build and confirm the file exists:

npm run build
fd scalr.app.mjs

• If the output lands in a subfolder (e.g. dist/), update the "main" field accordingly.
• Add a "files" entry to components/scalr/package.json, for example:

"files": [
  "scalr.app.mjs",
  "dist/"
]

3-3:

❓ Verification inconclusive

Confirm the version downgrade intent.
The version was changed from 0.0.2 to 0.0.1—ensure this aligns with your release strategy and doesn’t accidentally overwrite a newer release on npm.

Run the following to list published versions:


🏁 Script executed:

npm view @pipedream/scalr versions

Length of output: 57


Confirm version downgrade intent
The published versions for @pipedream/scalr are 0.0.1 and 0.0.2. The version in components/scalr/package.json has been downgraded from 0.0.2 to 0.0.1. Please confirm this is intentional and won’t accidentally overwrite a newer release on npm.

Copy link
Collaborator

@michelle0927 michelle0927 left a comment

Choose a reason for hiding this comment

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

Hi @lcaresia, I think you forgot to include the components in this PR.

@lcaresia
Copy link
Collaborator Author

Hi @lcaresia, I think you forgot to include the components in this PR.

Thanks @michelle0927!

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

🧹 Nitpick comments (7)
components/scalr/sources/new-run-completed/new-run-completed.mjs (1)

3-28: Component implementation looks good with room for data validation

The component correctly extends the common module and properly implements the required methods. The emission logic with unique ID generation and summary creation is well-structured.

Consider adding validation for the data structure before accessing properties:

  async emitEvent(data) {
+    if (!data?.run) {
+      console.log("Received invalid webhook data", data);
+      return;
+    }
    
    this.$emit(data, {
      id: data.run.id,
      summary: `New run completed with ID ${data.run.id}`,
      ts: Date.parse(data.run["created-at"]),
    });
  },

This would prevent potential errors if the webhook payload doesn't match the expected structure.

components/scalr/sources/common/common.mjs (4)

3-70: Well-structured common module with appropriate abstraction

The common module provides a solid foundation for Scalr webhook-based components with proper lifecycle management and abstract methods that enforce implementation.

A few observations:

  1. The webhook naming pattern "Webhook Pipedream - " + new Date().toISOString() ensures uniqueness but will create many webhooks if components are reactivated frequently
  2. The error message in emitEvent method includes the event parameter but doesn't use it correctly

Fix the error message in the emitEvent method:

  emitEvent(event) {
-    throw new Error("emitEvent is not implemented", event);
+    throw new Error("emitEvent is not implemented");
  },

The second argument to Error constructor is not used - JavaScript Error doesn't accept the data as a second parameter.


30-61: Webhook creation looks good but could benefit from error handling

The webhook creation logic correctly sets up the webhook with the Scalr API and stores the webhook ID.

Consider adding error handling to the webhook creation process:

  async activate() {
-    const { data } = await this.scalr.createWebhook({
-      data: {
-        "data": {
-          "attributes": {
-            "max-attempts": 3,
-            "timeout": 15,
-            "name": "Webhook Pipedream - " + new Date().toISOString(),
-            "url": this.http.endpoint,
-          },
-          "relationships": {
-            "account": {
-              "data": {
-                "type": "accounts",
-                "id": this.accountId,
-              },
-            },
-            "events": {
-              "data": [
-                {
-                  "type": "event-definitions",
-                  "id": this.getWebhookEventType(),
-                },
-              ],
-            },
-          },
-          "type": "webhook-integrations",
-        },
-      },
-    });
-    this._setWebhookId(data.id);
+    try {
+      const { data } = await this.scalr.createWebhook({
+        data: {
+          "data": {
+            "attributes": {
+              "max-attempts": 3,
+              "timeout": 15,
+              "name": "Webhook Pipedream - " + new Date().toISOString(),
+              "url": this.http.endpoint,
+            },
+            "relationships": {
+              "account": {
+                "data": {
+                  "type": "accounts",
+                  "id": this.accountId,
+                },
+              },
+              "events": {
+                "data": [
+                  {
+                    "type": "event-definitions",
+                    "id": this.getWebhookEventType(),
+                  },
+                ],
+              },
+            },
+            "type": "webhook-integrations",
+          },
+        },
+      });
+      this._setWebhookId(data.id);
+    } catch (err) {
+      console.error("Failed to create webhook", err);
+      throw err;
+    }
  },

62-65: Webhook deactivation should include error handling

The deactivation logic correctly retrieves and removes the webhook, but lacks error handling.

Add error handling to gracefully handle webhook removal failures:

  async deactivate() {
    const webhookId = this._getWebhookId();
-    await this.scalr.removeWebhook(webhookId);
+    if (!webhookId) {
+      console.log("No webhook ID found to remove");
+      return;
+    }
+    try {
+      await this.scalr.removeWebhook(webhookId);
+    } catch (err) {
+      console.error("Failed to remove webhook", err);
+      // Don't throw the error to allow component deactivation to complete
+    }
  },

67-69: Run method should include error handling

The run method passes the webhook payload to the emitEvent method but doesn't include error handling.

Add error handling to prevent component crashes:

  async run(event) {
-    await this.emitEvent(event.body);
+    try {
+      await this.emitEvent(event.body);
+    } catch (err) {
+      console.error("Failed to emit event", err);
+    }
  },
components/scalr/scalr.app.mjs (2)

21-40: API request handling is properly structured

The base URL construction and request handling are well-implemented with proper authentication and content type headers.

One small improvement would be to add error handling and more detailed error information:

  async _makeRequest(opts = {}) {
    const {
      $ = this,
      path,
      headers,
      ...otherOpts
    } = opts;
-    return axios($, {
-      ...otherOpts,
-      url: this._baseUrl() + path,
-      headers: {
-        "Authorization": `Bearer ${this.$auth.api_token}`,
-        "Content-type": "application/vnd.api+json",
-        ...headers,
-      },
-    });
+    try {
+      return await axios($, {
+        ...otherOpts,
+        url: this._baseUrl() + path,
+        headers: {
+          "Authorization": `Bearer ${this.$auth.api_token}`,
+          "Content-type": "application/vnd.api+json",
+          ...headers,
+        },
+      });
+    } catch (error) {
+      const statusCode = error.response?.status;
+      const statusText = error.response?.statusText;
+      const responseData = error.response?.data;
+      throw new Error(`Scalr API request failed: ${statusCode} ${statusText}. Path: ${path}. ${JSON.stringify(responseData)}`);
+    }
  },

41-72: API methods are well-organized and consistent

The API methods for webhook management, account fetching, and event retrieval are correctly implemented and follow a consistent pattern.

A minor enhancement would be to add JSDoc comments for better code documentation:

Add JSDoc comments to document method parameters and return values:

+  /**
+   * Create a new webhook integration
+   * @param {Object} args - Request arguments
+   * @returns {Promise<Object>} Response containing the created webhook data
+   */
  async createWebhook({ ...args }) {
    return this._makeRequest({
      path: "/integrations/webhooks",
      method: "post",
      ...args,
    });
  },

+  /**
+   * Remove a webhook integration by ID
+   * @param {string} webhookId - The ID of the webhook to remove
+   * @returns {Promise<Object>} Response from the delete operation
+   */
  async removeWebhook(webhookId) {
    return this._makeRequest({
      path: `/integrations/webhooks/${webhookId}`,
      method: "delete",
    });
  },
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 9969779 and 7d59f43.

📒 Files selected for processing (6)
  • components/scalr/.gitignore (0 hunks)
  • components/scalr/scalr.app.mjs (1 hunks)
  • components/scalr/sources/common/common.mjs (1 hunks)
  • components/scalr/sources/new-run-completed/new-run-completed.mjs (1 hunks)
  • components/scalr/sources/new-run-errored/new-run-errored.mjs (1 hunks)
  • components/scalr/sources/new-run-needs-attention/new-run-needs-attention.mjs (1 hunks)
💤 Files with no reviewable changes (1)
  • components/scalr/.gitignore
✅ Files skipped from review due to trivial changes (2)
  • components/scalr/sources/new-run-errored/new-run-errored.mjs
  • components/scalr/sources/new-run-needs-attention/new-run-needs-attention.mjs
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Verify TypeScript components
  • GitHub Check: pnpm publish
  • GitHub Check: Publish TypeScript components
  • GitHub Check: Lint Code Base
🔇 Additional comments (1)
components/scalr/scalr.app.mjs (1)

3-19: App definition and account option fetching are well-implemented

The Scalr app integration correctly defines its type, identifier, and properties. The accountId property with dynamic options fetching provides a good user experience.

@@ -1,16 +1,18 @@
{
"name": "@pipedream/scalr",
"version": "0.0.2",
"version": "0.0.1",
Copy link
Collaborator

Choose a reason for hiding this comment

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

Version should be increated to "0.0.3" rather than decreased to "0.0.1".

Comment on lines +11 to +17
async options() {
const { data: accounts } = await this.getAccounts();
return accounts.map((account) => ({
label: account.attributes.name,
value: account.id,
}));
},
Copy link
Collaborator

Choose a reason for hiding this comment

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

We should use pagination in async options whenever possible. The documentation shows that the list accounts endpoint accepts page[number] as a parameter.

Comment on lines +54 to +59
async getWebhooks(args = {}) {
return this._makeRequest({
path: "/integrations/webhooks",
...args,
});
},
Copy link
Collaborator

Choose a reason for hiding this comment

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

I don't see getWebhooks being called anywhere.

Comment on lines +66 to +71
async getEvents(args = {}) {
return this._makeRequest({
path: "/event-definitions",
...args,
});
},
Copy link
Collaborator

Choose a reason for hiding this comment

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

I don't see getEvents being called anywhere.

name: "New Run Completed (Instant)",
version: "0.0.1",
key: "scalr-new-run-completed",
description: "Emit new event on each new completed run.",
Copy link
Collaborator

Choose a reason for hiding this comment

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

I like to put in doc links if possible, especially when there aren't any other components with links to the docs.

Suggested change
description: "Emit new event on each new completed run.",
description: "Emit new event on each new completed run. [See the documentation](https://docs.scalr.io/reference/create_webhook_integration)",

name: "New Run Errored (Instant)",
version: "0.0.1",
key: "scalr-new-run-errored",
description: "Emit new event when a new run encountered an error.",
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
description: "Emit new event when a new run encountered an error.",
description: "Emit new event when a new run encountered an error. [See the documentation](https://docs.scalr.io/reference/create_webhook_integration)",

name: "New Run Needs Attention (Instant)",
version: "0.0.1",
key: "scalr-new-run-needs-attention",
description: "Emit new event when a new run needs attention.",
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
description: "Emit new event when a new run needs attention.",
description: "Emit new event when a new run needs attention. [See the documentation](https://docs.scalr.io/reference/create_webhook_integration)",

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.

[Components] scalr
2 participants