Skip to content

refactor: improve cache handling for chat user operations and enhance tests - #8194

Merged
wxg0103 merged 1 commit into
v3from
pr@v3@refactor_chat_user_cache
Nov 27, 2026
Merged

wxg0103 merged 1 commit into
v3from
pr@v3@refactor_chat_user_cache

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

refactor: improve cache handling for chat user operations and enhance tests


class ResourceAuthorizationIncludeChildrenTests(SimpleTestCase):
"""GHSA-223f-r4v5-8782: include_children 授权不能信任客户端传入的 folder_ids"""

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Here is an analysis of the provided code snippet, focusing on test logic, framework usage, and potential edge cases.

1. Analysis of Cache_Version Import

Potential Issue: The test relies on a custom wrapper or specific structure for cache keys (Cache_Version.APPLICATION_THIRD_PARTY.value).

  • Check: Ensure that ChatUserSerializer.delete() and .batch_delete() use the exact same key generation logic (prefix, versioning strategy) as the test setup. If the serializer uses a different default version or namespace, the test will pass incorrectly (false negative) because it checks against the wrong key, or fail if they match accidentally but diverge in future changes.
  • Suggestion: Consider extracting the cache key generation into a helper method used by both the serializer and the test to ensure they are always synchronized.

2. Test Coverage Gaps

Missing Edge Cases:

  • Batch Delete with Invalid IDs: test_batch_delete_removes_third_party_user_cache only tests valid IDs. It does not verify behavior when ids contains non-existent users, mixed valid/invalid IDs, or empty lists. Ensure batch_delete handles these gracefully without raising unexpected exceptions or leaving stale caches for valid entries.
  • Concurrent Deletes: While hard to unit test cleanly, ensure the cache invalidation inside delete() is not race-condition prone (e.g., invalidating before DB commit vs after).
  • Multiple Users: The batch delete test only uses one user. Adding a second user would better validate loop logic inside batch_delete.

3. Optimization & Best Practices

A. Use self.addCleanup or Assert Invalidation Instead of Manual Setup

Instead of manually setting the cache in setUp, you could assert the cache was deleted. However, current approach is fine. Optimization:
Use django.test.utils.override_settings if caching behavior depends on settings, though likely unnecessary here.

B. Avoid String Concatenation F-Strings in Cache Keys (If Performance Critical)

# Current: Likely fine for tests
self.cache_key = self.get_key(f"chat_user_{self.user.username}")

Ensure self.get_key correctly handles special characters in username if ChatUser allows them. Django's standard cache key sanitization should apply, but verify if username can have colons (:), which often break default cache backends.

C. Serializer Instantiation Pattern

ChatUserSerializer.Operate(data={"id": self.user.id}).delete(with_valid=True)

This pattern assumes ChatUserSerializer has a custom .Operate and .BatchDeleteInstance interface.

  • Concern: This is not standard DRF code. Standard DRF uses serializer.save() or viewset actions. If this is a custom framework, ensure .delete(with_valid=True) actually triggers signal-based cache invalidation or manual cache deletion internally.
  • Check: Does .delete() also trigger model.delete()? Ensure no database integrity errors occur if other models reference ChatUser.

D. Assertion Clarity

self.assertIsNone(cache.get(self.cache_key, version=self.version))
  • Improvement: Use self.assertFalse(cache.get(...)) if value could be falsy (empty dict/list), but assertIsNone is stricter and better here. Keep it.

4. Recommended Code Improvements

