非同期操作

長時間実行される操作

コールバック、Webhook、およびリアルタイムのステータス更新を使用して非同期操作を処理します。

非同期操作の開始

POST /api/{tenantId}/{projectId}/async/operation

長時間実行される非同期操作を開始し、追跡用の操作IDを返します。コールバックURLおよびWebhook通知をサポートします。

パラメーター

パラメーター タイプ 場所 説明
tenantId GUID パス テナント識別子
projectId GUID パス プロジェクト識別子

リクエストボディ

{
  "operationType": "ProcessMiningAnalysis",
  "operationName": "包括的なカスタマージャーニー分析",
  "operationDescription": "高度なMLアルゴリズムを用いた顧客インタラクションパターンの詳細分析",
  "priority": "High",
  "parameters": {
    "datasetId": "880e8400-e29b-41d4-a716-446655440000",
    "analysisType": "comprehensive",
    "timeWindow": {
      "startDate": "2024-01-01",
      "endDate": "2024-01-31"
    },
    "algorithmSettings": {
      "useAdvancedML": true,
      "enableAnomalyDetection": true,
      "performanceOptimization": "high_accuracy"
    },
    "outputOptions": {
      "generateReports": true,
      "createVisualizations": true,
      "exportFormats": ["PDF", "CSV", "JSON"]
    }
  },
  "callbacks": {
    "onProgress": "https://your-app.com/webhooks/progress",
    "onCompletion": "https://your-app.com/webhooks/completion",
    "onError": "https://your-app.com/webhooks/error"
  },
  "notifications": {
    "email": ["analyst@company.com", "manager@company.com"],
    "slack": {
      "channel": "#process-mining",
      "mentionUsers": ["@analyst", "@data-team"]
    }
  },
  "timeout": 7200,
  "retryPolicy": {
    "maxRetries": 3,
    "retryDelay": 300,
    "backoffMultiplier": 2.0
  }
}

レスポンス

{
  "operationId": "op-ff0e8400-e29b-41d4-a716-446655440000",
  "operationType": "ProcessMiningAnalysis",
  "operationName": "包括的なカスタマージャーニー分析",
  "status": "Initiated",
  "estimatedDuration": "45-60 minutes",
  "estimatedCompletion": "2024-01-20T12:15:00Z",
  "trackingUrl": "/api/{tenantId}/{projectId}/async/operation/op-ff0e8400-e29b-41d4-a716-446655440000",
  "webhooksRegistered": 3,
  "priority": "High",
  "dateCreated": "2024-01-20T11:15:00Z",
  "timeoutAt": "2024-01-20T13:15:00Z",
  "resourcesAllocated": {
    "cpuUnits": 4,
    "memoryGB": 8,
    "estimatedCost": "$2.45"
  }
}

操作ステータスの取得

GET /api/{tenantId}/{projectId}/async/operation/{operationId}

非同期操作の現在のステータスと進行状況を取得します。詳細な実行情報と推定完了時間を含みます。

パラメーター

パラメーター タイプ 場所 説明
operationId string パス 操作識別子

レスポンス

