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

Fix device integration filter for entityless devices #21136

Conversation

karwosts
Copy link
Contributor

@karwosts karwosts commented Jun 22, 2024

Proposed change

The current way we lookup device integrations is to use a core command to get the integration for every entity, and then check all the entities of a device, and then map the integrations of those entities to the device.

This does not work for devices without entities, as per #21060. This change leverages the config registry to get all the config entries when needed, and then checks the config entries for a device and gets the domains from there.

I'm not confident if this method should be used in addition to the existing per entity lookup, or if it can entirely replace the old method. Not sure if devices can have multiple domains or can have entities from different domains. So to be safe I just added this check in addition to the previous check, so it just adds more possible integrations that a device can be associated with.

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New feature (thank you!)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Example configuration

Additional information

Checklist

  • The code change is tested and works locally.
  • There is no commented out code in this PR.
  • Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

Summary by CodeRabbit

  • New Features

    • Enhanced area, device, and floor selectors to include configuration entries for improved integration.
  • Bug Fixes

    • Improved device lookup reliability by using more robust data structures and methods.

Copy link
Contributor

coderabbitai bot commented Jun 22, 2024

Walkthrough

Walkthrough

The recent changes aim to enhance the HaAreaSelector, HaDeviceSelector, and HaFloorSelector components by incorporating configuration entries (_configEntries) into their state. This addition allows these components to consider devices without entities during the lookup process, addressing issues where device selectors would omit such devices. The enhancements include asynchronous fetching of config entries and updating device integration lookup methods to use these entries.

Changes

Files/Paths Change Summary
.../ha-selector/ha-selector-area.ts Introduced _configEntries state, fetched config entries in connectedCallback, and updated deviceIntegrationLookup.
.../ha-selector/ha-selector-device.ts Added _configEntries state, integrated fetching in connectedCallback, updated _deviceIntegrationLookup.
.../ha-selector/ha-selector-floor.ts Included _configEntries state, fetched config entries asynchronously, and utilized in _deviceIntegrationLookup.
.../src/data/device_registry.ts Enhanced getDeviceIntegrationLookup to accept devices and configEntries as parameters.
.../src/data/selector.ts Updated filterSelectorDevices to use Set for deviceIntegrationLookup and adjusted inclusion logic.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant HaAreaSelector
    participant HaDeviceSelector
    participant HaFloorSelector
    participant ConfigEntryService
    participant DeviceRegistry
    participant FilterSelectorDevices

    User->>HaAreaSelector: Select Device
    HaAreaSelector->>ConfigEntryService: Fetch config entries
    ConfigEntryService-->>HaAreaSelector: Return config entries
    HaAreaSelector->>DeviceRegistry: Get devices and config entries
    DeviceRegistry-->>HaAreaSelector: Return device integration lookup
    HaAreaSelector->>FilterSelectorDevices: Apply filter to devices with integration lookup

    User->>HaDeviceSelector: Select Device
    HaDeviceSelector->>ConfigEntryService: Fetch config entries
    ConfigEntryService-->>HaDeviceSelector: Return config entries
    HaDeviceSelector->>DeviceRegistry: Get devices and config entries
    DeviceRegistry-->>HaDeviceSelector: Return device integration lookup
    HaDeviceSelector->>FilterSelectorDevices: Apply filter to devices with integration lookup

    User->>HaFloorSelector: Select Device
    HaFloorSelector->>ConfigEntryService: Fetch config entries
    ConfigEntryService-->>HaFloorSelector: Return config entries
    HaFloorSelector->>DeviceRegistry: Get devices and config entries
    DeviceRegistry-->>HaFloorSelector: Return device integration lookup
    HaFloorSelector->>FilterSelectorDevices: Apply filter to devices with integration lookup
Loading

Assessment against linked issues

