Skip to content

refactor: extract duplicate logic from observability filters and hooks into reusable utils#495

Merged
akila-i merged 7 commits intoopenchoreo:mainfrom
akila-i:obs-refactor-duplicates
Apr 7, 2026
Merged

refactor: extract duplicate logic from observability filters and hooks into reusable utils#495
akila-i merged 7 commits intoopenchoreo:mainfrom
akila-i:obs-refactor-duplicates

Conversation

@akila-i
Copy link
Copy Markdown
Contributor

@akila-i akila-i commented Apr 7, 2026

Purpose

This pull request refactors and unifies the time range filter logic and debounced search handling across the observability plugin's filter components. It removes duplicated code, centralizes shared constants and utilities, and introduces a new hook for auto-selecting the first environment when none is selected. The changes also move the calculateTimeRange utility to a shared package for broader reuse.

Key changes:

Refactoring and Code Reuse

  • Replaces component-local time range options (e.g., ALERTS_TIME_RANGE_OPTIONS, INCIDENTS_TIME_RANGE_OPTIONS, etc.) with a single shared TIME_RANGE_OPTIONS imported from ../../types, ensuring consistency across all filter components. [1] [2] [3] [4] [5]
  • Removes duplicated calculateTimeRange functions from local utility files and imports it from the shared @openchoreo/backstage-plugin-react package, both in implementation and tests. [1] [2] [3] [4] [5]

Improved Debounced Search

  • Replaces manual debounce logic (using useDebounce or useEffect/setTimeout) in all filter components with a unified custom hook, useDebouncedSearch, simplifying code and standardizing behavior. [1] [2] [3] [4] [5]

Type and Import Cleanups

  • Cleans up unused imports and consolidates type imports for better code clarity and maintainability in filter components and their type files. [1] [2] [3] [4] [5] [6] [7] [8] [9]

New Utility Hook

  • Adds a new hook, useAutoSelectFirstEnvironment, which ensures that if no valid environment is selected in the URL query parameters, the first available environment is automatically selected. This helps maintain valid state across all URL filter hooks.

Goals

Describe the solutions that this feature/fix will introduce to resolve the problems described above

Approach

Describe how you are implementing the solutions. Include an animated GIF or screenshot if the change affects the UI (email documentation@wso2.com to review all UI text). Include a link to a Markdown file or Google doc if the feature write-up is too long to paste here.

User stories

Summary of user stories addressed by this change>

Release note

Brief description of the new feature or bug fix as it will appear in the release notes

Documentation

Link(s) to product documentation that addresses the changes of this PR. If no doc impact, enter “N/A” plus brief explanation of why there’s no doc impact

Training

Link to the PR for changes to the training content in https://github.com/wso2/WSO2-Training, if applicable

Certification

Type “Sent” when you have provided new/updated certification questions, plus four answers for each question (correct answer highlighted in bold), based on this change. Certification questions/answers should be sent to certification@wso2.com and NOT pasted in this PR. If there is no impact on certification exams, type “N/A” and explain why.

Marketing

Link to drafts of marketing content that will describe and promote this feature, including product page changes, technical articles, blog posts, videos, etc., if applicable

Automation tests

  • Unit tests

    Code coverage information

  • Integration tests

    Details about the test cases and coverage

Security checks

Samples

Provide high-level details about the samples related to this feature

Related PRs

List any other related PRs

Migrations (if applicable)

Describe migration steps and platforms on which migration has been tested

Test environment

List all JDK versions, operating systems, databases, and browser/versions on which this feature/fix was tested

Learning

Describe the research phase and any blog posts, patterns, libraries, or add-ons you used to solve the problem.

Summary by CodeRabbit

  • New Features

    • Automatically selects the first available environment when none is specified in the URL.
  • Refactor

    • Unified debounced search behavior across filters via a shared hook.
    • Consolidated time-range computation to a shared utility used by multiple features.
    • Moved environment auto-selection logic into a reusable hook.
  • Tests

    • Updated test mocks to align with the shared time-range utility.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 7, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: cf98f803-79d7-4539-b94d-a2e9970c39cd

📥 Commits

Reviewing files that changed from the base of the PR and between 4e380ed and 228a250.

📒 Files selected for processing (2)
  • plugins/openchoreo-observability/src/components/Traces/ObservabilityTracesPage.test.tsx
  • plugins/openchoreo-observability/src/hooks/useAutoSelectFirstEnvironment.ts
