Skip to content

Refactor cache handling in session and user retrieval methods across …#1612

Merged
nevil-mathew merged 12 commits into
ELEVATE-Project:developfrom
sumanvpacewisdom:tenant_fork_phase2
Mar 30, 2026
Merged

Refactor cache handling in session and user retrieval methods across …#1612
nevil-mathew merged 12 commits into
ELEVATE-Project:developfrom
sumanvpacewisdom:tenant_fork_phase2

Conversation

@sumanvpacewisdom
Copy link
Copy Markdown
Collaborator

@sumanvpacewisdom sumanvpacewisdom commented Mar 26, 2026

…services to improve efficiency. Updated cache deletion logic in AdminService and streamlined user cache clearing in EntityHelper. Enhanced organization extension updates in OrganizationService by including tenantCode in the upsert method.

Release Notes

  • Cache key optimization: removed redundant organizationCode from single-ID cache lookups in getSessionKafka, getMentorKafka, and getMenteeKafka to improve cache efficiency.
  • Simplified cache invalidation: removed redundant post-mutation invalidations and entity-list cache operations; capture old template code once and only delete cache for the old code in NotificationTemplateHelper.
  • Broader entity-type handling: entity-type updates and deletes now iterate all model names and clear caches per model value after successful DB deletion.
  • Tenancy support: pass tenantCode into organisationExtensionQueries.upsert to ensure tenant-scoped organization extension updates.
  • AdminService cache deletion fix: delete mentee cache using tenantCode + menteeId (removed organization_code) and corrected error logging to reference mentee_id.
  • Local refactors: adjusted variable mutability and simplified mentor/mentee mapping logic in cacheHelper methods.

Lines Changed by Author

Author Added Removed
sumanvpacewisdom 37 132

sumanvpacewisdom and others added 3 commits March 23, 2026 15:35
…nant_phase2