{
  "operationId": "op-ff0e8400-e29b-41d4-a716-446655440000",
  "operationType": "ProcessMiningAnalysis",
  "operationName": "包括的なカスタマージャーニー分析",
  "status": "Running",
  "progress": {
    "percentage": 67,
    "currentPhase": "Machine Learning Analysis",
    "phasesCompleted": 2,
    "totalPhases": 3,
    "startTime": "2024-01-20T11:18:00Z",
    "elapsedTime": "23 minutes 15 seconds",
    "estimatedRemaining": "15-20 minutes",
    "estimatedCompletion": "2024-01-20T12:05:00Z"
  },
  "execution": {
    "executionId": "exec-aa1e8400-e29b-41d4-a716-446655440000",
    "workerNode": "async-worker-03",
    "resourceUsage": {
      "cpuUsage": 78,
      "memoryUsage": "6.2 GB",
      "diskUsage": "1.3 GB",
      "networkIO": "45 MB"
    },
    "processedRecords": 125430,
    "totalRecords": 187250,
    "processingRate": "1890 records/minute"
  },
  "phases": [
    {
      "phaseName": "データの読み込みと検証",
      "status": "Completed",
      "startTime": "2024-01-20T11:18:00Z",
      "endTime": "2024-01-20T11:25:00Z",
      "duration": "7 minutes",
      "recordsProcessed": 187250,
      "validationResults": {
        "validRecords": 187248,
        "errorRecords": 2,
        "dataQualityScore": 99.9
      }
    },
    {
      "phaseName": "プロセス発見",
      "status": "Completed",
      "startTime": "2024-01-20T11:25:00Z",
      "endTime": "2024-01-20T11:38:00Z",
      "duration": "13 minutes",
      "results": {
        "activitiesDiscovered": 52,
        "processVariants": 347,
        "uniquePaths": 289
      }
    },
    {
      "phaseName": "機械学習分析",
      "status": "Running",
      "startTime": "2024-01-20T11:38:00Z",
      "progress": 72,
      "currentActivity": "異常検知モデルのトレーニング",
      "modelsTraining": 3,
      "modelsCompleted": 2
    },
    {
      "phaseName": "レポート生成",
      "status": "Pending",
      "estimatedStartTime": "2024-01-20T11:55:00Z",
      "estimatedDuration": "8-10 minutes"
    }
  ],
  "callbacks": {
    "progressCallbacksSent": 15,
    "lastProgressCallback": "2024-01-20T11:40:00Z",
    "callbacksSuccessful": 15,
    "callbacksFailed": 0
  },
  "dateCreated": "2024-01-20T11:15:00Z",
  "timeoutAt": "2024-01-20T13:15:00Z",
  "priority": "High"
}

非同期操作の一覧取得

GET /api/{tenantId}/{projectId}/async/operations

フィルタリングおよびページネーションオプション付きで非同期操作の一覧を取得します。複数の長時間実行操作の監視に便利です。

クエリパラメーター

パラメーター タイプ 説明
status string ステータスによるフィルタ:Initiated, Running, Completed, Failed, Cancelled, Timeout
operationType string 操作タイプによるフィルタ:ProcessMiningAnalysis, DataEnrichment, ReportGeneration
priority string 優先度によるフィルタ:Low, Normal, High, Critical
dateFrom datetime この日付以降の操作をフィルタ
dateTo datetime この日付までの操作をフィルタ
includeDetails boolean 詳細な実行情報を含める(デフォルト:false)
page integer ページ番号(デフォルト:1)
pageSize integer 1ページあたりのアイテム数(デフォルト:20、最大:100)

レスポンス

{
  "operations": [
    {
      "operationId": "op-ff0e8400-e29b-41d4-a716-446655440000",
      "operationType": "ProcessMiningAnalysis",
      "operationName": "包括的なカスタマージャーニー分析",
      "status": "Running",
      "progress": 67,
      "priority": "High",
      "startTime": "2024-01-20T11:18:00Z",
      "estimatedCompletion": "2024-01-20T12:05:00Z",
      "currentPhase": "Machine Learning Analysis",
      "resourceUsage": {
        "cpuUsage": 78,
        "memoryUsage": "6.2 GB"
      }
    },
    {
      "operationId": "op-gg1e8400-e29b-41d4-a716-446655440000",
      "operationType": "DataEnrichment",
      "operationName": "Sales Data Processing",
      "status": "Completed",
      "progress": 100,
      "priority": "Normal",
      "startTime": "2024-01-20T10:45:00Z",
      "endTime": "2024-01-20T11:10:00Z",
      "duration": "25 minutes",
      "recordsProcessed": 89420
    }
  ],
  "summary": {
    "totalOperations": 47,
    "running": 3,
    "completed": 41,
    "failed": 2,
    "cancelled": 1
  },
  "page": 1,
  "pageSize": 20,
  "hasNextPage": true
}

非同期操作のキャンセル

DELETE /api/{tenantId}/{projectId}/async/operation/{operationId}

実行中または保留中の非同期操作をキャンセルします。操作はグレースフルに停止され、完了した作業は保持されます。

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

{
  "reason": "変更された要件によりユーザーがキャンセルを要求",
  "preservePartialResults": true,
  "forceTermination": false,
  "notifyCallbacks": true
}