✅ Files skipped from review due to trivial changes (1)
  • plugins/openchoreo-observability/src/components/Traces/ObservabilityTracesPage.test.tsx

📝 Walkthrough

Walkthrough

Refactors observability plugin to centralize debounced search and environment auto-selection via two new hooks, removes local time-range utilities/constants, and updates components and hooks to import shared calculateTimeRange/TIME_RANGE_OPTIONS from @openchoreo/backstage-plugin-react.

Changes

Cohort / File(s) Summary
New Hooks
plugins/openchoreo-observability/src/hooks/useDebouncedSearch.ts, plugins/openchoreo-observability/src/hooks/useAutoSelectFirstEnvironment.ts
Added useDebouncedSearch (local search state + debounced onChange) and useAutoSelectFirstEnvironment (auto-corrects env URL param to first environment or canonical name).
Filter Components
plugins/openchoreo-observability/src/components/Alerts/AlertsFilter.tsx, plugins/openchoreo-observability/src/components/Incidents/IncidentsFilter.tsx, plugins/openchoreo-observability/src/components/RCA/RCAFilters.tsx, plugins/openchoreo-observability/src/components/RuntimeLogs/LogsFilter.tsx, plugins/openchoreo-observability/src/components/Traces/TracesFilters.tsx
Replaced per-component search state/effect/debounce logic with useDebouncedSearch; onChange now uses hook-provided handler; imports updated to use centralized TIME_RANGE_OPTIONS.
Filter Types
plugins/openchoreo-observability/src/components/Alerts/types.ts, plugins/openchoreo-observability/src/components/Incidents/types.ts, plugins/openchoreo-observability/src/components/RuntimeLogs/types.ts
Removed local re-exports and duplicated TIME_RANGE_OPTIONS and some summary type re-exports (AlertSummary, IncidentSummary).
Time Range Utilities (removed)
plugins/openchoreo-observability/src/components/Traces/utils.ts, plugins/openchoreo-observability/src/components/RuntimeLogs/utils.ts
Deleted local calculateTimeRange implementations; callers now import shared calculateTimeRange.
Time Range Usage / Tests
plugins/openchoreo-observability/src/components/Traces/ObservabilityTracesPage.tsx, .../Traces/utils.test.ts, .../Traces/ObservabilityTracesPage.test.tsx
Switched imports to external calculateTimeRange; added Jest mock for external calculateTimeRange in tests.
URL Filter Hooks
plugins/openchoreo-observability/src/hooks/useUrlFilters.ts, .../useUrlFiltersForAlerts.ts, .../useUrlFiltersForIncidents.ts, .../useUrlFiltersForRuntimeLogs.ts
Removed inline env-validation effects; delegated env auto-selection to useAutoSelectFirstEnvironment; validation of timeRange/severity updated to use centralized TIME_RANGE_OPTIONS/ALERT_SEVERITIES.
Time Range-Dependent Hooks
plugins/openchoreo-observability/src/hooks/useComponentAlerts.ts, .../useMetrics.ts, .../useProjectIncidents.ts, .../useProjectRuntimeLogs.ts, .../useRuntimeLogs.ts, .../useTraces.ts
Replaced local calculateTimeRange imports/implementations with @openchoreo/backstage-plugin-react shared calculateTimeRange.
Tests / Mocks
plugins/openchoreo-observability/src/components/Traces/ObservabilityTracesPage.test.tsx
Extended Jest mock to provide calculateTimeRange returning fixed start/end timestamps.
Removed constants/exports
plugins/openchoreo-observability/src/components/Alerts/types.ts, .../Incidents/types.ts, .../RuntimeLogs/types.ts
Removed exported ALERTS_TIME_RANGE_OPTIONS, INCIDENTS_TIME_RANGE_OPTIONS, and TIME_RANGE_OPTIONS duplicates from local type files.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant TextField as SearchInput
  participant Hook as useDebouncedSearch
  participant Component as ParentComponent
  User->>TextField: types characters
  TextField->>Hook: onChange events
  Hook->>Hook: update local searchInput
  Hook-->>Hook: debounce timer (e.g., 500-1000ms)
  Hook->>Component: onChange callback with debounced searchQuery
  Component->>Component: call onFiltersChange({ searchQuery })