Feature/tenant phase2 temp branch -1
…ficiency. Updated cache set and delete methods in cacheHelper for session and user data. Simplified cache invalidation logic in EntityHelper and NotificationTemplateHelper by capturing old values before updates. Removed redundant cache invalidation after entity operations to streamline processing.
…services to improve efficiency. Updated cache deletion logic in AdminService and streamlined user cache clearing in EntityHelper. Enhanced organization extension updates in OrganizationService by including tenantCode in the upsert method.
Comment thread src/services/entity-type.js Outdated
Comment thread src/services/entity-type.js Outdated
Comment thread src/services/admin.js Outdated
Comment thread src/generics/cacheHelper.js
// Step 3: Fetch missing users from DB immediately using getUsersByUserIds
const dbFetchedUsers = []
let userMentorEntries = []
if (missingUserIds.length > 0) {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The getMenteeKafka method has no equivalent call to this._sendToKafkaBackground() to getMentorKafka. What is the use of getMenteeKafka?

Copy link
Copy Markdown
Collaborator Author

@sumanvpacewisdom sumanvpacewisdom Mar 27, 2026

Choose a reason for hiding this comment

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

This needs to be done later as discussion

@sumanvpacewisdom sumanvpacewisdom changed the base branch from tenant_phase_2 to develop March 27, 2026 13:49
@sumanvpacewisdom sumanvpacewisdom changed the base branch from develop to master March 30, 2026 08:11
@sumanvpacewisdom sumanvpacewisdom changed the base branch from master to develop March 30, 2026 08:12
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 30, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Changed cache key usage to rely on tenantCode + ID (removed organizationCode) for single-ID session/mentor/mentee cache operations, updated related cache deletes and logs, iterated entity-type model invalidation across all models and deferred user-cache clearing post-delete, removed entity-list caching, and passed tenantCode into organisationExtensionQueries.upsert.

Changes

Cohort / File(s) Summary
Cache helper & admin consumer
src/generics/cacheHelper.js, src/services/admin.js
Single-ID cache calls (get/set/delete) for sessions, mentors, and mentees now use tenantCode + id only (organizationCode removed); userMentorEntries made assignable; admin unenroll cache deletion updated to tenantCode + mentee_id and log fixed.
Entity-type cache invalidation
src/services/entity-type.js
Now iterates all model_names on update/delete and calls _clearUserCachesForEntityTypeChange per model; performs user-cache clearing after successful DB deletion; changes deletion key from unified model:${modelName}:__ALL__ to model-specific key tied to the entity value.
Entity list & mutation caching removal
src/services/entity.js
Removed entity list caching and all forms cache read/write/delete calls from create/update/delete; list always queries DB and calls getAllEntitiesWithEntityTypeDetails with tenantCode passed as [tenantCode].
Notification template cache update
src/services/notification.js
Compute oldCode immediately from existing template and simplify cache invalidation to delete only the oldCode entry (removed conditional path for newCode and related branches).
Organization extension upsert change
src/services/organization.js
organisationExtensionQueries.upsert now receives tenantCode as a second argument (upsert(extensionData, tenantCode)).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • nevil-mathew

Poem

"I hopped through keys both short and neat,
Swapped orgs for tenants in cache retreat,
IDs now lead the lookup dance,
No more duplicates — a tidy prance,
Rabbit grin — caches meet 🐇"

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title is vague and incomplete, using ellipsis ('across …') without clearly conveying the specific scope or main objective of the changes. Revise the title to be more specific and complete. Examples: 'Refactor cache handling in session and user retrieval methods' or 'Simplify cache invalidation logic across services'.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/generics/cacheHelper.js (2)

1094-1094: ⚠️ Potential issue | 🟡 Minor

Missing organizationCode parameter in _sendToKafkaBackground call.

The mentor._sendToKafkaBackground method signature at line 975 expects three parameters: (userMappingData, tenantCode, organizationCode), but this call only passes two. This will cause organizationCode to be undefined in the Kafka batch message (line 1008).

🐛 Proposed fix
-			this._sendToKafkaBackground(userMappingData, tenantCode)
+			this._sendToKafkaBackground(userMappingData, tenantCode, organizationCode)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/generics/cacheHelper.js` at line 1094, The call to
this._sendToKafkaBackground(userMappingData, tenantCode) is missing the third
parameter organizationCode expected by _sendToKafkaBackground; update the call
to pass the appropriate organizationCode value from the current scope (e.g.,
organizationCode or this.organizationCode) so the method receives
(userMappingData, tenantCode, organizationCode) and the Kafka batch message will
include the correct organizationCode.

1101-1101: ⚠️ Potential issue | 🟡 Minor

Incorrect method name in error log.

The error message references getMenteeKafka but this code is inside the getMentorKafka method.

📝 Proposed fix
-			console.error(`❌ [getMenteeKafka] Error processing user IDs:`, error)
+			console.error(`❌ [getMentorKafka] Error processing user IDs:`, error)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/generics/cacheHelper.js` at line 1101, The error log in the
getMentorKafka function incorrectly references getMenteeKafka; update the
console.error call inside getMentorKafka to use the correct method name (e.g.,
change the message string from "[getMenteeKafka] Error processing user IDs:" to
"[getMentorKafka] Error processing user IDs:") and scan for any other misplaced
identifiers in getMentorKafka to ensure log consistency with the function name.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/services/entity.js`:
- Around line 398-404: The call to getAllEntitiesWithEntityTypeDetails is
passing [tenantCode] (an array) which breaks the Sequelize WHERE clause and
tenant isolation; change the call so tenantCode is passed as a scalar string
(remove the surrounding array) or simply rely on the existing filter.
Specifically, update the invocation of getAllEntitiesWithEntityTypeDetails to
pass tenantCode (not [tenantCode]) and ensure filter.tenant_code remains the
scalar tenant_code value so the function (and the query using tenant_code in
entityQueries.getAllEntitiesWithEntityTypeDetails) receives a string, not an
array.

---

Outside diff comments:
In `@src/generics/cacheHelper.js`:
- Line 1094: The call to this._sendToKafkaBackground(userMappingData,
tenantCode) is missing the third parameter organizationCode expected by
_sendToKafkaBackground; update the call to pass the appropriate organizationCode
value from the current scope (e.g., organizationCode or this.organizationCode)
so the method receives (userMappingData, tenantCode, organizationCode) and the
Kafka batch message will include the correct organizationCode.
- Line 1101: The error log in the getMentorKafka function incorrectly references
getMenteeKafka; update the console.error call inside getMentorKafka to use the
correct method name (e.g., change the message string from "[getMenteeKafka]
Error processing user IDs:" to "[getMentorKafka] Error processing user IDs:")
and scan for any other misplaced identifiers in getMentorKafka to ensure log
consistency with the function name.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 27f91ab6-bde5-4001-abdb-f204a0a62d7c

📥 Commits

Reviewing files that changed from the base of the PR and between f1e9ac5 and 9f6eafa.

📒 Files selected for processing (6)
  • src/generics/cacheHelper.js
  • src/services/admin.js
  • src/services/entity-type.js
  • src/services/entity.js
  • src/services/notification.js
  • src/services/organization.js

Comment thread src/services/entity.js
Comment thread src/services/notification.js Outdated
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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/generics/cacheHelper.js (1)

1112-1120: ⚠️ Potential issue | 🟡 Minor

Incorrect log prefix in error messages.

The error logs reference [getMenteeKafka] but this code is inside mentor.getMentorKafka. This appears to be a copy-paste error that will cause confusion during debugging.

Proposed fix
 		} catch (error) {
-			console.error(`❌ [getMenteeKafka] Error processing user IDs:`, error)
+			console.error(`❌ [getMentorKafka] Error processing user IDs:`, error)
 			// Fallback to regular cache method for all user IDs
 			const fallbackResults = []
 			for (const userId of Array.isArray(userIds) ? userIds : [userIds]) {
 				try {
 					const user = await this.get(tenantCode, userId)
 					if (user) fallbackResults.push(user)
 				} catch (fallbackError) {
-					console.error(`❌ [getMenteeKafka] Fallback failed for user ${userId}:`, fallbackError.message)
+					console.error(`❌ [getMentorKafka] Fallback failed for user ${userId}:`, fallbackError.message)
 				}
 			}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/generics/cacheHelper.js` around lines 1112 - 1120, The console error
messages inside the mentor.getMentorKafka flow use the wrong log prefix
"[getMenteeKafka]"; update those log messages to use "[getMentorKafka]" so logs
reflect the correct function context—specifically change the two console.error
calls that print the main error and the fallbackError.message within the
getMentorKafka implementation to use the correct prefix.
src/services/notification.js (1)

103-117: ⚠️ Potential issue | 🔴 Critical

Critical: isDefaultOrg is undefined and will cause a ReferenceError.

The isDefaultOrg variable is used on line 105 but is never defined in this method. Based on the AI summary, the variable definition was removed but its usage was not. This will cause a runtime crash when any notification template update is attempted.

Proposed fix - Add isDefaultOrg computation or simplify logic

Option 1: Add the missing isDefaultOrg computation:

 			const existingTemplate = existingTemplates?.[0]
 			const oldCode = existingTemplate?.code || filter.code
+
+			// Determine if this is the default organization
+			const defaults = await getDefaults()
+			const isDefaultOrg = tokenInformation.organization_code === defaults.orgCode

 			const result = await notificationTemplateQueries.updateTemplate(filter, bodyData, tenantCode)

Option 2: If default org check is no longer needed, simplify to always use single-org deletion:

 			try {
 				if (oldCode) {
-					if (isDefaultOrg) {
-						await cacheHelper.notificationTemplates.deleteNotificationsAcrossAllOrgs(tenantCode, oldCode)
-					} else {
-						await cacheHelper.notificationTemplates.delete(
-							tenantCode,
-							tokenInformation.organization_code,
-							oldCode
-						)
-					}
+					await cacheHelper.notificationTemplates.delete(
+						tenantCode,
+						tokenInformation.organization_code,
+						oldCode
+					)
 				}
 			} catch (cacheError) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/services/notification.js` around lines 103 - 117, The code uses an
undefined isDefaultOrg causing a ReferenceError; update the try block in the
notification update flow to compute or remove that check: either compute
isDefaultOrg (e.g., derive from tokenInformation or tenantCode) before the if
(oldCode) block and use it to choose between
cacheHelper.notificationTemplates.deleteNotificationsAcrossAllOrgs(tenantCode,
oldCode) and cacheHelper.notificationTemplates.delete(tenantCode,
tokenInformation.organization_code, oldCode), or remove the isDefaultOrg
conditional and always call the single-org delete path
(cacheHelper.notificationTemplates.delete(...)) if default-org semantics are no
longer required; ensure you reference tenantCode,
tokenInformation.organization_code and oldCode consistently.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@src/generics/cacheHelper.js`:
- Around line 1112-1120: The console error messages inside the
mentor.getMentorKafka flow use the wrong log prefix "[getMenteeKafka]"; update
those log messages to use "[getMentorKafka]" so logs reflect the correct
function context—specifically change the two console.error calls that print the
main error and the fallbackError.message within the getMentorKafka
implementation to use the correct prefix.

In `@src/services/notification.js`:
- Around line 103-117: The code uses an undefined isDefaultOrg causing a
ReferenceError; update the try block in the notification update flow to compute
or remove that check: either compute isDefaultOrg (e.g., derive from
tokenInformation or tenantCode) before the if (oldCode) block and use it to
choose between
cacheHelper.notificationTemplates.deleteNotificationsAcrossAllOrgs(tenantCode,
oldCode) and cacheHelper.notificationTemplates.delete(tenantCode,
tokenInformation.organization_code, oldCode), or remove the isDefaultOrg
conditional and always call the single-org delete path
(cacheHelper.notificationTemplates.delete(...)) if default-org semantics are no
longer required; ensure you reference tenantCode,
tokenInformation.organization_code and oldCode consistently.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a8d49d9a-dbf9-433c-816d-1fdc9c15357a

📥 Commits

Reviewing files that changed from the base of the PR and between 1b207b6 and 7e254b6.

📒 Files selected for processing (2)
  • src/generics/cacheHelper.js
  • src/services/notification.js

@nevil-mathew nevil-mathew merged commit aaada5a into ELEVATE-Project:develop Mar 30, 2026
1 of 2 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Apr 9, 2026
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