レスポンス

{
  "operationId": "op-ff0e8400-e29b-41d4-a716-446655440000",
  "status": "Cancelled",
  "cancellationTime": "2024-01-20T11:42:00Z",
  "reason": "変更された要件によりユーザーがキャンセルを要求",
  "progressAtCancellation": 67,
  "phaseAtCancellation": "Machine Learning Analysis",
  "partialResults": {
    "available": true,
    "completedPhases": 2,
    "downloadUrls": [
      "https://api.mindzie.com/downloads/partial-results-ff0e8400.zip"
    ]
  },
  "resourcesReleased": {
    "cpuUnits": 4,
    "memoryGB": 8,
    "costSaved": "$1.20"
  },
  "cancelledBy": "user123"
}

操作結果の取得

GET /api/{tenantId}/{projectId}/async/operation/{operationId}/results

完了した非同期操作の完全な結果を取得します。生成されたすべての出力、レポート、およびダウンロード可能な成果物を含みます。

クエリパラメーター

パラメーター タイプ 説明
format string レスポンスフォーマット:summary、detailed、download(デフォルト:summary)
includeArtifacts boolean ダウンロード可能な成果物をレスポンスに含める(デフォルト:true)
phase string 特定のフェーズ結果のみ取得

レスポンス

{
  "operationId": "op-ff0e8400-e29b-41d4-a716-446655440000",
  "operationType": "ProcessMiningAnalysis",
  "operationName": "包括的なカスタマージャーニー分析",
  "status": "Completed",
  "completionTime": "2024-01-20T12:03:00Z",
  "totalDuration": "45 minutes",
  "success": true,
  "summary": {
    "recordsAnalyzed": 187248,
    "processVariants": 347,
    "anomaliesDetected": 23,
    "modelsGenerated": 3,
    "reportsCreated": 5,
    "dataQualityScore": 94.7,
    "overallConfidenceScore": 91.2
  },
  "phaseResults": [
    {
      "phaseName": "データの読み込みと検証",
      "status": "Completed",
      "results": {
        "recordsLoaded": 187250,
        "validRecords": 187248,
        "dataQualityScore": 99.9,
        "validationErrors": [
          {
            "type": "Missing Timestamp",
            "count": 2,
            "resolved": true
          }
        ]
      }
    },
    {
      "phaseName": "プロセス発見",
      "status": "Completed",
      "results": {
        "processModel": {
          "activities": 52,
          "transitions": 178,
          "variants": 347,
          "complexity": "Medium-High"
        },
        "performanceMetrics": {
          "averageCycleTime": "4.2 hours",
          "medianCycleTime": "3.1 hours",
          "bottleneckActivities": ["Review Application", "Manager Approval"],
          "efficiency": 78.3
        }
      }
    },
    {
      "phaseName": "機械学習分析",
      "status": "Completed",
      "results": {
        "anomalies": {
          "detected": 23,
          "highSeverity": 5,
          "mediumSeverity": 12,
          "lowSeverity": 6,
          "falsePositiveRate": 0.03
        },
        "predictions": {
          "cycleTimePrediction": {
            "accuracy": 0.89,
            "meanAbsoluteError": "0.3 hours"
          },
          "pathPrediction": {
            "accuracy": 0.92,
            "confidence": 0.87
          }
        },
        "patterns": {
          "frequentPatterns": 15,
          "rarePatterns": 8,
          "criticalPaths": 3
        }
      }
    }
  ],
  "artifacts": [
    {
      "name": "Process Mining Analysis Report",
      "type": "Report",
      "format": "PDF",
      "size": "3.2 MB",
      "downloadUrl": "https://api.mindzie.com/downloads/report-ff0e8400.pdf",
      "description": "洞察と推奨事項を含む包括的な分析レポート"
    },
    {
      "name": "Process Model Visualization",
      "type": "Visualization",
      "format": "SVG",
      "size": "890 KB",
      "downloadUrl": "https://api.mindzie.com/downloads/process-map-ff0e8400.svg",
      "description": "インタラクティブなプロセスフローダイアグラム"
    },
    {
      "name": "Anomaly Detection Results",
      "type": "Dataset",
      "format": "CSV",
      "size": "1.8 MB",
      "downloadUrl": "https://api.mindzie.com/downloads/anomalies-ff0e8400.csv",
      "description": "厳密な異常分析と重大度スコア"
    },
    {
      "name": "Predictive Models",
      "type": "Model",
      "format": "PKL",
      "size": "45.7 MB",
      "downloadUrl": "https://api.mindzie.com/downloads/models-ff0e8400.zip",
      "description": "サイクルタイムおよびパス予測用のトレーニング済みMLモデル"
    }
  ],
  "performance": {
    "totalExecutionTime": "45 minutes",
    "resourceUtilization": {
      "averageCpuUsage": 72,
      "peakMemoryUsage": "7.8 GB",
      "totalCpuHours": 3.0,
      "totalCost": "$2.31"
    },
    "throughput": "4161 records/minute",
    "efficiency": 87.2
  },
  "recommendations": [
    {
      "category": "プロセス最適化",
      "priority": "High",
      "recommendation": "'Manager Approval' アクティビティの待機時間削減に注力すること",
      "expectedImprovement": "全体のサイクルタイムを25%短縮"
    },
    {
      "category": "データ品質",
      "priority": "Medium",
      "recommendation": "自動タイムスタンプ検証の実装",
      "expectedImprovement": "データ品質スコアを99.5%に改善"
    }
  ]
}