class ChatUserDeleteTests(TestCase):
    def setUp(self):
        # 1. Verify get_key produces consistent results for serializer and test
        self.version, self.get_key = Cache_Version.APPLICATION_THIRD_PARTY.value
        self.user = ChatUser.objects.create(
            username="channel-openid",
            nick_name="Channel User",
            password="encrypted-password",
        )
        
        # Pre-populate cache
        self.cache_key = self.get_key(f"chat_user_{self.user.username}")
        cache.set(
            self.cache_key,
            {"user_id": str(self.user.id), "nick_name": self.user.nick_name},
            timeout=60, # Explicit timeout for clarity
            version=self.version,
        )

    def _assert_cache_cleared(self, user_id: int, username: str):
        """Helper to reduce duplication."""
        key = self.get_key(f"chat_user_{username}")
        cached_value = cache.get(key, version=self.version)
        self.assertIsNone(cached_value, f"Cache for user {user_id} ({username}) was not cleared.")

    def test_delete_removes_third_party_user_cache(self):
        ChatUserSerializer.Operate(data={"id": self.user.id}).delete(with_valid=True)
        self._assert_cache_cleared(self.user.id, self.user.username)

    def test_batch_delete_removes_third_party_user_cache(self):
        # Create multiple users to test batch looping
        users = [
            ChatUser.objects.create(username="batch-user-1"),
            ChatUser.objects.create(username="batch-user-2"),
        ]
        keys = []
        for u in users:
            key = self.get_key(f"chat_user_{u.username}")
            cache.set(key, {"user_id": str(u.id)}, version=self.version)
            keys.append((u, key))

        ids = [u.id for u in users]
        ChatUserSerializer.BatchDeleteInstance(data={"ids": ids}).batch_delete()

        for u, key in keys:
            self.assertIsNone(
                cache.get(key, version=self.version),
                f"Batch delete failed to clear cache for {u.username}"
            )

    def test_batch_delete_with_missing_ids_does_not_error(self):
        """Optional: Test error handling / no-op for missing IDs."""
        fake_id = 999999
        # Should not raise exception, and existing caches remain untouched
        ChatUserSerializer.BatchDeleteInstance(data={"ids": [self.user.id, fake_id]}).batch_delete()
        # Existing user cache should still be there if the serializer skips invalid IDs? 
        # OR if it processes all, check self.user cache is gone
        # Behavior depends on implementation. This test ensures robustness.

Summary of Recommendations

  1. Extract Key Generation: Ensure get_key logic matches internal serializer logic exactly.
  2. Expand Batch Test: Use multiple users in batch delete to catch loop/logic errors.
  3. Handle Missing IDs: Add a test for batch_delete with invalid/non-existent IDs.
  4. Explicit Timeouts: Add explicit timeouts to cache.set in tests to avoid environment-dependent behavior.

clear_application_third_party_chat_user_cache([username])
return True

def edit(self, instance, with_valid=True):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Overall, the patch is reasonable, but there are a few correctness/behavioral regressions and cache-consistency risks.

Main issues

  1. Empty ids list is now allowed

    • ListField defaults to allow_empty=True.
    • The original code explicitly rejected an empty list with AppApiException(1004, ...).
    • Now ids: [] passes validation and silently deletes nothing.
    • Fix with allow_empty=False or keep an explicit check.
  2. API error contract changed

    • The original empty-ID case raised AppApiException(1004, ...).
    • The new self.is_valid(raise_exception=True) raises DRF ValidationError, which may change the response body/status/code expected by clients.
    • If clients depend on code 1004, preserve that behavior with a serializer validate_ids or explicit check.
  3. Cache invalidation should run after transaction commit

    • If the request runs inside a transaction / ATOMIC_REQUESTS, clearing the cache immediately after .delete() happens before commit.
    • A concurrent request could repopulate the cache with stale data, or a rollback could leave the cache unnecessarily cleared.
    • Use transaction.on_commit(...):
    transaction.on_commit(
        lambda: clear_application_third_party_chat_user_cache(usernames)
    )
  4. Inconsistent use of self.data vs self.validated_data

    • batch_delete() was updated correctly to use validated_data.
    • delete() still uses self.data.get("id") after validation. Prefer:
    user_id = self.validated_data.get("id")
    • Also prefer if username is not None: instead of if username: if empty usernames are possible.
  5. Cache-clear failure can turn a successful delete into an API error

    • ChatUser.objects...delete() may succeed, but cache.delete_many(...) can fail and raise.
    • The user is already deleted, but the client may receive a 500.
    • Consider making cache invalidation best-effort with logging, or ensure it runs in an on_commit callback that cannot break the delete response.
  6. Hard-coded cache key prefix

    • f"chat_user_{username}" is duplicated knowledge of the cache key format.
    • If the write path ever changes the key format, invalidation silently stops working.
    • Centralize it, e.g. get_chat_user_cache_key(username), and reuse it where the cache is written and cleared.
  7. Race between username lookup and deletion

    • The code selects the username, then deletes. If a concurrent rename occurs in between, the cache key cleared may not match the current key.
    • If usernames are mutable and this matters, wrap in transaction.atomic() with select_for_update().
  8. Large batch performance

    • For very large ids lists, loading all usernames and deleting all cache keys at once may be memory/Redis-command heavy.
    • Consider chunking cache keys, e.g. batches of 500–1000.

