File size: 7,448 Bytes
59697b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/**
 * Task Queue System
 * Manages multiple task queues with type-specific processing
 */

export type TaskType = 'workflow' | 'scraper' | 'email' | 'social';
export type TaskStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
export type TaskPriority = 'low' | 'medium' | 'high';

export interface Task {
  id: string;
  type: TaskType;
  status: TaskStatus;
  priority: TaskPriority;
  data: Record<string, unknown>;
  createdAt: Date;
  startedAt?: Date;
  completedAt?: Date;
  error?: string;
  retryCount: number;
  maxRetries: number;
}

export interface QueueStats {
  type: TaskType;
  pending: number;
  running: number;
  completed: number;
  failed: number;
  avgProcessingTime: number;
}

export interface QueueConfig {
  maxConcurrent: number;
  processingInterval: number;
  maxRetries: number;
}

/**
 * In-memory task queue manager
 */
export class TaskQueue {
  private tasks: Map<string, Task> = new Map();
  private queues: Map<TaskType, Task[]> = new Map();
  private running: Map<TaskType, Set<string>> = new Map();
  private config: Map<TaskType, QueueConfig> = new Map();

  constructor() {
    // Initialize queues for each type
    const types: TaskType[] = ['workflow', 'scraper', 'email', 'social'];
    types.forEach(type => {
      this.queues.set(type, []);
      this.running.set(type, new Set());
      
      // Default configs
      this.config.set(type, {
        maxConcurrent: type === 'scraper' ? 2 : 5, // Limit concurrent scrapers
        processingInterval: 1000,
        maxRetries: 3,
      });
    });
  }

  /**
   * Add task to queue
   */
  async addTask(task: Omit<Task, 'id' | 'createdAt' | 'status' | 'retryCount'>): Promise<string> {
    const id = `${task.type}_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
    
    const fullTask: Task = {
      ...task,
      id,
      status: 'pending',
      createdAt: new Date(),
      retryCount: 0,
    };

    this.tasks.set(id, fullTask);
    
    const queue = this.queues.get(task.type);
    if (queue) {
      // Insert based on priority
      const insertIndex = queue.findIndex(t => 
        this.getPriorityValue(t.priority) < this.getPriorityValue(task.priority)
      );
      
      if (insertIndex === -1) {
        queue.push(fullTask);
      } else {
        queue.splice(insertIndex, 0, fullTask);
      }
    }

    console.log(`✅ Task ${id} added to ${task.type} queue`);
    return id;
  }

  /**
   * Get next task to process
   */
  getNextTask(type: TaskType): Task | null {
    const queue = this.queues.get(type);
    const runningSet = this.running.get(type);
    const config = this.config.get(type);

    if (!queue || !runningSet || !config) return null;

    // Check if we can process more tasks
    if (runningSet.size >= config.maxConcurrent) {
      return null;
    }

    // Get first pending task
    const task = queue.find(t => t.status === 'pending');
    if (!task) return null;

    // Mark as running
    task.status = 'running';
    task.startedAt = new Date();
    runningSet.add(task.id);

    return task;
  }

  /**
   * Complete task
   */
  completeTask(taskId: string, error?: string): void {
    const task = this.tasks.get(taskId);
    if (!task) return;

    const runningSet = this.running.get(task.type);
    if (runningSet) {
      runningSet.delete(taskId);
    }

    task.completedAt = new Date();
    
    if (error) {
      task.error = error;
      task.retryCount++;

      // Retry if under max retries
      const config = this.config.get(task.type);
      if (config && task.retryCount < (task.maxRetries || config.maxRetries)) {
        task.status = 'pending';
        console.log(`🔄 Retrying task ${taskId} (attempt ${task.retryCount + 1})`);
      } else {
        task.status = 'failed';
        console.log(`❌ Task ${taskId} failed: ${error}`);
      }
    } else {
      task.status = 'completed';
      console.log(`✅ Task ${taskId} completed`);
      
      // Remove from queue
      const queue = this.queues.get(task.type);
      if (queue) {
        const index = queue.findIndex(t => t.id === taskId);
        if (index !== -1) {
          queue.splice(index, 1);
        }
      }
    }
  }

  /**
   * Cancel task
   */
  cancelTask(taskId: string): boolean {
    const task = this.tasks.get(taskId);
    if (!task || task.status === 'completed' || task.status === 'failed') {
      return false;
    }

    task.status = 'cancelled';
    task.completedAt = new Date();

    const runningSet = this.running.get(task.type);
    if (runningSet) {
      runningSet.delete(taskId);
    }

    // Remove from queue
    const queue = this.queues.get(task.type);
    if (queue) {
      const index = queue.findIndex(t => t.id === taskId);
      if (index !== -1) {
        queue.splice(index, 1);
      }
    }

    console.log(`🛑 Task ${taskId} cancelled`);
    return true;
  }

  /**
   * Get task by ID
   */
  getTask(taskId: string): Task | undefined {
    return this.tasks.get(taskId);
  }

  /**
   * Get all tasks by type
   */
  getTasksByType(type: TaskType): Task[] {
    return Array.from(this.tasks.values()).filter(t => t.type === type);
  }

  /**
   * Get all active tasks
   */
  getActiveTasks(): Task[] {
    return Array.from(this.tasks.values()).filter(
      t => t.status === 'pending' || t.status === 'running'
    );
  }

  /**
   * Get queue statistics
   */
  getStats(type: TaskType): QueueStats {
    const tasks = this.getTasksByType(type);
    
    const pending = tasks.filter(t => t.status === 'pending').length;
    const running = tasks.filter(t => t.status === 'running').length;
    const completed = tasks.filter(t => t.status === 'completed').length;
    const failed = tasks.filter(t => t.status === 'failed').length;

    // Calculate average processing time
    const completedTasks = tasks.filter(t => 
      t.status === 'completed' && t.startedAt && t.completedAt
    );
    const avgProcessingTime = completedTasks.length > 0
      ? completedTasks.reduce((sum, t) => {
          const duration = t.completedAt!.getTime() - t.startedAt!.getTime();
          return sum + duration;
        }, 0) / completedTasks.length
      : 0;

    return {
      type,
      pending,
      running,
      completed,
      failed,
      avgProcessingTime,
    };
  }

  /**
   * Get all statistics
   */
  getAllStats(): QueueStats[] {
    return Array.from(this.queues.keys()).map(type => this.getStats(type));
  }

  /**
   * Update queue configuration
   */
  updateConfig(type: TaskType, config: Partial<QueueConfig>): void {
    const currentConfig = this.config.get(type);
    if (currentConfig) {
      this.config.set(type, { ...currentConfig, ...config });
    }
  }

  /**
   * Clear completed/failed tasks
   */
  clearCompleted(type?: TaskType): number {
    let cleared = 0;
    
    this.tasks.forEach((task, id) => {
      if (type && task.type !== type) return;
      
      if (task.status === 'completed' || task.status === 'failed' || task.status === 'cancelled') {
        this.tasks.delete(id);
        cleared++;
      }
    });

    console.log(`🧹 Cleared ${cleared} completed tasks`);
    return cleared;
  }

  /**
   * Get priority numeric value
   */
  private getPriorityValue(priority: TaskPriority): number {
    const values = { low: 1, medium: 2, high: 3 };
    return values[priority];
  }
}

// Export singleton instance
export const taskQueue = new TaskQueue();