Webhookの登録

POST /api/{tenantId}/{projectId}/async/webhooks

非同期操作のリアルタイム通知を受け取るWebhookエンドポイントを登録します。複数のイベントタイプとカスタムフィルターをサポートします。

リクエストボディ

{
  "webhookUrl": "https://your-app.com/webhooks/async-operations",
  "webhookName": "Main Operations Webhook",
  "events": [
    "operation.started",
    "operation.progress",
    "operation.phase.completed",
    "operation.completed",
    "operation.failed",
    "operation.cancelled"
  ],
  "filters": {
    "operationTypes": ["ProcessMiningAnalysis", "DataEnrichment"],
    "priorities": ["High", "Critical"],
    "minProgressIncrement": 10
  },
  "authentication": {
    "type": "hmac-sha256",
    "secret": "your-webhook-secret-key"
  },
  "retryPolicy": {
    "maxRetries": 5,
    "retryDelay": 60,
    "backoffMultiplier": 2.0,
    "maxDelay": 3600
  },
  "headers": {
    "X-Source": "mindzie-api",
    "X-Environment": "production"
  }
}

レスポンス

{
  "webhookId": "wh-123e8400-e29b-41d4-a716-446655440000",
  "webhookUrl": "https://your-app.com/webhooks/async-operations",
  "webhookName": "Main Operations Webhook",
  "status": "Active",
  "eventsSubscribed": [
    "operation.started",
    "operation.progress",
    "operation.phase.completed",
    "operation.completed",
    "operation.failed",
    "operation.cancelled"
  ],
  "filters": {
    "operationTypes": ["ProcessMiningAnalysis", "DataEnrichment"],
    "priorities": ["High", "Critical"],
    "minProgressIncrement": 10
  },
  "createdAt": "2024-01-20T11:45:00Z",
  "lastDelivery": null,
  "deliveryStats": {
    "totalDeliveries": 0,
    "successfulDeliveries": 0,
    "failedDeliveries": 0,
    "averageResponseTime": null
  }
}

失敗した操作のリトライ

POST /api/{tenantId}/{projectId}/async/operation/{operationId}/retry

失敗した非同期操作をリトライします。パラメーターの変更が可能で、失敗したポイントからの再開または完全な再開始ができます。

リクエストボディ

{
  "retryMode": "resume",
  "retryReason": "インフラ問題解決、リソース増強でリトライ中",
  "modifyParameters": true,
  "updatedParameters": {
    "algorithmSettings": {
      "useAdvancedML": true,
      "enableAnomalyDetection": true,
      "performanceOptimization": "high_throughput"
    },
    "resourceAllocation": {
      "cpuUnits": 6,
      "memoryGB": 12,
      "priority": "Critical"
    }
  },
  "retryPolicy": {
    "maxRetries": 2,
    "retryDelay": 180,
    "backoffMultiplier": 1.5
  },
  "newTimeout": 10800,
  "preserveOriginalResults": true
}