Suggested minimal patch

def batch_delete(self):
    self.is_valid(raise_exception=True)
    user_ids = self.validated_data.get("ids")
    if not user_ids:
        raise AppApiException(1004, _("User IDs cannot be empty"))

    usernames = list(
        ChatUser.objects.filter(id__in=user_ids)
        .values_list("username", flat=True)
    )

    ChatUser.objects.filter(id__in=user_ids).delete()

    transaction.on_commit(
        lambda: clear_application_third_party_chat_user_cache(usernames)
    )
    return True

For the single delete:

if with_valid:
    self.is_valid(raise_exception=True)

user_id = self.validated_data.get("id") if with_valid else self.data.get("id")
username = (
    ChatUser.objects.filter(id=user_id)
    .values_list("username", flat=True)
    .first()
)

ChatUser.objects.filter(id=user_id).delete()

if username is not None:
    transaction.on_commit(
        lambda: clear_application_third_party_chat_user_cache([username])
    )

The main required fixes are: reject empty ids, preserve the expected exception/API contract if needed, and move cache invalidation to transaction.on_commit.

@wxg0103
wxg0103 merged commit 5e89d8c into v3 Nov 27, 2026
3 of 4 checks passed
@wxg0103
wxg0103 deleted the pr@v3@refactor_chat_user_cache branch November 27, 2026 03:39
f"{CONFIG.get_chat_path()}/{access_token}/" if access_token else f"{CONFIG.get_chat_path()}/portal"
)
response.set_cookie(
key="mk_file_auth",

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Here is the analysis of the code change:

1. Irregularities & Errors

  • Missing Closing Quote/Syntax Error (Line in context):
    The line access_token = [API_KEY]"access_token") appears to be a typo or a bad merge artifact in the context provided. It is syntactically invalid Python. It should likely be something like access_token = request.META.get(HTTP_AUTHORIZATION) or similar, depending on how you parse tokens. This is likely a critical bug if present in the actual code.

  • Trailing Slash Inconsistency:
    The main change removes the trailing slash / from the fallback path:

    • Before: f".../portal/"
    • After: f".../portal"

    This is generally an improvement, but it introduces a potential issue if the rest of the system does not normalize paths. See "Potential Issues" below.

2. Potential Issues

  • Path Concatenation Risks:
    If this cookie_path is later used in a string concatenation like path + subpath, the lack of a trailing slash on "portal" could cause issues if subpath doesn't start with /.

    • Example: "portal" + "settings" → "portalettings" (Bug)
    • Example: "portal" + "/settings" → "portal/settings" (OK)

    Conversely, if you previously relied on "portal/" + "settings" working and now use "portal" + "settings", it breaks. Ensure that all downstream consumers of this cookie value either:

    1. Always prepend a / when joining paths.
    2. Use a proper URL/path joining function (e.g., os.path.join or urllib.parse.urljoin).
  • Cookie Path Validity:
    HTTP cookie paths must be properly formatted. While both "/portal/" and "/portal" are often treated similarly by browsers (they usually redirect or match subsets), consistency is key. Most modern frameworks expect the path to not have a trailing slash unless it points to a directory file (which it doesn't). Removing the trailing slash is standard best practice for directory-like cookie paths.

3. Optimization & Best Practice Suggestions

  1. Use Standard Path Joining: Instead of manual f-string concatenation, consider using urljoin or string methods that ensure no double slashes or missing separators.
    # Better approach for clarity and safety
    from urllib.parse import urljoin
    
    chat_base = CONFIG.get_chat_path().rstrip('/')  # Ensure no trailing slash at base
    if access_token:
        cookie_path = f"{chat_base}/{access_token}"
    else:
        cookie_path = f"{chat_base}/portal"
  2. Verify Access Token Extraction: Fix the syntax error in [API_KEY]"access_token"). Ensure access_token is always a sanitized string or None. If it contains slashes or special characters, it might break the cookie path format. Consider URL-encoding or validating the token before inserting it into the path.
  3. Security Check: Ensure that access_token is validated before being used in a path. Unvalidated user input in a cookie path can sometimes lead to header injection if not handled correctly by the framework (though most modern frameworks sanitize this automatically).

Summary

The removal of the trailing slash from /portal/ → /portal is correct and recommended for cleaner URL/path semantics. However, fix the syntax error in the access_token assignment line immediately, as it will cause a runtime SyntaxError.

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