🔍 Code Extractor

function api_cancel_task

Maturity: 48

Flask API endpoint that cancels a background task if it belongs to the authenticated user and is currently processing.

File:
/tf/active/vicechatdev/vice_ai/app.py
Lines:
1219 - 1242
Complexity:
moderate

Purpose

This endpoint provides a RESTful API for users to cancel their own background tasks. It validates task ownership, checks task status, and marks the task as cancelled if appropriate. It includes authentication checks, authorization validation, and comprehensive error handling for various failure scenarios.

Source Code

def api_cancel_task(task_id):
    """Cancel a background task"""
    try:
        task = get_task_status(task_id)
        if not task:
            return jsonify({'error': 'Task not found'}), 404
        
        # Check if task belongs to current user
        current_user_email = session['user'].get('email', 'unknown')
        if task.get('user') != current_user_email:
            return jsonify({'error': 'Access denied'}), 403
        
        if task['status'] != 'processing':
            return jsonify({'error': 'Task is not currently processing'}), 400
        
        # Mark task as cancelled
        fail_task(task_id, "Cancelled by user")
        logger.info(f"Task {task_id} cancelled by user {current_user_email}")
        
        return jsonify({'message': 'Task cancelled successfully'})
        
    except Exception as e:
        logger.error(f"Cancel task API error: {e}")
        return jsonify({'error': 'Failed to cancel task'}), 500

Parameters

Name Type Default Kind
task_id - - positional_or_keyword

Parameter Details

task_id: String identifier for the background task to be cancelled. This is extracted from the URL path parameter. Must correspond to an existing task in the system.

Return Value

Returns a Flask JSON response tuple. On success (200): {'message': 'Task cancelled successfully'}. On error: 404 if task not found, 403 if user doesn't own the task, 400 if task is not in 'processing' status, 500 for internal errors. All error responses include an 'error' key with a descriptive message.

Dependencies

  • flask
  • logging

Required Imports

from flask import jsonify
from flask import session
import logging

Usage Example

# Assuming Flask app setup with authentication and task management functions
# Client-side usage (JavaScript fetch example):

fetch('/api/cancel-task/abc123-task-id', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  credentials: 'include'  // Include session cookies
})
.then(response => response.json())
.then(data => {
  if (data.message) {
    console.log('Task cancelled:', data.message);
  } else if (data.error) {
    console.error('Error:', data.error);
  }
})
.catch(error => console.error('Request failed:', error));

# Server-side context requirements:
# - get_task_status(task_id) should return dict with keys: 'user', 'status'
# - fail_task(task_id, reason) should mark task as failed
# - session['user'] should contain {'email': 'user@example.com'}
# - require_auth decorator should validate user authentication

Best Practices

  • Always verify task ownership before allowing cancellation to prevent unauthorized access
  • Check task status before cancellation to avoid invalid state transitions
  • Use appropriate HTTP status codes (404, 403, 400, 500) for different error scenarios
  • Log cancellation events with user information for audit trails
  • Handle exceptions gracefully and return user-friendly error messages without exposing internal details
  • Ensure the require_auth decorator is applied to protect this endpoint from unauthenticated access
  • The function assumes session['user']['email'] exists; ensure session is properly populated by authentication middleware
  • Consider implementing rate limiting to prevent abuse of the cancellation endpoint
  • The fail_task function should handle cleanup of any resources associated with the cancelled task

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_task_status_v1 79.9% similar

    Flask API endpoint that retrieves and returns the status of a background task, with user authorization checks.

    From: /tf/active/vicechatdev/vice_ai/app.py
  • function get_task_status 68.9% similar

    Flask API endpoint that retrieves the current status of a background task by its task ID from an in-memory active_tasks dictionary.

    From: /tf/active/vicechatdev/docchat/blueprint.py
  • function api_task_status 68.6% similar

    Flask API endpoint that retrieves and returns the status of asynchronous tasks (chat or indexing operations) by task ID.

    From: /tf/active/vicechatdev/docchat/app.py
  • function cancel_enhanced_workflow 64.5% similar

    Flask route handler that cancels an in-progress enhanced workflow by workflow ID, returning a JSON response indicating success or failure.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function api_index_folder 60.3% similar

    Flask API endpoint that initiates a background task to index documents in a specified folder, tracking progress and returning a task ID for status monitoring.

    From: /tf/active/vicechatdev/docchat/app.py
← Back to Browse