🔍 Code Extractor

function run_permission_check_async

Maturity: 50

Launches a background daemon thread to perform document permission checks without blocking the main application thread.

File:
/tf/active/vicechatdev/CDocs/controllers/permission_startup_check.py
Lines:
450 - 478
Complexity:
moderate

Purpose

This function is designed for application startup scenarios where document permissions need to be verified and updated across all documents in the system. By running the permission check in a separate daemon thread, it prevents blocking the main application thread during startup, allowing the application to remain responsive while permissions are being validated and corrected in the background. The function calls check_document_permissions_on_startup() in the background thread and logs the results.

Source Code

def run_permission_check_async():
    """
    Run the permission check in a background thread.
    
    This is useful for application startup to avoid blocking the main thread
    while still ensuring all document permissions are correctly set.
    
    Returns:
        Dict with status of the background check launch
    """
    def background_check():
        try:
            logger.info("Starting background permission check thread")
            result = check_document_permissions_on_startup()
            logger.info(f"Background permission check completed: {result['updated_count']} documents updated, " +
                        f"{result.get('versions_with_missing_attributes', 0)} versions with missing attributes fixed")
        except Exception as e:
            logger.error(f"Error in background permission check: {str(e)}")
    
    # Start the check in a background thread
    check_thread = threading.Thread(target=background_check, name="PermissionCheck")
    check_thread.daemon = True
    check_thread.start()
    
    logger.info("Background permission check thread started")
    return {
        'success': True,
        'message': 'Permission check started in background'
    }

Return Value

Returns a dictionary with two keys: 'success' (boolean, always True indicating the thread was successfully started) and 'message' (string, confirmation message 'Permission check started in background'). Note that this return value only indicates the thread was launched, not the actual results of the permission check, which are logged asynchronously.

Dependencies

  • logging
  • threading
  • typing
  • CDocs.models.document
  • CDocs.models.document_status
  • CDocs.controllers.share_controller
  • CDocs.controllers.filecloud_controller
  • CDocs.controllers.document_controller
  • CDocs.models.user_extensions
  • traceback

Required Imports

import logging
import threading
from typing import Dict
from CDocs.controllers.share_controller import manage_document_permissions
from CDocs.controllers.document_controller import get_documents
from CDocs.models.document import ControlledDocument, DocumentVersion

Usage Example

# At application startup
from your_module import run_permission_check_async

# Start the background permission check
result = run_permission_check_async()
print(result)  # {'success': True, 'message': 'Permission check started in background'}

# The application continues running while permissions are checked in the background
# Check logs for actual permission check results:
# INFO: Starting background permission check thread
# INFO: Background permission check completed: X documents updated, Y versions with missing attributes fixed

Best Practices

  • This function should be called during application startup, not during regular request handling
  • The daemon thread will be terminated when the main application exits, so ensure the application stays running long enough for the check to complete if needed
  • Monitor application logs to verify the background permission check completes successfully
  • Do not call this function repeatedly as it will spawn multiple background threads
  • Ensure proper database connection pooling is configured to handle the background thread's database operations
  • The function returns immediately, so the actual permission check results must be obtained from logs, not the return value
  • Consider implementing a mechanism to track completion status if you need to know when the background check finishes
  • The daemon thread setting means the thread won't prevent application shutdown, but may be interrupted mid-operation

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function check_document_permissions_on_startup_v1 73.4% similar

    Performs a system-wide startup check to verify and update document permissions for all documents in the system, ensuring permissions align with document status.

    From: /tf/active/vicechatdev/CDocs/controllers/permission_startup_check.py
  • function check_document_permissions_on_startup 68.4% similar

    Validates and fixes document permission issues during application startup, prioritizing active documents (DRAFT, IN_REVIEW, IN_APPROVAL) to ensure proper sharing permissions are configured.

    From: /tf/active/vicechatdev/CDocs/utils/sharing_validator.py
  • function check_document_permission 54.4% similar

    Validates whether a user has specific permission(s) to access or modify a document based on their roles, ownership status, and configured role permissions.

    From: /tf/active/vicechatdev/CDocs/config/permissions.py
  • function get_document_permissions 52.1% similar

    Retrieves permission information for a specific document by its unique identifier, returning structured data about who can access the document and their permission levels.

    From: /tf/active/vicechatdev/CDocs/controllers/api_handler.py
  • function validate_and_fix_document_permissions 51.8% similar

    Validates and optionally fixes document sharing permissions for controlled documents in a Neo4j database, processing documents in configurable batches with detailed progress tracking and error handling.

    From: /tf/active/vicechatdev/CDocs/utils/sharing_validator.py
← Back to Browse