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

Fixed proper L0 space agent selection in recursive license assignment #4708

Merged
merged 2 commits into from
Nov 18, 2024

Conversation

valentinyanakiev
Copy link
Member

@valentinyanakiev valentinyanakiev commented Nov 15, 2024

  • agent was picked up from the wrong entity, leading to agent being picked up from space on L1 spaces, not from account

Summary by CodeRabbit

  • New Features

    • Enhanced license policy application with the addition of an optional agent parameter, allowing for more flexible license management across spaces and subspaces.
  • Bug Fixes

    • Improved error handling by updating exception types for better clarity when entitlements or licenses are not found.

Copy link
Contributor

coderabbitai bot commented Nov 15, 2024

Walkthrough

The pull request introduces changes to the LicenseService and SpaceLicenseService classes. In LicenseService, the error handling logic has been modified to throw EntityNotFoundException instead of RelationshipNotFoundException in specific methods. In SpaceLicenseService, the applyLicensePolicy method's signature has been updated to include an optional agent parameter, allowing for more flexible license policy applications. The overall structure and control flow of the methods remain unchanged, focusing on refining error categorization and enhancing method capabilities.

Changes

File Path Change Summary
src/domain/common/license/license.service.ts Updated exception types in findAndCopyParentEntitlement and getEntitlementsFromLicenseOrFail methods from RelationshipNotFoundException to EntityNotFoundException.
src/domain/space/space/space.service.license.ts Modified applyLicensePolicy method to include an optional agent parameter, affecting how licenses are extended and applied recursively.

Possibly related PRs

  • Add license lookup #4705: This PR adds a license lookup feature that utilizes the LicenseService, which is directly related to the changes made in the LicenseService class in the main PR, particularly in how licenses are handled and retrieved.

Suggested reviewers

  • Comoque1

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.

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

🧹 Outside diff range and nitpick comments (3)
src/domain/space/space/space.service.license.ts (2)

66-69: Correct implementation of agent selection logic.

The use of nullish coalescing (??) ensures proper fallback to space.agent only when necessary, fixing the L0 account agent selection issue.

Consider adding a debug log statement here to track which agent is being used, as this is a critical business logic point that might need monitoring in production.


Line range hint 28-90: Consider implementing agent selection strategy pattern.

The current implementation handles agent selection well, but as the licensing system grows, you might want to consider implementing a strategy pattern for agent selection. This would make it easier to add new agent selection rules in the future.

Example structure:

interface IAgentSelectionStrategy {
  selectAgent(space: Space, providedAgent?: IAgent): IAgent;
}

class DefaultAgentSelectionStrategy implements IAgentSelectionStrategy {
  selectAgent(space: Space, providedAgent?: IAgent): IAgent {
    return providedAgent ?? space.agent;
  }
}
src/domain/common/license/license.service.ts (1)

183-186: Enhance error message with more context.

The change from RelationshipNotFoundException to EntityNotFoundException is appropriate as it better reflects that we're looking for a specific entitlement entity. However, the error message could be more descriptive.

Consider this improvement:

-      throw new EntityNotFoundException(
-        `Parent entitlement not found: ${childEntitlement.type}`,
-        LogContext.LICENSE
-      );
+      throw new EntityNotFoundException(
+        `Parent entitlement of type '${childEntitlement.type}' not found in parent entitlements`,
+        LogContext.LICENSE
+      );
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 83ad95a and 51c8290.

📒 Files selected for processing (2)
  • src/domain/common/license/license.service.ts (2 hunks)
  • src/domain/space/space/space.service.license.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/domain/common/license/license.service.ts (1)

Pattern src/**/*.{ts,js}: Review the TypeScript/JavaScript code for NestJS best practices, dependency injection, module structure, and potential bugs. Ensure that the code adheres to TypeScript's typing system and modern standards.

src/domain/space/space/space.service.license.ts (1)

Pattern src/**/*.{ts,js}: Review the TypeScript/JavaScript code for NestJS best practices, dependency injection, module structure, and potential bugs. Ensure that the code adheres to TypeScript's typing system and modern standards.

