🔍 Code Extractor

function remove_user_document

Maturity: 46

Removes a specific document for a user by deleting the file from the filesystem and removing its metadata from the in-memory storage structure.

File:
/tf/active/vicechatdev/vice_ai/app.py
Lines:
112 - 133
Complexity:
moderate

Purpose

This function provides thread-safe document deletion functionality in a document management system. It handles cleanup of both the physical file on disk and the document metadata stored in memory. The function uses a lock to prevent race conditions when multiple threads attempt to modify the document storage simultaneously. It also performs cleanup of empty user entries to prevent memory leaks.

Source Code

def remove_user_document(user_email, document_id):
    """Remove a specific document for a user"""
    with document_lock:
        if user_email in uploaded_documents and document_id in uploaded_documents[user_email]:
            doc_info = uploaded_documents[user_email][document_id]
            
            # Clean up file
            try:
                if os.path.exists(doc_info['file_path']):
                    os.remove(doc_info['file_path'])
            except Exception as e:
                logger.warning(f"Error removing file {doc_info['file_path']}: {e}")
            
            # Remove from storage
            del uploaded_documents[user_email][document_id]
            
            # Clean up empty user entry
            if not uploaded_documents[user_email]:
                del uploaded_documents[user_email]
            
            return True
    return False

Parameters

Name Type Default Kind
user_email - - positional_or_keyword
document_id - - positional_or_keyword

Parameter Details

user_email: String identifier for the user (typically an email address). Used as the primary key to locate the user's documents in the uploaded_documents dictionary. Expected to be a valid string that exists as a key in the uploaded_documents structure.

document_id: Unique identifier for the specific document to be removed. Expected to be a string (likely a UUID) that exists as a key within the user's document collection. Used to locate the specific document metadata including its file path.

Return Value

Returns a boolean value. Returns True if the document was successfully found and removed (both file deletion and metadata removal). Returns False if the user_email or document_id was not found in the uploaded_documents structure, indicating the document does not exist or was already removed.

Dependencies

  • os
  • logging
  • threading

Required Imports

import os
import logging
from threading import Lock

Usage Example

import os
import logging
from threading import Lock

# Setup required globals
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
document_lock = Lock()
uploaded_documents = {
    'user@example.com': {
        'doc-123': {
            'file_path': '/tmp/document.pdf',
            'filename': 'document.pdf',
            'upload_time': '2024-01-01 12:00:00'
        }
    }
}

# Create a test file
with open('/tmp/document.pdf', 'w') as f:
    f.write('test content')

# Remove the document
success = remove_user_document('user@example.com', 'doc-123')
if success:
    print('Document removed successfully')
else:
    print('Document not found')

# Attempt to remove non-existent document
success = remove_user_document('user@example.com', 'doc-999')
print(f'Non-existent document removal: {success}')  # False

Best Practices

  • Always check the return value to verify whether the document was successfully removed
  • Ensure document_lock, uploaded_documents, and logger are properly initialized as global variables before calling this function
  • The function gracefully handles file deletion errors (logs warning but continues) to ensure metadata is still cleaned up even if file removal fails
  • The function automatically cleans up empty user entries to prevent memory leaks in the uploaded_documents dictionary
  • This function is thread-safe due to the document_lock, making it suitable for use in multi-threaded web applications
  • Consider implementing additional validation to verify user permissions before calling this function
  • The function does not raise exceptions for missing files, making it idempotent for file deletion operations
  • For production use, consider adding audit logging to track document deletions for compliance purposes

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function remove_uploaded_document_v1 82.9% similar

    Removes a specific uploaded document from a user's document collection in the application state, with thread-safe locking and automatic cleanup of empty user entries.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function remove_uploaded_document 82.8% similar

    Removes a specific uploaded document from the application state for a given user, with thread-safe locking and automatic cleanup of empty user entries.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function clear_user_uploaded_documents 78.4% similar

    Removes all uploaded documents associated with a specific user from the application state in a thread-safe manner.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function delete_document_file 70.8% similar

    Deletes a document file from the file system based on the provided document ID, removing the corresponding JSON file from the DOCUMENTS_DIR directory.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function delete_document_from_filecloud 65.3% similar

    Deletes a document and its associated folder from FileCloud storage, with permission checks, audit logging, and error handling.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
← Back to Browse