Skip to content
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

Support Multiple License Products when using Unity Licensing Server #282

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

ejnarvala
Copy link

@ejnarvala ejnarvala commented Aug 7, 2024

Changes

This change enables supporting unity floating license servers with multiple products configured, more info here.

  • adds an action parameter unityLicensingProductIds
  • updates services-config.json.template to set toolset based on unityLicensingProductIds. If this value is set to an empty string, it will use the server's default configuration, the same behavior as if the parameter was not included at alll

Related PRs

Related Issues

Successful Workflow Run Link

PRs don't have access to secrets so you will need to provide a link to a successful run
of the workflows from your own repo.

  • Our repositories are private, but we have successfully run a workflow using this fork.

Checklist

Summary by CodeRabbit

  • New Features

    • Introduced an optional input parameter for Unity licensing product IDs to enhance license management.
    • Added a new environment variable for Unity licensing product IDs to improve configurability.
  • Bug Fixes

    • Maintained existing error handling and control flow across various components, ensuring stability.
  • Documentation

    • Updated method signatures and descriptions to reflect the addition of the new licensing parameter.

Copy link

github-actions bot commented Aug 7, 2024

Cat Gif

@GabLeRoux
Copy link
Member

@coderabbitai do a full review

Copy link

coderabbitai bot commented Oct 27, 2024

@GabLeRoux: Understood, I will perform a full review of the PR.

✅ Actions performed

Full review triggered.

Copy link

coderabbitai bot commented Oct 27, 2024

Walkthrough

The changes introduce a new input parameter, unityLicensingProductIds, across several files related to the Unity test runner. This parameter is optional and allows users to specify a comma-separated list of license product identifiers for the Unity licensing server. The modifications affect how input parameters are handled, how the Docker container is configured, and how environment variables are set up, without altering the overall structure or logic of existing functionalities.

Changes

File Path Change Summary
action.yml Added new optional input parameter unityLicensingProductIds with a default value of an empty string.
src/main.ts Introduced unityLicensingProductIds to the input parameters in the run function and passed it to Docker.run.
src/model/docker.ts Updated run method signature to include parameters.unityLicensingProductIds in the call to LicensingServerSetup.Setup.
src/model/image-environment-factory.ts Added new environment variable UNITY_LICENSING_PRODUCT_IDS in getEnvironmentVariables method.
src/model/input.ts Added new input variable unityLicensingProductIds in getFromUser method, initialized from user input.
src/model/licensing-server-setup.ts Updated Setup method signature to include unityLicensingProductIds and replace placeholder in servicesConfig.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Input
    participant Docker
    participant LicensingServerSetup
    participant ImageEnvironmentFactory

    User->>Input: Provide unityLicensingProductIds
    Input->>Docker: Pass unityLicensingProductIds
    Docker->>LicensingServerSetup: Setup with unityLicensingProductIds
    LicensingServerSetup->>ImageEnvironmentFactory: Configure environment with UNITY_LICENSING_PRODUCT_IDS
Loading

🐇 "In the meadow, changes sprout,
New licenses to talk about!
With product IDs in tow,
Unity's magic starts to flow.
A hop, a skip, a joyful cheer,
For all the bunnies, it's finally here!" 🐇


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 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: 2

🧹 Outside diff range and nitpick comments (7)
src/model/licensing-server-setup.ts (2)

5-9: Add type annotations and parameter documentation.

The method signature could be improved with:

  1. Type annotation for unityLicensingServer parameter
  2. JSDoc documentation explaining the purpose and format of unityLicensingProductIds

Consider applying these changes:

+/**
+ * Sets up the Unity licensing server configuration
+ * @param unityLicensingServer The URL of the Unity licensing server
+ * @param actionFolder The folder containing action configuration files
+ * @param unityLicensingProductIds Comma-separated list of Unity license product IDs
+ */
 public static Setup(
-  unityLicensingServer,
+  unityLicensingServer: string,
   actionFolder: string,
   unityLicensingProductIds: string,
 )

Line range hint 11-17: Enhance error handling and return status.

The error handling could be improved to provide better feedback and status reporting.

Consider these improvements:

