ブロック実行

分析ブロックの実行

個々のブロックを非同期で実行し、その処理状況を監視します。ブロックはタイプと設定に従ってデータを処理します。

ブロックの実行

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

非同期実行のためにブロックをキューに登録します。ブロックはタイプと設定(フィルター、計算機、アラートなど)に従ってデータを処理します。進行状況を追跡するための実行IDを返します。

パスパラメーター

パラメーター タイプ 必須 説明
tenantId GUID はい テナント識別子
projectId GUID はい プロジェクト識別子
blockId GUID はい 実行するブロックの識別子

リクエストボディ(任意)

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

レスポンス(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"
}

レスポンスフィールド

フィールド タイプ 説明
blockId GUID キューに登録されたブロック
executionId GUID この実行の一意の識別子
status string 現在の実行ステータス
dateQueued datetime 実行がキューに登録された日時
dateStarted datetime 実行開始日時(開始していない場合はnull)
dateEnded datetime 実行完了日時(完了していない場合はnull)
result object 実行結果データ(完了するまでnull)
errorMessage string 実行失敗時のエラー詳細
message string 人間が読みやすいステータスメッセージ

エラーレスポンス

Not Found (404):

{
  "Error": "Block not found",
  "BlockId": "550e8400-e29b-41d4-a716-446655440000"
}

Unauthorized (401):

{error message describing authorization failure}

実行ステータスの値

ブロック実行は以下のステータス値を経て進行します:

ステータス 説明
Queued ブロックが実行キューで待機中
Running ブロックが現在データを処理中
Success ブロックの実行が正常に完了
Failed ブロックの実行がエラーで失敗
Cancelled ブロックの実行がキャンセルされた

実装例

cURL

# パラメータなしでブロックを実行
curl -X POST "https://your-mindzie-instance.com/api/12345678-1234-1234-1234-123456789012/87654321-4321-4321-4321-210987654321/block/550e8400-e29b-41d4-a716-446655440000/execute" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json"

# パラメータを指定してブロックを実行
curl -X POST "https://your-mindzie-instance.com/api/12345678-1234-1234-1234-123456789012/87654321-4321-4321-4321-210987654321/block/550e8400-e29b-41d4-a716-446655440000/execute" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"parameters": {"dateFrom": "2024-01-01", "dateTo": "2024-12-31"}}'

JavaScript/Node.js

const TENANT_ID = '12345678-1234-1234-1234-123456789012';
const PROJECT_ID = '87654321-4321-4321-4321-210987654321';
const BASE_URL = 'https://your-mindzie-instance.com';

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

  async executeBlock(blockId, parameters = null) {
    const url = `${BASE_URL}/api/${TENANT_ID}/${PROJECT_ID}/block/${blockId}/execute`;

    const body = parameters ? JSON.stringify({ parameters }) : null;

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

    if (response.status === 202) {
      return await response.json();
    }

    throw new Error(`Execution failed: ${response.statusText}`);
  }
}

// 使用例
const executor = new BlockExecutor('your-auth-token');

// パラメータなしで実行
const result = await executor.executeBlock('block-guid');
console.log(`実行キューに登録されました: ${result.executionId}`);

// パラメータを渡して実行
const resultWithParams = await executor.executeBlock('block-guid', {
  dateFrom: '2024-01-01',
  dateTo: '2024-12-31'
});

Python

import requests

TENANT_ID = '12345678-1234-1234-1234-123456789012'
PROJECT_ID = '87654321-4321-4321-4321-210987654321'
BASE_URL = 'https://your-mindzie-instance.com'

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

    def execute_block(self, block_id, parameters=None):
        """ブロックを実行キューに登録する。"""
        url = f'{BASE_URL}/api/{TENANT_ID}/{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'ブロックの実行に失敗しました: {response.text}')

# 使用例
executor = BlockExecutor('your-auth-token')

# パラメータなしで実行
result = executor.execute_block('block-guid')
print(f"実行キューに登録されました: {result['executionId']}")

# パラメータを指定して実行
result = executor.execute_block('block-guid', {
    'dateFrom': '2024-01-01',
    'dateTo': '2024-12-31',
    'threshold': 1000
})
print(f"ステータス: {result['status']}")

C#

using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

public class ExecuteBlockReturn
{
    public Guid BlockId { get; set; }
    public Guid ExecutionId { get; set; }
    public string Status { get; set; }
    public DateTime DateQueued { get; set; }
    public DateTime? DateStarted { get; set; }
    public DateTime? DateEnded { get; set; }
    public object Result { get; set; }
    public string ErrorMessage { get; set; }
    public string Message { get; set; }
}

public class BlockExecutorClient
{
    private readonly HttpClient _httpClient;
    private readonly string _baseUrl;
    private readonly Guid _tenantId;
    private readonly Guid _projectId;

    public BlockExecutorClient(string baseUrl, Guid tenantId, Guid projectId, string accessToken)
    {
        _baseUrl = baseUrl;
        _tenantId = tenantId;
        _projectId = projectId;
        _httpClient = new HttpClient();
        _httpClient.DefaultRequestHeaders.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
    }

    public async Task<ExecuteBlockReturn> ExecuteBlockAsync(Guid blockId, object parameters = null)
    {
        var url = $"{_baseUrl}/api/{_tenantId}/{_projectId}/block/{blockId}/execute";

        var payload = parameters != null ? new { parameters } : new { };
        var content = new StringContent(
            JsonSerializer.Serialize(payload),
            Encoding.UTF8,
            "application/json");

        var response = await _httpClient.PostAsync(url, content);

        if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
        {
            var json = await response.Content.ReadAsStringAsync();
            return JsonSerializer.Deserialize<ExecuteBlockReturn>(json,
                new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
        }

        throw new Exception($"ブロックの実行に失敗しました: {response.StatusCode}");
    }
}

// 使用例
var executor = new BlockExecutorClient(
    "https://your-mindzie-instance.com",
    Guid.Parse("12345678-1234-1234-1234-123456789012"),
    Guid.Parse("87654321-4321-4321-4321-210987654321"),
    "your-access-token");

// ブロックを実行
var result = await executor.ExecuteBlockAsync(
    Guid.Parse("block-guid"),
    new { dateFrom = "2024-01-01", dateTo = "2024-12-31" });

Console.WriteLine($"実行キューに登録されました: {result.ExecutionId}");

ベストプラクティス

  • ブロックのステータスを確認: 実行前にブロックが無効化されていないかを確認する
  • パラメータを適切に使う: 実行時パラメータを渡してブロック設定を変更せずにカスタマイズする
  • 非同期処理を考慮: ブロック実行は非同期のため、完了確認には結果エンドポイントを使用する
  • 実行状況を監視: 長時間実行されるブロックは結果エンドポイントを定期的にポーリングして進行を追跡する