レスポンス

{
  "originalOperationId": "op-ff0e8400-e29b-41d4-a716-446655440000",
  "newOperationId": "op-retry-ff0e8400-e29b-41d4-a716-446655440000",
  "retryMode": "resume",
  "retryNumber": 1,
  "resumeFromPhase": "Machine Learning Analysis",
  "status": "Initiated",
  "estimatedDuration": "20-25 minutes",
  "estimatedCompletion": "2024-01-20T12:30:00Z",
  "preservedResults": {
    "phasesPreserved": 2,
    "recordsProcessed": 187248,
    "progressSaved": 45
  },
  "resourcesAllocated": {
    "cpuUnits": 6,
    "memoryGB": 12,
    "estimatedCost": "$3.20"
  },
  "retryAttemptDate": "2024-01-20T12:05:00Z"
}

バッチ操作の送信

POST /api/{tenantId}/{projectId}/async/batch

依存関係と調整を持つ複数の非同期操作をバッチとして送信します。複雑なワークフローでの複数操作の連携に便利です。

リクエストボディ

{
  "batchName": "月次プロセスマイニングパイプライン",
  "batchDescription": "複数のデータセットを使った月次の完全分析ワークフロー",
  "operations": [
    {
      "operationName": "データ準備",
      "operationType": "DataEnrichment",
      "priority": "High",
      "operationKey": "data-prep",
      "parameters": {
        "datasetId": "dataset-1",
        "cleaningRules": ["remove_duplicates", "fix_timestamps"],
        "outputFormat": "processed_csv"
      }
    },
    {
      "operationName": "プロセス発見",
      "operationType": "ProcessMiningAnalysis",
      "priority": "High",
      "operationKey": "discovery",
      "dependencies": ["data-prep"],
      "parameters": {
        "algorithm": "alpha_miner_enhanced",
        "enableVariantAnalysis": true
      }
    },
    {
      "operationName": "パフォーマンス分析",
      "operationType": "ProcessMiningAnalysis",
      "priority": "Normal",
      "operationKey": "performance",
      "dependencies": ["discovery"],
      "parameters": {
        "enableBottleneckDetection": true,
        "generateOptimizationRecommendations": true
      }
    }
  ],
  "batchCallbacks": {
    "onBatchStart": "https://your-app.com/webhooks/batch-start",
    "onOperationComplete": "https://your-app.com/webhooks/operation-complete",
    "onBatchComplete": "https://your-app.com/webhooks/batch-complete"
  },
  "failurePolicy": {
    "stopOnFirstFailure": false,
    "continueIndependentOperations": true,
    "retryFailedOperations": true
  }
}

レスポンス

{
  "batchId": "batch-567e8400-e29b-41d4-a716-446655440000",
  "batchName": "月次プロセスマイニングパイプライン",
  "status": "Initiated",
  "operations": [
    {
      "operationKey": "data-prep",
      "operationId": "op-prep-890e8400-e29b-41d4-a716-446655440000",
      "status": "Running",
      "dependencies": [],
      "estimatedDuration": "15 minutes"
    },
    {
      "operationKey": "discovery",
      "operationId": "op-disc-901e8400-e29b-41d4-a716-446655440000",
      "status": "Pending",
      "dependencies": ["data-prep"],
      "estimatedStartTime": "2024-01-20T12:20:00Z"
    },
    {
      "operationKey": "performance",
      "operationId": "op-perf-012e8400-e29b-41d4-a716-446655440000",
      "status": "Pending",
      "dependencies": ["discovery"],
      "estimatedStartTime": "2024-01-20T12:45:00Z"
    }
  ],
  "totalOperations": 3,
  "estimatedBatchDuration": "75-90 minutes",
  "estimatedBatchCompletion": "2024-01-20T13:45:00Z",
  "batchStartTime": "2024-01-20T12:05:00Z",
  "trackingUrl": "/api/{tenantId}/{projectId}/async/batch/batch-567e8400-e29b-41d4-a716-446655440000"
}

例:非同期操作の完全なワークフロー