🔇 Additional comments (3)
src/domain/space/space/space.service.license.ts (2)

28-31: LGTM! Method signature change improves flexibility.

The addition of the optional agent parameter aligns with the PR objective to fix L0 account agent selection while maintaining backward compatibility.

Let's verify this change doesn't break existing callers:

✅ Verification successful

Method signature change is safe and compatible with existing callers

The verification shows that all existing calls to applyLicensePolicy in the codebase are compatible with the new optional agent parameter:

  • Most calls use only the required spaceID parameter
  • The only call passing the agent parameter is the recursive call within the same service
  • Both AccountLicenseService and SpaceLicenseService implementations maintain their respective signatures
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing calls to applyLicensePolicy to ensure they're compatible
rg "applyLicensePolicy\(" --type ts -B 2 -A 2

Length of output: 7886


87-90: Verify the assumption about subspace agent inheritance.

While passing space.agent to subspaces ensures consistency, please verify if there are cases where subspaces should use their own agents instead of inheriting from the parent space.

Let's check if subspaces can have their own agents:

✅ Verification successful

Passing space.agent to subspaces is the correct implementation

The codebase analysis confirms that subspaces should inherit their parent space's agent. This is evidenced by:

  1. Each space has a single agent property (agent?: IAgent) in the Space entity
  2. During space creation, a new agent is created specifically for that space
  3. The license policy implementation explicitly requires the parent space's agent to be passed down to maintain consistent licensing across the hierarchy

The current implementation correctly ensures license policy consistency by passing the parent's agent to subspaces.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if subspaces can have their own agents
ast-grep --pattern 'class Space {
  $$$
  agent: $_
  $$$
}'

# Check for any special subspace agent handling
rg "subspace.*agent" --type ts

Length of output: 677


Script:

#!/bin/bash
# Check Space class definition and agent initialization
ast-grep --pattern 'class Space {
  $$$
}'

# Check space creation and agent assignment
rg "createSpace.*agent" -A 5 --type ts

Length of output: 1041


Script:

#!/bin/bash
# Check how agent is used in Space entity and service
rg "agent" src/domain/space/space/ -A 3 -B 3 --type ts

# Check if there's any specific agent handling for subspaces
ast-grep --pattern 'function $_(subspace$_) {
  $$$
  agent
  $$$
}'

Length of output: 45176

src/domain/common/license/license.service.ts (1)

197-200: Verify exception handling consistency across the codebase.

The change from RelationshipNotFoundException to EntityNotFoundException is correct as this case specifically handles when the license entity itself is undefined. However, we should verify that this pattern is consistently applied across similar scenarios in the codebase.

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

🧹 Outside diff range and nitpick comments (1)
src/domain/space/space/space.service.license.ts (1)

88-91: Consistent agent propagation ensures proper recursive license assignment

The propagation of rootLevelSpaceAgent to subspaces ensures consistent license policy application throughout the space hierarchy. This is crucial for maintaining proper access control and license management.

Consider documenting this important agent inheritance behavior in the class-level JSDoc comments, as it's a key architectural decision that affects the entire license assignment process.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 51c8290 and 67d3888.

📒 Files selected for processing (1)
  • src/domain/space/space/space.service.license.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/domain/space/space/space.service.license.ts (1)

Pattern src/**/*.{ts,js}: Review the TypeScript/JavaScript code for NestJS best practices, dependency injection, module structure, and potential bugs. Ensure that the code adheres to TypeScript's typing system and modern standards.

🔇 Additional comments (2)
src/domain/space/space/space.service.license.ts (2)

28-31: LGTM! Method signature change improves flexibility

The addition of the optional agent parameter maintains backward compatibility while allowing explicit agent specification, which aligns with the PR's objective to fix agent selection.


65-70: Verify agent inheritance in nested spaces

The agent selection logic correctly implements the fix for L0 account agent selection. The rootLevelSpaceAgent ensures consistent agent usage throughout the license policy application.

Let's verify the agent inheritance pattern:

✅ Verification successful

Let me gather more context about the agent inheritance pattern by checking the implementation of extendLicensePolicy.


Let me try a different approach to understand the license policy extension and space hierarchy.