Loading
sequenceDiagram
  participant Component as FilterHook/Component
  participant AutoHook as useAutoSelectFirstEnvironment
  participant Envs as Environments
  participant URL as URLSearchParams/setSearchParams
  Component->>AutoHook: mount or searchParams change (environments, searchParams)
  AutoHook->>Envs: read environments list
  AutoHook->>URL: read current env param
  alt env missing or not matching canonical
    AutoHook->>URL: set env to Envs[0].name (setSearchParams with replace:true)
  else env matches but not canonical name
    AutoHook->>URL: rewrite env to canonical name (replace:true)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Suggested reviewers

  • kaviththiranga
  • sameerajayasoma
  • jhivandb

Poem

🐰
I hopped through hooks and tidied the trail,
Debounced my whispers down the data vale,
Time ranges moved to a shared chest so neat,
Env names aligned — my job's complete! ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides a comprehensive Purpose section with key changes listed, but most other required template sections (Goals, Approach, User stories, Release note, Documentation, etc.) are incomplete or contain only template placeholders. Complete the remaining template sections: Goals, Approach, User stories, Release note, Documentation, Training, Certification, Marketing, Automation tests, Security checks, Samples, Related PRs, Migrations, Test environment, and Learning to fully document this refactoring effort.
Docstring Coverage ⚠️ Warning Docstring coverage is 44.44% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main refactoring objective: extracting and centralizing duplicate logic from observability filters and hooks into reusable utilities and hooks.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands and usage tips.

akila-i added 6 commits April 7, 2026 12:05
Signed-off-by: Akila-I <akila.99g@gmail.com>
Signed-off-by: Akila-I <akila.99g@gmail.com>
…mary

Signed-off-by: Akila-I <akila.99g@gmail.com>
…ve duplicates

Signed-off-by: Akila-I <akila.99g@gmail.com>
…r components

Signed-off-by: Akila-I <akila.99g@gmail.com>
@akila-i akila-i force-pushed the obs-refactor-duplicates branch from cd5d72b to 4e380ed Compare April 7, 2026 06:36
Copy link
Copy Markdown

@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

🧹 Nitpick comments (1)
plugins/openchoreo-observability/src/hooks/useUrlFiltersForAlerts.ts (1)

37-41: Normalize severity tokens before validation.

Whitespace around comma-separated severity values is currently treated as invalid. Trimming before validation makes URL parsing more robust.

Suggested refactor
     const severity = severityParam
       ? severityParam
           .split(',')
+          .map(s => s.trim())
           .filter(
             s =>
               Boolean(s) && (ALERT_SEVERITIES as readonly string[]).includes(s),
           )
       : [];
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@plugins/openchoreo-observability/src/hooks/useUrlFiltersForAlerts.ts` around
lines 37 - 41, The filter is rejecting values with surrounding whitespace; in
useUrlFiltersForAlerts.ts update the split/filter pipeline to trim each token
before validation so ALERT_SEVERITIES checks the normalized value (e.g., use
s.trim() in the predicate and, if tokens are propagated later, map to the
trimmed value) — change the lambda that uses (ALERT_SEVERITIES as readonly
string[]).includes(s) to perform includes(s.trim()) and ensure downstream code
uses the trimmed token.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@plugins/openchoreo-observability/src/components/Traces/ObservabilityTracesPage.test.tsx`:
- Around line 14-17: The mock implementation of calculateTimeRange uses new
Date().toISOString(), making tests time-dependent; update the calculateTimeRange
mock in ObservabilityTracesPage.test.tsx to return deterministic, fixed ISO
timestamps with a non-zero interval (e.g., a fixed start and a later end) so
startTime/endTime wiring is stable and reproducible during tests.

In `@plugins/openchoreo-observability/src/hooks/useAutoSelectFirstEnvironment.ts`:
- Around line 19-23: The current isValid check only accepts exact envParam ===
e.name, causing URLs that matched by displayName or case-insensitive name (as
handled in useUrlFilters) to be treated invalid and rewritten to
environments[0]; update the validation and rewrite logic in
useAutoSelectFirstEnvironment (the isValid variable that reads envParam and the
branch that creates newParams and calls setSearchParams) to consider a match
when envParam equals e.name, equals e.displayName, or equals e.name
case-insensitively, and if a match is found set the env param to that matched
environment's canonical e.name (instead of forcing environments[0].name); keep
falling back to environments[0].name only when no such match exists.

---