Objective (Issue #21060) Addressed Explanation
Devices with filters should not exclude devices without entities
Use configuration entries in device lookups
Fix integration filter to consider devices regardless of entities

Recent review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between 373a0ad and 88f73d7.

Files selected for processing (2)
  • src/data/device_registry.ts (2 hunks)
  • src/data/selector.ts (2 hunks)
Additional context used
Biome
src/data/device_registry.ts

[error] 158-158: Forbidden non-null assertion. (lint/style/noNonNullAssertion)


[error] 159-159: Forbidden non-null assertion. (lint/style/noNonNullAssertion)


[error] 160-160: Forbidden non-null assertion. (lint/style/noNonNullAssertion)


[error] 149-149: Excessive complexity detected. (lint/complexity/noExcessiveCognitiveComplexity)

Please refactor this function to reduce its complexity score from 17 to the max allowed complexity 15.

src/data/selector.ts

[error] 340-340: Unexpected any. Specify a different type. (lint/suspicious/noExplicitAny)

any disables many type checking rules. Its use should be avoided.


[error] 364-364: Unexpected any. Specify a different type. (lint/suspicious/noExplicitAny)

any disables many type checking rules. Its use should be avoided.


[error] 689-689: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator


[error] 727-727: Excessive complexity detected. (lint/complexity/noExcessiveCognitiveComplexity)

Please refactor this function to reduce its complexity score from 18 to the max allowed complexity 15.


[error] 784-786: Forbidden non-null assertion. (lint/style/noNonNullAssertion)


[error] 812-814: Forbidden non-null assertion. (lint/style/noNonNullAssertion)


[error] 92-92: Don't use '{}' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the object shape. '{}' means "any non-nullable value".


[error] 104-104: Don't use '{}' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the object shape. '{}' means "any non-nullable value".


[error] 109-109: Don't use '{}' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the object shape. '{}' means "any non-nullable value".


[error] 155-155: Don't use '{}' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the object shape. '{}' means "any non-nullable value".


[error] 160-160: Don't use '{}' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the object shape. '{}' means "any non-nullable value".


[error] 296-296: Don't use '{}' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the object shape. '{}' means "any non-nullable value".


[error] 314-314: Don't use '{}' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the object shape. '{}' means "any non-nullable value".


[error] 329-329: Don't use '{}' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the object shape. '{}' means "any non-nullable value".


[error] 359-359: Don't use '{}' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the object shape. '{}' means "any non-nullable value".


[error] 372-372: Don't use '{}' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the object shape. '{}' means "any non-nullable value".


[error] 421-421: Don't use '{}' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the object shape. '{}' means "any non-nullable value".


[error] 429-429: Don't use '{}' as a type. (lint/complexity/noBannedTypes)

Prefer explicitly define the object shape. '{}' means "any non-nullable value".


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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
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: 3

Outside diff range comments (4)
src/components/ha-selector/ha-selector-device.ts (1)

Line range hint 147-147: Remove non-null assertion.

Using non-null assertions can lead to runtime errors if not handled properly. It's safer to use optional chaining.

-  const deviceIntegrations = this._entitySources ? this._deviceIntegrationLookup(this._entitySources, Object.values(this.hass.entities), Object.values(this.hass.devices), this._configEntries) : undefined;
+  const deviceIntegrations = this._entitySources ? this._deviceIntegrationLookup(this._entitySources, Object.values(this.hass.entities), Object.values(this.hass.devices), this._configEntries!) : undefined;
src/components/ha-selector/ha-selector-area.ts (1)

Line range hint 29-29: Avoid using any type for the value property.

It's recommended to specify a more precise type instead of any to leverage TypeScript's type checking.

-  @property() public value?: any;
+  @property() public value?: AreaSelector[] | AreaSelector;
src/components/ha-selector/ha-selector-floor.ts (1)

Line range hint 29-29: Avoid using any type for the value property.

It's better to specify a more specific type instead of any to fully utilize TypeScript's type safety features.

-  @property() public value?: any;
+  @property() public value?: FloorSelector[] | FloorSelector;
src/data/device_registry.ts (1)

Line range hint 158-158: Remove non-null assertions.

Non-null assertions can lead to runtime errors if not properly handled. It's safer to use optional chaining.

-    if (!deviceIntegrations[entity.device_id!]) {
+    if (!deviceIntegrations[entity.device_id]) {
-      deviceIntegrations[entity.device_id!] = [];
+      deviceIntegrations[entity.device_id] = [];
    }
-    deviceIntegrations[entity.device_id!].push(source.domain);
+    deviceIntegrations[entity.device_id]?.push(source.domain);

Also applies to: 159-159, 161-161

src/data/device_registry.ts Outdated Show resolved Hide resolved
if (entry?.domain) {
(
deviceIntegrations[device.id] ||
(deviceIntegrations[device.id] = [])
Copy link
Contributor

@coderabbitai coderabbitai bot Jun 22, 2024

Choose a reason for hiding this comment

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

Avoid assignment within an expression.

Using assignments within expressions can be confusing. It's clearer to separate them.

-          (deviceIntegrations[device.id] || (deviceIntegrations[device.id] = [])).push(entry.domain);
+          deviceIntegrations[device.id] = deviceIntegrations[device.id] || [];
+          deviceIntegrations[device.id].push(entry.domain);
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
(deviceIntegrations[device.id] = [])
deviceIntegrations[device.id] = deviceIntegrations[device.id] || [];
deviceIntegrations[device.id].push(entry.domain);
Tools
Biome

[error] 174-174: The assignment should not be in an expression. (lint/suspicious/noAssignInExpressions)

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

Copy link
Member

Choose a reason for hiding this comment

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

I do agree with coderabbit on this

Copy link
Contributor

Choose a reason for hiding this comment

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

@bramkragten, I'm glad you agree with the suggestion! If you need further assistance or have more questions as you implement this change, feel free to reach out. Happy coding! 🚀


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

(
deviceIntegrations[device.id] ||
(deviceIntegrations[device.id] = [])
).push(entry.domain);
Copy link
Member

Choose a reason for hiding this comment

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

We will probably add domains multiple time now for devices with entities, should we check if the domain is already in there?

Copy link
Contributor Author

@karwosts karwosts Jun 26, 2024

Choose a reason for hiding this comment

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

The original code above (ln 158) seems to push the domain once per entity already, without ill effect, so I was just going with similar. I could adds checks to avoid duplicates if that's helpful.

Copy link
Member

@bramkragten bramkragten Jun 26, 2024

Choose a reason for hiding this comment

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

Maybe best to just make it a Set?

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

Outside diff range comments (1)
src/data/selector.ts (1)

Line range hint 699-716: Improve handling of optional properties.

Using optional chaining (?.) instead of non-null assertions (!) can prevent runtime errors if the property is undefined.

- if (!deviceIntegrationLookup?.[device.id]?.has(filterIntegration)) {
+ if (!deviceIntegrationLookup?.[device.id].has(filterIntegration)) {
    return false;
  }

Comment on lines +158 to +160
deviceIntegrations[entity.device_id!] =
deviceIntegrations[entity.device_id!] || new Set<string>();
deviceIntegrations[entity.device_id!].add(source.domain);
Copy link
Contributor

Choose a reason for hiding this comment

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

Avoid non-null assertions.

The non-null assertion operator ! is used here, which can lead to runtime errors if the value is actually null. Consider using optional chaining or proper checks before accessing properties.

- deviceIntegrations[entity.device_id!] = deviceIntegrations[entity.device_id!] || new Set<string>();
- deviceIntegrations[entity.device_id!].add(source.domain);
+ deviceIntegrations[entity.device_id] = deviceIntegrations[entity.device_id] || new Set<string>();
+ if (deviceIntegrations[entity.device_id]) {
+   deviceIntegrations[entity.device_id].add(source.domain);
+ }
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
deviceIntegrations[entity.device_id!] =
deviceIntegrations[entity.device_id!] || new Set<string>();
deviceIntegrations[entity.device_id!].add(source.domain);
deviceIntegrations[entity.device_id] =
deviceIntegrations[entity.device_id] || new Set<string>();
if (deviceIntegrations[entity.device_id]) {
deviceIntegrations[entity.device_id].add(source.domain);
}
Tools
Biome

[error] 158-158: Forbidden non-null assertion. (lint/style/noNonNullAssertion)


[error] 159-159: Forbidden non-null assertion. (lint/style/noNonNullAssertion)


[error] 160-160: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Comment on lines +149 to +172
): Record<string, Set<string>> => {
const deviceIntegrations: Record<string, Set<string>> = {};

for (const entity of entities) {
const source = entitySources[entity.entity_id];
if (!source?.domain || entity.device_id === null) {
continue;
}

if (!deviceIntegrations[entity.device_id!]) {
deviceIntegrations[entity.device_id!] = [];
deviceIntegrations[entity.device_id!] =
deviceIntegrations[entity.device_id!] || new Set<string>();
deviceIntegrations[entity.device_id!].add(source.domain);
}
// Lookup devices that have no entities
if (devices && configEntries) {
for (const device of devices) {
for (const config_entry_id of device.config_entries) {
const entry = configEntries.find((e) => e.entry_id === config_entry_id);
if (entry?.domain) {
deviceIntegrations[device.id] =
deviceIntegrations[device.id] || new Set<string>();
deviceIntegrations[device.id].add(entry.domain);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider refactoring to reduce complexity.

The getDeviceIntegrationLookup function has been flagged for excessive complexity. Breaking down this function into smaller, more manageable parts could enhance readability and maintainability.

- export const getDeviceIntegrationLookup = (
+ function addEntityIntegrations(deviceIntegrations, entitySources, entities) {
+   for (const entity of entities) {
+     const source = entitySources[entity.entity_id];
+     if (!source?.domain || entity.device_id === null) {
+       continue;
+     }
+     deviceIntegrations[entity.device_id] = deviceIntegrations[entity.device_id] || new Set<string>();
+     deviceIntegrations[entity.device_id].add(source.domain);
+   }
+ }
+
+ function addDeviceConfigIntegrations(deviceIntegrations, devices, configEntries) {
+   for (const device of devices) {
+     for (const config_entry_id of device.config_entries) {
+       const entry = configEntries.find((e) => e.entry_id === config_entry_id);
+       if (entry?.domain) {
+         deviceIntegrations[device.id] = deviceIntegrations[device.id] || new Set<string>();
+         deviceIntegrations[device.id].add(entry.domain);
+       }
+     }
+   }
+ }
+
+ export const getDeviceIntegrationLookup = (
    entitySources: EntitySources,
    entities: EntityRegistryDisplayEntry[] | EntityRegistryEntry[],
    devices?: DeviceRegistryEntry[],
    configEntries?: ConfigEntry[]
  ): Record<string, Set<string>> => {
    const deviceIntegrations: Record<string, Set<string>> = {};
    addEntityIntegrations(deviceIntegrations, entitySources, entities);
    if (devices && configEntries) {
      addDeviceConfigIntegrations(deviceIntegrations, devices, configEntries);
    }
    return deviceIntegrations;
  };
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
): Record<string, Set<string>> => {
const deviceIntegrations: Record<string, Set<string>> = {};
for (const entity of entities) {
const source = entitySources[entity.entity_id];
if (!source?.domain || entity.device_id === null) {
continue;
}
if (!deviceIntegrations[entity.device_id!]) {
deviceIntegrations[entity.device_id!] = [];
deviceIntegrations[entity.device_id!] =
deviceIntegrations[entity.device_id!] || new Set<string>();
deviceIntegrations[entity.device_id!].add(source.domain);
}
// Lookup devices that have no entities
if (devices && configEntries) {
for (const device of devices) {
for (const config_entry_id of device.config_entries) {
const entry = configEntries.find((e) => e.entry_id === config_entry_id);
if (entry?.domain) {
deviceIntegrations[device.id] =
deviceIntegrations[device.id] || new Set<string>();
deviceIntegrations[device.id].add(entry.domain);
}
}
function addEntityIntegrations(deviceIntegrations, entitySources, entities) {
for (const entity of entities) {
const source = entitySources[entity.entity_id];
if (!source?.domain || entity.device_id === null) {
continue;
}
deviceIntegrations[entity.device_id] = deviceIntegrations[entity.device_id] || new Set<string>();
deviceIntegrations[entity.device_id].add(source.domain);
}
}
function addDeviceConfigIntegrations(deviceIntegrations, devices, configEntries) {
for (const device of devices) {
for (const config_entry_id of device.config_entries) {
const entry = configEntries.find((e) => e.entry_id === config_entry_id);
if (entry?.domain) {
deviceIntegrations[device.id] = deviceIntegrations[device.id] || new Set<string>();
deviceIntegrations[device.id].add(entry.domain);
}
}
}
}
export const getDeviceIntegrationLookup = (
entitySources: EntitySources,
entities: EntityRegistryDisplayEntry[] | EntityRegistryEntry[],
devices?: DeviceRegistryEntry[],
configEntries?: ConfigEntry[]
): Record<string, Set<string>> => {
const deviceIntegrations: Record<string, Set<string>> = {};
addEntityIntegrations(deviceIntegrations, entitySources, entities);
if (devices && configEntries) {
addDeviceConfigIntegrations(deviceIntegrations, devices, configEntries);
}
return deviceIntegrations;
};
Tools
Biome

[error] 158-158: Forbidden non-null assertion. (lint/style/noNonNullAssertion)


[error] 159-159: Forbidden non-null assertion. (lint/style/noNonNullAssertion)


[error] 160-160: Forbidden non-null assertion. (lint/style/noNonNullAssertion)


[error] 149-149: Excessive complexity detected. (lint/complexity/noExcessiveCognitiveComplexity)

Please refactor this function to reduce its complexity score from 17 to the max allowed complexity 15.

@bramkragten bramkragten added this to the 2024.7 milestone Jun 27, 2024
@bramkragten bramkragten merged commit 7aa005e into home-assistant:dev Jun 27, 2024
13 checks passed
@karwosts karwosts deleted the fix-device-integration-filter-no-entity branch June 27, 2024 12:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Device selector with filter removes devices without entities
2 participants