この例は、非同期操作の完全なライフサイクルを示しています:

// 1. リアルタイム通知用のWebhook登録
const registerWebhook = async () => {
  const response = await fetch('/api/{tenantId}/{projectId}/async/webhooks', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      webhookUrl: 'https://your-app.com/webhooks/async-operations',
      webhookName: 'Process Mining Webhook',
      events: [
        'operation.started',
        'operation.progress',
        'operation.completed',
        'operation.failed'
      ],
      filters: {
        operationTypes: ['ProcessMiningAnalysis'],
        priorities: ['High', 'Critical'],
        minProgressIncrement: 15
      },
      authentication: {
        type: 'hmac-sha256',
        secret: 'your-secret-key'
      }
    })
  });

  return await response.json();
};

// 2. 複雑な非同期操作の開始
const startAsyncAnalysis = async () => {
  const response = await fetch('/api/{tenantId}/{projectId}/async/operation', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      operationType: 'ProcessMiningAnalysis',
      operationName: '高度なカスタマージャーニー分析',
      operationDescription: '異常検知を含む深層ML分析',
      priority: 'High',
      parameters: {
        datasetId: '880e8400-e29b-41d4-a716-446655440000',
        analysisType: 'comprehensive',
        timeWindow: {
          startDate: '2024-01-01',
          endDate: '2024-01-31'
        },
        algorithmSettings: {
          useAdvancedML: true,
          enableAnomalyDetection: true,
          performanceOptimization: 'high_accuracy'
        },
        outputOptions: {
          generateReports: true,
          createVisualizations: true,
          exportFormats: ['PDF', 'CSV', 'JSON']
        }
      },
      callbacks: {
        onProgress: 'https://your-app.com/webhooks/progress',
        onCompletion: 'https://your-app.com/webhooks/completion',
        onError: 'https://your-app.com/webhooks/error'
      },
      notifications: {
        email: ['analyst@company.com'],
        slack: {
          channel: '#process-mining',
          mentionUsers: ['@analyst']
        }
      },
      timeout: 7200
    })
  });

  return await response.json();
};