Let me check the implementation details of the license policy extension to understand how it handles the agent parameter.


Agent inheritance implementation is correct and properly scoped

The verification confirms that the agent selection logic is correctly implemented:

  • The rootLevelSpaceAgent is only used within the license context and properly passed to extendLicensePolicy
  • The implementation handles parent-child space relationships appropriately, with clear separation between space hierarchy and license policy extension
  • The nullish coalescing operator ensures proper fallback to space.agent when no override is provided
  • The variable naming levelZeroSpaceAgent in the method signature reinforces the intended L0 account agent selection
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other potential agent selections in space-related services
rg -t ts "space\.agent" src/domain/space/

Length of output: 1124


Script:

#!/bin/bash
# Search for extendLicensePolicy implementation and usage
ast-grep --pattern 'extendLicensePolicy($$$)'

# Also check for any nested space relationships
rg -t ts "nested.*space" src/domain/space/

Length of output: 92


Script:

#!/bin/bash
# Search for license policy extension implementation
rg -t ts "extendLicensePolicy" -A 5 src/domain/space/

# Look for parent-child space relationships
rg -t ts "parent.*space|child.*space" src/domain/space/

# Check space hierarchy related types/interfaces
fd -e ts . src/domain/space/ --exec grep -l "interface.*Space"

Length of output: 3295


Script:

#!/bin/bash
# Get the implementation of extendLicensePolicy in space service
rg -t ts -A 15 "private async extendLicensePolicy" src/domain/space/space/space.service.license.ts

# Check if there are any other usages of rootLevelSpaceAgent
rg -t ts "rootLevelSpaceAgent" src/domain/space/

Length of output: 1037

@valentinyanakiev valentinyanakiev changed the title Fixed proper L0 account agent selection in recursive license assignment Fixed proper L0 space agent selection in recursive license assignment Nov 18, 2024
@valentinyanakiev valentinyanakiev merged commit e79586c into develop Nov 18, 2024
2 checks passed
@valentinyanakiev valentinyanakiev deleted the fix-assign-subspace-license branch November 18, 2024 10:04
ccanos pushed a commit that referenced this pull request Nov 18, 2024
…#4708)

* Fixed proper L0 account agent selection in recursive license assignment

* provide root space agent for sub-sub space
valentinyanakiev added a commit that referenced this pull request Dec 6, 2024
* initial setup of invoking engines and receiving reponses trough CQRS

* adding the new mesages/handlers

* rename question to input and ask to invoke related to VCs
adds room controller to be used by the server
post replies to rooms and threads

* complete implementation for the Expert engine

* fix build

* address comments and minor cleanups

* change ask guidence question query to mutation
back the guidance chat with a room
implement guidence communication thorugh the event bus

* update quickstart services

* handle guidance room creaton trough the room service

* Generate room on demand

* Chat guidance room created only when needed

* pending reset chat

* it was already done

* address comments

* address some comments

