Execution

Execute and Monitor Analysis Blocks

Execute individual blocks asynchronously and monitor their processing status. Track execution progress, retrieve results, and manage the execution queue.

Execute Block

POST /api/{tenantId}/{projectId}/block/{blockId}/execute

Queues a block for asynchronous execution. The block will process data according to its type and configuration (filter, calculator, alert, etc.). Returns an execution ID for tracking progress.

Parameters

Parameter Type Location Description
tenantId GUID Path The tenant identifier
projectId GUID Path The project identifier
blockId GUID Path The block identifier to execute

Request Body (Optional)

{
  "parameters": {
    "dateFrom": "2024-01-01",
    "dateTo": "2024-12-31",
    "threshold": 1000
  }
}

Response (202 Accepted)

{
  "blockId": "550e8400-e29b-41d4-a716-446655440000",
  "executionId": "770e8400-e29b-41d4-a716-446655440000",
  "status": "Queued",
  "dateQueued": "2024-01-15T10:30:00Z",
  "dateStarted": null,
  "dateEnded": null,
  "result": null,
  "errorMessage": null,
  "message": "Block execution has been queued"
}

Get Block Results

GET /api/{tenantId}/{projectId}/block/{blockId}/results

Retrieves the processed results from the block's most recent execution. Results vary by block type: filtered datasets, calculated metrics, alert notifications, etc.

Response

{
  "blockId": "550e8400-e29b-41d4-a716-446655440000",
  "results": {
    "recordsProcessed": 15000,
    "recordsFiltered": 3500,
    "executionTime": "00:00:12",
    "metrics": {
      "avgProcessTime": 125.5,
      "throughput": 1250
    }
  },
  "message": "Results retrieved successfully"
}

Get Block Output Data

GET /api/{tenantId}/{projectId}/block/{blockId}/output-data

Retrieves the transformed dataset produced by the block. This is the filtered, calculated, or enriched data that serves as input for subsequent blocks in the workflow.

Response

{
  "blockId": "550e8400-e29b-41d4-a716-446655440000",
  "dataType": "ProcessData",
  "data": [
    {
      "caseId": "CASE-001",
      "activity": "Order Received",
      "timestamp": "2024-01-15T09:00:00Z",
      "resource": "System",
      "calculatedMetric": 125.50
    },
    {
      "caseId": "CASE-002",
      "activity": "Payment Processed",
      "timestamp": "2024-01-15T09:15:00Z",
      "resource": "Finance",
      "calculatedMetric": 250.75
    }
  ],
  "recordCount": 3500,
  "message": "Output data retrieved successfully"
}

Execution Status Values

Block execution progresses through these status values:

Status Description
Queued Block is waiting in the execution queue
Running Block is currently processing data
Success Block completed execution successfully
Failed Block execution failed with errors
Cancelled Block execution was cancelled by user

JavaScript Example: Execute and Monitor Block

class BlockExecutor {
  constructor(baseUrl, tenantId, projectId, token) {
    this.baseUrl = baseUrl;
    this.tenantId = tenantId;
    this.projectId = projectId;
    this.headers = {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    };
  }

  async executeBlock(blockId, parameters = null) {
    const url = `${this.baseUrl}/api/${this.tenantId}/${this.projectId}/block/${blockId}/execute`;

    const response = await fetch(url, {
      method: 'POST',
      headers: this.headers,
      body: parameters ? JSON.stringify({ parameters }) : null
    });

    if (response.status === 202) {
      return await response.json();
    }
    throw new Error(`Execution failed: ${response.statusText}`);
  }

  async getResults(blockId) {
    const url = `${this.baseUrl}/api/${this.tenantId}/${this.projectId}/block/${blockId}/results`;

    const response = await fetch(url, {
      headers: this.headers
    });

    return await response.json();
  }

  async getOutputData(blockId) {
    const url = `${this.baseUrl}/api/${this.tenantId}/${this.projectId}/block/${blockId}/output-data`;

    const response = await fetch(url, {
      headers: this.headers
    });

    return await response.json();
  }

  async executeAndWait(blockId, parameters = null, pollInterval = 2000) {
    // Execute the block
    const execution = await this.executeBlock(blockId, parameters);
    console.log(`Block execution started: ${execution.executionId}`);

    // Poll for completion
    while (true) {
      await new Promise(resolve => setTimeout(resolve, pollInterval));

      const results = await this.getResults(blockId);

      if (results.status === 'Success') {
        console.log('Block execution completed successfully');
        return results;
      } else if (results.status === 'Failed') {
        throw new Error(`Block execution failed: ${results.errorMessage}`);
      }

      console.log(`Current status: ${results.status}`);
    }
  }
}

// Usage
const executor = new BlockExecutor(
  'https://your-mindzie-instance.com',
  'tenant-guid',
  'project-guid',
  'your-token'
);

// Execute with parameters
executor.executeAndWait('block-guid', {
  dateFrom: '2024-01-01',
  dateTo: '2024-12-31'
})
.then(results => {
  console.log('Results:', results);
})
.catch(error => {
  console.error('Execution error:', error);
});

Python Example: Async Block Execution

import requests
import time
import json

class BlockExecutor:
    def __init__(self, base_url, tenant_id, project_id, token):
        self.base_url = base_url
        self.tenant_id = tenant_id
        self.project_id = project_id
        self.headers = {
            'Authorization': f'Bearer {token}',
            'Content-Type': 'application/json'
        }

    def execute_block(self, block_id, parameters=None):
        """Queue block for execution"""
        url = f"{self.base_url}/api/{self.tenant_id}/{self.project_id}/block/{block_id}/execute"

        payload = {'parameters': parameters} if parameters else {}
        response = requests.post(url, json=payload, headers=self.headers)

        if response.status_code == 202:
            return response.json()
        else:
            raise Exception(f"Failed to execute block: {response.text}")

    def get_results(self, block_id):
        """Get block execution results"""
        url = f"{self.base_url}/api/{self.tenant_id}/{self.project_id}/block/{block_id}/results"
        response = requests.get(url, headers=self.headers)
        return response.json()

    def get_output_data(self, block_id):
        """Get block output dataset"""
        url = f"{self.base_url}/api/{self.tenant_id}/{self.project_id}/block/{block_id}/output-data"
        response = requests.get(url, headers=self.headers)
        return response.json()

    def execute_and_wait(self, block_id, parameters=None, poll_interval=2):
        """Execute block and wait for completion"""
        # Start execution
        execution = self.execute_block(block_id, parameters)
        print(f"Block execution queued: {execution['executionId']}")

        # Poll for completion
        while True:
            time.sleep(poll_interval)

            results = self.get_results(block_id)
            status = results.get('status', 'Unknown')

            if status == 'Success':
                print("Block execution completed successfully")
                return results
            elif status == 'Failed':
                error_msg = results.get('errorMessage', 'Unknown error')
                raise Exception(f"Block execution failed: {error_msg}")

            print(f"Current status: {status}")

# Example usage
executor = BlockExecutor(
    'https://your-mindzie-instance.com',
    'tenant-guid',
    'project-guid',
    'your-auth-token'
)

# Execute a filter block with date parameters
try:
    results = executor.execute_and_wait(
        'block-guid',
        parameters={
            'dateFrom': '2024-01-01',
            'dateTo': '2024-12-31',
            'threshold': 1000
        }
    )

    # Get the output data
    output_data = executor.get_output_data('block-guid')
    print(f"Processed {output_data['recordCount']} records")

except Exception as e:
    print(f"Error: {e}")
An error has occurred. This application may no longer respond until reloaded. Reload ??