Nitpick comments:
In `@plugins/openchoreo-observability/src/hooks/useUrlFiltersForAlerts.ts`:
- Around line 37-41: The filter is rejecting values with surrounding whitespace;
in useUrlFiltersForAlerts.ts update the split/filter pipeline to trim each token
before validation so ALERT_SEVERITIES checks the normalized value (e.g., use
s.trim() in the predicate and, if tokens are propagated later, map to the
trimmed value) — change the lambda that uses (ALERT_SEVERITIES as readonly
string[]).includes(s) to perform includes(s.trim()) and ensure downstream code
uses the trimmed token.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: fba7034e-305a-45a4-acd1-3db497e69bc1

📥 Commits

Reviewing files that changed from the base of the PR and between 15f2526 and 4e380ed.

📒 Files selected for processing (25)
  • plugins/openchoreo-observability/src/components/Alerts/AlertsFilter.tsx
  • plugins/openchoreo-observability/src/components/Alerts/types.ts
  • plugins/openchoreo-observability/src/components/Incidents/IncidentsFilter.tsx
  • plugins/openchoreo-observability/src/components/Incidents/types.ts
  • plugins/openchoreo-observability/src/components/RCA/RCAFilters.tsx
  • plugins/openchoreo-observability/src/components/RuntimeLogs/LogsFilter.tsx
  • plugins/openchoreo-observability/src/components/RuntimeLogs/types.ts
  • plugins/openchoreo-observability/src/components/RuntimeLogs/utils.ts
  • plugins/openchoreo-observability/src/components/Traces/ObservabilityTracesPage.test.tsx
  • plugins/openchoreo-observability/src/components/Traces/ObservabilityTracesPage.tsx
  • plugins/openchoreo-observability/src/components/Traces/TracesFilters.tsx
  • plugins/openchoreo-observability/src/components/Traces/utils.test.ts
  • plugins/openchoreo-observability/src/components/Traces/utils.ts
  • plugins/openchoreo-observability/src/hooks/useAutoSelectFirstEnvironment.ts
  • plugins/openchoreo-observability/src/hooks/useComponentAlerts.ts
  • plugins/openchoreo-observability/src/hooks/useDebouncedSearch.ts
  • plugins/openchoreo-observability/src/hooks/useMetrics.ts
  • plugins/openchoreo-observability/src/hooks/useProjectIncidents.ts
  • plugins/openchoreo-observability/src/hooks/useProjectRuntimeLogs.ts
  • plugins/openchoreo-observability/src/hooks/useRuntimeLogs.ts
  • plugins/openchoreo-observability/src/hooks/useTraces.ts
  • plugins/openchoreo-observability/src/hooks/useUrlFilters.ts
  • plugins/openchoreo-observability/src/hooks/useUrlFiltersForAlerts.ts
  • plugins/openchoreo-observability/src/hooks/useUrlFiltersForIncidents.ts
  • plugins/openchoreo-observability/src/hooks/useUrlFiltersForRuntimeLogs.ts
💤 Files with no reviewable changes (5)
  • plugins/openchoreo-observability/src/components/RuntimeLogs/types.ts
  • plugins/openchoreo-observability/src/components/Alerts/types.ts
  • plugins/openchoreo-observability/src/components/Incidents/types.ts
  • plugins/openchoreo-observability/src/components/RuntimeLogs/utils.ts
  • plugins/openchoreo-observability/src/components/Traces/utils.ts

Comment thread plugins/openchoreo-observability/src/hooks/useAutoSelectFirstEnvironment.ts Outdated
…nment selection logic

Signed-off-by: Akila-I <akila.99g@gmail.com>
@akila-i
Copy link
Copy Markdown
Contributor Author

akila-i commented Apr 7, 2026

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 7, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@stefinie123
Copy link
Copy Markdown
Contributor

@akila-i In many obs related views we use the same set of filters right ? Like Environment, Time Range and so on. Can we consider adding reusable UI components for these filters as well ?

@akila-i
Copy link
Copy Markdown
Contributor Author

akila-i commented Apr 7, 2026

@akila-i In many obs related views we use the same set of filters right ? Like Environment, Time Range and so on. Can we consider adding reusable UI components for these filters as well ?

Ack. Will do that refactoring in a separate PR.

@akila-i akila-i merged commit 126d236 into openchoreo:main Apr 7, 2026
7 checks passed
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