* Entitlements + license services (#4593)

* first pass at two new modules for TemplatesManager, TemplateDefault

* added templates manager to space; removed the SpaceDefaults entity (module still present until move all data to be via defaults

* added templatesManager to platform

* moved creating of default innovatin flow input to space defaults

* back out space type on Template; tidy up Template module to use switch statements

* created template applier module

* tidy up naming

* updated set of default template types

* fixed circular dependency; moved logic for creating collaboration input to space defaults

* removed loading of defaults from files for collaboration content

* removed code based addition of callouts, innovation flow states

* tidy up naming

* added loading of default templates at platform level in to bootstrap

* removed option to create new innovation flow template

* added in migration:

* loading in templates on bootstrap

* added field for collaboration templates on templatesSet; added lookup for templatesManager

* added mutation to create template from collaboration; added logic to prevent template used as default to be deleted; fixed removal of template set on template manager

* initial creation of license + entitlements modules

* add license into account

* updated account to have license service + use that in mutations checking limits, removing notion of soft limits

* ensure data is loaded properly on account for license checking

* added mutation to reset the license calculations on account, including new auth privilege to be able to do so

* renamed Licensing module to LicensingFramework module; trigger license reset on Account after assigning / removing license

* removed usage of LicenseEngine outside of license services on space or account

* renamed entitlement to licenseEntitlement as entity; first pass at migration

* fixed issues in migration

* fixed issues related to auth reset; tidied up loader creator imports

* fixed auth cascade for templates of type post

* license reset running

* reset licenses on space after adding / removing license plans

* removed need for license check in community; added entitlement check in roleset when adding a VC

* remove auth reset when assigning / removing license plans

* added License to RoleSet

* added license to collaboration

* tidied up retrieval of license for whiteboard; added license to collaboration in migration

* fix typo; fix space spec file

* fix additional tests

* moved tempaltesManager to last migration in the list

* fixed retrieval of template when creating collaboration

* added logging

* fixed bootstrap setting of templates

* refactored inputCreator to do the data loading closer to usage; fixed picking up of templates; fixed bootstrap usage of templates

* added ability to retrieve limits on entitlements + current usage

* updated field names on entitlements

* updated field names on entitlements

* fixed account mutaiton logic bug

* ensure that licenses are reset when assigning beta tester or vc campaign role to a user

* added reset all account licenses mutation

* fixed bug on space entitlements; refactored code to reduce duplication

* fixed url generation for templates inside of TempaltesManager

* fixed bootstrap order to create forum earlier

* ensure collaboration creation on template provides some defaults for callouts

* fix deletion of templates of type post

* ensure more data is defaulted inside of template service for collaboration; add setting of isTemplate field on Collaboration, and also on contained Callouts

* ensure isTempalte is passed to Collaboration entity

* fixed groups in bootstrap space template; updated signature for creating callout from collaboration

* fixed missing field

* fixed type on mutation to create from collaboration

* fixed typo

* fixed groups in bootstrap space template; updated signature for creating callout from collaboration

* fixed missing field

* fixed type on mutation to create from collaboration

* fixed typo

* reworked applying collaboraiton template to collaboration

* improved error message in wrong type of ID passed in

* fixed build

* made migration last in the list

* rename migration to be last

* removed read check when looking up collaboration

* track free / plus / premium space entitlements separately

* updated migration order

* removed duplicate migration

* moved auth reset to mutation for applying the template to another collaboration

* extend lookup of entitlement usage to cover new types

* updaed license policy to reflect new entitlements; made license engine work with entitlements, not license privileges; removed license privilege (no longer relevant)

* updated migration to not drop indexes already removed

* fix for license reset on space

* added license policy rule for free space credential

* ensure license entitlements are reset as part of the bootstrap

* fixed typo

* extended reset all to include resetting licenses on accounts + AI server; moved migration to be last

* Address pr comment

* Address PR feedback

* Address PR comment

* Address PR comments

* Address PR comments

* Address PR comment

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Improved types & naming

* Address PR comments

* Fixed switch-case logic in entitlements

* Converge entitlements schema

* Remove unused AuthorizationPrivilege

---------

Co-authored-by: Carlos Cano <[email protected]>
Co-authored-by: Valentin Yanakiev <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Major version bump

* Add license lookup

* removed redundant checks

* Fixed proper L0 space agent selection in recursive license assignment (#4708)

* Fixed proper L0 account agent selection in recursive license assignment

* provide root space agent for sub-sub space

* Look up correct entitlement for VC creation (#4707)

Co-authored-by: Evgeni Dimitrov <[email protected]>

* filter out demo spaces for unauthenticated users search in elastic (#4712)

* filter out demo spaces for unauthenticated users search in elastic

* improvements

---------

Co-authored-by: Svetoslav <[email protected]>

* get guidance room from user and not from me

* Finish

* wrapping up

* fix roomId missing

* Put the GuidanceVC into the platform

* Guidance VC created on bootstrap

* add support for guidance ingest

* cleanup and handle sources label

* fix build

* address comments and update engine images

---------

Co-authored-by: Valentin Yanakiev <[email protected]>
Co-authored-by: Carlos Cano <[email protected]>
Co-authored-by: Neil Smyth <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Evgeni Dimitrov <[email protected]>
Co-authored-by: Svetoslav <[email protected]>
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