-  public static Setup(
+  public static async Setup(
     unityLicensingServer: string,
     actionFolder: string,
     unityLicensingProductIds: string,
-  ) {
+  ): Promise<boolean> {
     const servicesConfigPath = `${actionFolder}/unity-config/services-config.json`;
     const servicesConfigPathTemplate = `${servicesConfigPath}.template`;
     if (!fs.existsSync(servicesConfigPathTemplate)) {
-      core.error(`Missing services config ${servicesConfigPathTemplate}`);
-      return;
+      core.error(`Services config template not found at: ${servicesConfigPathTemplate}`);
+      return false;
     }
+    try {
+      // ... existing code ...
+      return true;
+    } catch (error) {
+      core.error(`Failed to setup licensing server: ${error.message}`);
+      return false;
+    }
   }
src/model/image-environment-factory.ts (1)

30-30: LGTM with suggestions for improvement.

The addition of UNITY_LICENSING_PRODUCT_IDS environment variable follows the established pattern and integrates well with the existing code.

Consider adding input validation and documentation:

+      // Comma-separated list of Unity license product IDs (e.g., "UC-XXXX,UC-YYYY")
       { name: 'UNITY_LICENSING_PRODUCT_IDS', value: parameters.unityLicensingProductIds },

Also, consider adding validation before assignment:

{
  name: 'UNITY_LICENSING_PRODUCT_IDS',
  value: parameters.unityLicensingProductIds?.split(',')
    .map(id => id.trim())
    .filter(id => id.match(/^UC-[A-Z0-9]+$/))
    .join(',')
}
action.yml (1)

96-99: Consider single-line description for consistency.

The multi-line description format differs from other parameters in the file. Consider consolidating it into a single line for consistency:

-    description:
-      'Comma separated list of license product identifiers to request licenses for from the license server. Not setting
-      this will request the default license product configured on the licensing server. Only applicable if
-      unityLicensingServer is set.'
+    description: 'Comma separated list of license product identifiers to request licenses for from the license server. Not setting this will request the default license product configured on the licensing server. Only applicable if unityLicensingServer is set.'
src/model/docker.ts (1)

37-41: Document the new parameter in JSDoc.

Add documentation for the new parameter to improve code maintainability.

Add JSDoc above the run method:

/**
 * Run a Docker container with the specified parameters
 * @param image - The Docker image to run
 * @param parameters - Configuration parameters
 * @param parameters.unityLicensingServer - Unity licensing server configuration
 * @param parameters.actionFolder - Action folder path
 * @param parameters.unityLicensingProductIds - Comma-separated list of Unity license product IDs
 * @param silent - Whether to suppress output
 */
src/model/input.ts (2)

90-90: Consider adding input validation for unityLicensingProductIds.

While the implementation follows the existing pattern, consider adding validation to ensure the product IDs are in the correct format (e.g., comma-separated valid identifiers) to catch configuration errors early.

Example validation:

if (unityLicensingProductIds !== '') {
  const productIds = unityLicensingProductIds.split(',').map(id => id.trim());
  if (productIds.some(id => !/^[\w-]+$/.test(id))) {
    throw new Error(`Invalid unityLicensingProductIds format. Expected comma-separated alphanumeric IDs.`);
  }
}

243-243: Add TypeScript type annotations for better type safety.

Consider adding type annotations to the return object to improve type safety and documentation.

Example:

interface InputConfig {
  // ... existing properties
  unityLicensingServer: string;
  unityLicensingProductIds: string;
  // ... remaining properties
}

public static getFromUser(): InputConfig {
  // ... existing implementation
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 05a00ef and 55b59f8.

⛔ Files ignored due to path filters (3)
  • dist/index.js is excluded by !**/dist/**
  • dist/index.js.map is excluded by !**/dist/**, !**/*.map
  • dist/unity-config/services-config.json.template is excluded by !**/dist/**
📒 Files selected for processing (6)
  • action.yml (1 hunks)
  • src/main.ts (2 hunks)
  • src/model/docker.ts (1 hunks)
  • src/model/image-environment-factory.ts (1 hunks)
  • src/model/input.ts (2 hunks)
  • src/model/licensing-server-setup.ts (2 hunks)
🔇 Additional comments (6)
src/main.ts (2)

32-32: LGTM: Clean integration of the new licensing parameter.

The addition of unityLicensingProductIds follows the existing pattern and is positioned logically with other Unity-related parameters.


70-70: Verify the Docker configuration handling.

The parameter is correctly forwarded to Docker.run(). However, let's verify that the Docker configuration properly handles this parameter.

src/model/image-environment-factory.ts (1)

Line range hint 1-93: Verify error handling in dependent components.

The new environment variable affects the Docker container configuration. Ensure proper error handling exists in the Unity licensing server setup code.

Let's check the related files:

action.yml (1)

93-99: LGTM! Well-integrated licensing parameter.

The new unityLicensingProductIds parameter is well-designed:

  • Optional with empty default maintains backward compatibility
  • Clear dependency on unityLicensingServer is documented
  • Comma-separated format is explicitly mentioned
src/model/docker.ts (1)

37-41: Verify integration with LicensingServerSetup.

The changes look good, but we should verify the integration with the LicensingServerSetup class.

Let's check the implementation of the Setup method:

✅ Verification successful

Let me verify the source implementation rather than the compiled code:


Integration with LicensingServerSetup is correctly implemented

The Setup method is being called with the correct parameters in the same order as defined in the class:

  1. unityLicensingServer - for replacing the '%URL%' placeholder
  2. actionFolder - for constructing the config paths
  3. unityLicensingProductIds - for replacing the '%LICENSE_PRODUCT_IDS%' placeholder

The implementation handles the configuration file setup properly with appropriate error handling.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the LicensingServerSetup class implementation
ast-grep --pattern $'class LicensingServerSetup {
  $$$
  static Setup($$$) {
    $$$
  }
  $$$
}'

Length of output: 1160


Script:

#!/bin/bash
# Search for the LicensingServerSetup class in TypeScript files
rg -t typescript "class LicensingServerSetup" -A 15

Length of output: 88


Script:

#!/bin/bash
# Search for the LicensingServerSetup class in .ts files
rg "class LicensingServerSetup" -g "*.ts" -A 15

Length of output: 1238

src/model/input.ts (1)

90-91: Document and validate the relationship with unityLicensingServer.

Since this parameter is related to the licensing server functionality, consider:

  1. Adding JSDoc comments to document the relationship between unityLicensingProductIds and unityLicensingServer
  2. Implementing conditional validation when the licensing server is specified

Let's verify the usage pattern:

Example implementation:

/**
 * @param unityLicensingServer - The Unity licensing server URL
 * @param unityLicensingProductIds - Comma-separated list of product IDs to request from the licensing server
 * @throws {Error} When product IDs are specified without a licensing server
 */
if (unityLicensingProductIds !== '' && unityLicensingServer === '') {
  throw new Error('unityLicensingProductIds requires unityLicensingServer to be specified');
}

@@ -13,6 +17,7 @@ class LicensingServerSetup {

let servicesConfig = fs.readFileSync(servicesConfigPathTemplate).toString();
servicesConfig = servicesConfig.replace('%URL%', unityLicensingServer);
servicesConfig = servicesConfig.replace('%LICENSE_PRODUCT_IDS%', unityLicensingProductIds);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add input validation and maintain backward compatibility.

The current implementation has potential security and compatibility concerns:

  1. Direct string replacement without sanitization
  2. No handling of empty values
  3. No validation of product ID format

Consider applying these changes:

+    // Validate and sanitize product IDs
+    const sanitizedProductIds = unityLicensingProductIds
+      ?.split(',')
+      .map(id => id.trim())
+      .filter(id => /^[\w-]+$/.test(id))  // Allow only alphanumeric chars and hyphens
+      .join(',');
+
+    // Only replace if valid product IDs are provided
+    if (sanitizedProductIds) {
+      servicesConfig = servicesConfig.replace('%LICENSE_PRODUCT_IDS%', sanitizedProductIds);
+    } else {
+      // Maintain backward compatibility by using empty string
+      servicesConfig = servicesConfig.replace('%LICENSE_PRODUCT_IDS%', '');
+    }
-    servicesConfig = servicesConfig.replace('%LICENSE_PRODUCT_IDS%', unityLicensingProductIds);
📝 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
servicesConfig = servicesConfig.replace('%LICENSE_PRODUCT_IDS%', unityLicensingProductIds);
// Validate and sanitize product IDs
const sanitizedProductIds = unityLicensingProductIds
?.split(',')
.map(id => id.trim())
.filter(id => /^[\w-]+$/.test(id)) // Allow only alphanumeric chars and hyphens
.join(',');
// Only replace if valid product IDs are provided
if (sanitizedProductIds) {
servicesConfig = servicesConfig.replace('%LICENSE_PRODUCT_IDS%', sanitizedProductIds);
} else {
// Maintain backward compatibility by using empty string
servicesConfig = servicesConfig.replace('%LICENSE_PRODUCT_IDS%', '');
}

Comment on lines +37 to +41
LicensingServerSetup.Setup(
parameters.unityLicensingServer,
parameters.actionFolder,
parameters.unityLicensingProductIds,
);
Copy link

@coderabbitai coderabbitai bot Oct 27, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding type safety and validation for unityLicensingProductIds.

While the change correctly implements the new parameter, consider adding validation to ensure the product IDs are in the correct format before passing them to Setup.

Consider wrapping the Setup call with validation:

      LicensingServerSetup.Setup(
        parameters.unityLicensingServer,
        parameters.actionFolder,
-       parameters.unityLicensingProductIds,
+       validateProductIds(parameters.unityLicensingProductIds),
      );

+ function validateProductIds(ids: string): string {
+   if (!ids) return '';
+   const productIds = ids.split(',').map(id => id.trim());
+   if (productIds.some(id => !/^[\w-]+$/.test(id))) {
+     throw new Error('Invalid product ID format. Product IDs should only contain alphanumeric characters, hyphens and underscores.');
+   }
+   return productIds.join(',');
+ }

Committable suggestion was skipped due to low confidence.

Copy link
Member

@GabLeRoux GabLeRoux Oct 27, 2024

Choose a reason for hiding this comment

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

I'm not sure about this suggestion as I don't have much details about unityLicensingProductIds's actual format, but it sounds a like a good idea to do input validation.

On the other hand, we're not doing validation for other parameters so this might be out of scope. Feel free to discard.

edit: I've deleted this learning as not relevant. Suggesting input validation is usually good

Copy link

Choose a reason for hiding this comment

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

@GabLeRoux, understood. Since input validation for other parameters is not currently implemented and might be out of scope for this PR, it's acceptable to discard this suggestion. Thank you for clarifying.


✏️ Learnings added
Learnt from: GabLeRoux
PR: game-ci/unity-test-runner#282
File: src/model/docker.ts:37-41
Timestamp: 2024-10-27T16:14:24.321Z
Learning: Input validation for parameters such as `unityLicensingProductIds` is not currently implemented in the codebase, so suggesting to add validation might be out of scope during code reviews.

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.

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