// 3. 操作の進捗監視
const monitorOperation = async (operationId) => {
  const checkStatus = async () => {
    const response = await fetch(`/api/{tenantId}/{projectId}/async/operation/${operationId}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });

    const operation = await response.json();
    console.log(`操作 ${operationId}: ${operation.status} (${operation.progress.percentage}%)`);
    console.log(`現在のフェーズ: ${operation.progress.currentPhase}`);
    console.log(`推定完了時間: ${operation.progress.estimatedCompletion}`);

    if (operation.status === 'Running') {
      setTimeout(() => checkStatus(), 60000); // 1分毎にチェック
    } else if (operation.status === 'Completed') {
      console.log('操作が正常に完了しました!');
      await getOperationResults(operationId);
    } else if (operation.status === 'Failed') {
      console.log('操作が失敗しました。リトライを試みます...');
      await retryOperation(operationId);
    }
  };

  await checkStatus();
};

// 4. 操作結果の取得
const getOperationResults = async (operationId) => {
  const response = await fetch(`/api/{tenantId}/{projectId}/async/operation/${operationId}/results?format=detailed&includeArtifacts=true`, {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });

  const results = await response.json();
  console.log('操作結果:', results.summary);
  console.log('生成された成果物:');

  results.artifacts.forEach(artifact => {
    console.log(`- ${artifact.name} (${artifact.format}): ${artifact.downloadUrl}`);
  });

  return results;
};

// 5. 失敗した操作のリトライ
const retryOperation = async (operationId) => {
  const response = await fetch(`/api/{tenantId}/{projectId}/async/operation/${operationId}/retry`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      retryMode: 'resume',
      retryReason: '自動リトライでリソース増強',
      modifyParameters: true,
      updatedParameters: {
        resourceAllocation: {
          cpuUnits: 6,
          memoryGB: 12,
          priority: 'Critical'
        }
      },
      newTimeout: 10800
    })
  });

  const retryResult = await response.json();
  console.log(`リトライ操作が開始されました: ${retryResult.newOperationId}`);

  // リトライ操作の監視
  await monitorOperation(retryResult.newOperationId);

  return retryResult;
};

// 6. バッチ操作の送信
const submitBatchOperations = async () => {
  const response = await fetch('/api/{tenantId}/{projectId}/async/batch', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      batchName: '完全なプロセスマイニングパイプライン',
      batchDescription: 'データ準備と報告を含むエンドツーエンド分析',
      operations: [
        {
          operationName: 'データクリーニング',
          operationType: 'DataEnrichment',
          priority: 'High',
          operationKey: 'clean',
          parameters: {
            datasetId: 'raw-dataset-123',
            cleaningRules: ['remove_duplicates', 'fix_timestamps', 'validate_activities']
          }
        },
        {
          operationName: 'プロセス分析',
          operationType: 'ProcessMiningAnalysis',
          priority: 'High',
          operationKey: 'analyze',
          dependencies: ['clean'],
          parameters: {
            analysisType: 'comprehensive',
            enableML: true,
            generateInsights: true
          }
        },
        {
          operationName: 'レポート生成',
          operationType: 'ReportGeneration',
          priority: 'Normal',
          operationKey: 'report',
          dependencies: ['analyze'],
          parameters: {
            reportType: 'executive_summary',
            includeVisualizations: true,
            exportFormats: ['PDF', 'PowerPoint']
          }
        }
      ],
      failurePolicy: {
        stopOnFirstFailure: false,
        continueIndependentOperations: true,
        retryFailedOperations: true
      }
    })
  });

  return await response.json();
};

// 完全な非同期ワークフローの実行
const runAsyncWorkflow = async () => {
  try {
    console.log('非同期操作ワークフローを開始します...');

    // Webhook登録
    const webhook = await registerWebhook();
    console.log(`Webhook登録完了: ${webhook.webhookId}`);

    // 操作開始
    const operation = await startAsyncAnalysis();
    console.log(`操作開始: ${operation.operationId}`);
    console.log(`推定完了時間: ${operation.estimatedCompletion}`);

    // 進捗監視
    await monitorOperation(operation.operationId);

  } catch (error) {
    console.error('非同期ワークフローでエラーが発生しました:', error);
  }
};

// ワークフロー開始
runAsyncWorkflow();

Pythonの例

import requests
import time
import json
import hmac
import hashlib
from datetime import datetime, timedelta

class AsyncOperationManager:
    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 start_operation(self, operation_type, name, parameters, priority='Normal', timeout=3600):
        """非同期操作を開始する"""
        url = f"{self.base_url}/api/{self.tenant_id}/{self.project_id}/async/operation"
        payload = {
            'operationType': operation_type,
            'operationName': name,
            'priority': priority,
            'parameters': parameters,
            'timeout': timeout,
            'callbacks': {
                'onProgress': 'https://your-app.com/webhooks/progress',
                'onCompletion': 'https://your-app.com/webhooks/completion',
                'onError': 'https://your-app.com/webhooks/error'
            }
        }
        response = requests.post(url, json=payload, headers=self.headers)
        return response.json()

    def get_operation_status(self, operation_id):
        """現在の操作ステータスを取得する"""
        url = f"{self.base_url}/api/{self.tenant_id}/{self.project_id}/async/operation/{operation_id}"
        response = requests.get(url, headers=self.headers)
        return response.json()

    def list_operations(self, status=None, operation_type=None, page=1, page_size=20):
        """フィルタリング付き非同期操作リストを取得する"""
        url = f"{self.base_url}/api/{self.tenant_id}/{self.project_id}/async/operations"
        params = {'page': page, 'pageSize': page_size}

        if status:
            params['status'] = status
        if operation_type:
            params['operationType'] = operation_type

        response = requests.get(url, params=params, headers=self.headers)
        return response.json()

    def cancel_operation(self, operation_id, reason="User cancellation"):
        """実行中の操作をキャンセルする"""
        url = f"{self.base_url}/api/{self.tenant_id}/{self.project_id}/async/operation/{operation_id}"
        payload = {
            'reason': reason,
            'preservePartialResults': True,
            'notifyCallbacks': True
        }
        response = requests.delete(url, json=payload, headers=self.headers)
        return response