forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbatch-progress.service.ts
More file actions
217 lines (187 loc) · 6.4 KB
/
Copy pathbatch-progress.service.ts
File metadata and controls
217 lines (187 loc) · 6.4 KB
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
import { Injectable, Logger } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { EventEmitter2 } from "@nestjs/event-emitter";
import { BatchJob, BatchJobStatus } from "./entities/batch-job.entity";
import { BatchOperation, BatchOperationStatus } from "./entities/batch-operation.entity";
import { BatchProgressEventDto } from "./dto/batch-status.dto";
@Injectable()
export class BatchProgressService {
private readonly logger = new Logger(BatchProgressService.name);
constructor(
@InjectRepository(BatchJob)
private batchJobRepository: Repository<BatchJob>,
@InjectRepository(BatchOperation)
private batchOperationRepository: Repository<BatchOperation>,
private eventEmitter: EventEmitter2,
) {}
/**
* Update batch progress after an operation completes
*/
async updateProgress(batchId: string): Promise<void> {
const batch = await this.batchJobRepository.findOne({
where: { id: batchId },
relations: ["operations"],
});
if (!batch) {
this.logger.warn(`Batch ${batchId} not found for progress update`);
return;
}
const operations = batch.operations || [];
const completed = operations.filter(
(op) => op.status === BatchOperationStatus.COMPLETED,
).length;
const failed = operations.filter(
(op) => op.status === BatchOperationStatus.FAILED,
).length;
const processing = operations.filter(
(op) => op.status === BatchOperationStatus.PROCESSING,
).length;
batch.completed_operations = completed;
batch.failed_operations = failed;
batch.progress = Math.round((completed / batch.total_operations) * 100);
// Determine batch status
if (completed + failed === batch.total_operations) {
if (failed === 0) {
batch.status = BatchJobStatus.COMPLETED;
batch.completed_at = new Date();
} else if (completed === 0) {
batch.status = BatchJobStatus.FAILED;
batch.completed_at = new Date();
} else {
batch.status = BatchJobStatus.PARTIAL;
batch.completed_at = new Date();
}
} else if (processing > 0 && batch.status === BatchJobStatus.PENDING) {
batch.status = BatchJobStatus.PROCESSING;
if (!batch.started_at) {
batch.started_at = new Date();
}
}
await this.batchJobRepository.save(batch);
// Emit progress event
this.emitProgressEvent(batch);
}
/**
* Mark an operation as started
*/
async markOperationStarted(operationId: string): Promise<void> {
await this.batchOperationRepository.update(operationId, {
status: BatchOperationStatus.PROCESSING,
started_at: new Date(),
});
}
/**
* Mark an operation as completed
*/
async markOperationCompleted(
operationId: string,
result?: Record<string, any>,
): Promise<void> {
const operation = await this.batchOperationRepository.findOne({
where: { id: operationId },
relations: ["batch"],
});
if (!operation) {
this.logger.warn(`Operation ${operationId} not found`);
return;
}
await this.batchOperationRepository.update(operationId, {
status: BatchOperationStatus.COMPLETED,
result,
completed_at: new Date(),
});
// Update batch progress
await this.updateProgress(operation.batch_id);
}
/**
* Mark an operation as failed
*/
async markOperationFailed(
operationId: string,
errorMessage: string,
errorCode?: string,
): Promise<void> {
const operation = await this.batchOperationRepository.findOne({
where: { id: operationId },
relations: ["batch"],
});
if (!operation) {
this.logger.warn(`Operation ${operationId} not found`);
return;
}
const retryCount = operation.retry_count + 1;
const shouldRetry = retryCount < (operation.batch?.options?.retryAttempts || 5);
const updateData: any = {
status: shouldRetry ? BatchOperationStatus.RETRYING : BatchOperationStatus.FAILED,
error_message: errorMessage,
error_code: errorCode,
retry_count: retryCount,
};
if (!shouldRetry) {
updateData.completed_at = new Date();
}
await this.batchOperationRepository.update(operationId, updateData);
// Update batch progress
await this.updateProgress(operation.batch_id);
}
/**
* Calculate estimated time remaining
*/
calculateETA(batch: BatchJob): number | undefined {
if (!batch.started_at || batch.completed_operations === 0) {
return undefined;
}
const elapsed = Date.now() - batch.started_at.getTime();
const rate = batch.completed_operations / elapsed; // operations per ms
const remaining = batch.total_operations - batch.completed_operations;
const eta = remaining / rate;
return Math.round(eta);
}
/**
* Calculate processing rate (operations per second)
*/
calculateProcessingRate(batch: BatchJob): number | undefined {
if (!batch.started_at || batch.completed_operations === 0) {
return undefined;
}
const elapsed = (Date.now() - batch.started_at.getTime()) / 1000; // seconds
return Math.round((batch.completed_operations / elapsed) * 100) / 100;
}
/**
* Emit progress event
*/
private emitProgressEvent(batch: BatchJob): void {
const event: BatchProgressEventDto = {
batchId: batch.id,
progress: batch.progress,
completedOperations: batch.completed_operations,
failedOperations: batch.failed_operations,
status: batch.status,
message: this.getProgressMessage(batch),
};
this.eventEmitter.emit("batch.progress", event);
this.logger.debug(`Batch ${batch.id} progress: ${batch.progress}%`);
}
/**
* Get human-readable progress message
*/
private getProgressMessage(batch: BatchJob): string {
switch (batch.status) {
case BatchJobStatus.PENDING:
return "Waiting to start";
case BatchJobStatus.PROCESSING:
return `Processing: ${batch.completed_operations}/${batch.total_operations} completed`;
case BatchJobStatus.COMPLETED:
return "All operations completed successfully";
case BatchJobStatus.FAILED:
return "All operations failed";
case BatchJobStatus.PARTIAL:
return `${batch.completed_operations} completed, ${batch.failed_operations} failed`;
case BatchJobStatus.CANCELLED:
return "Batch cancelled";
default:
return "Unknown status";
}
}
}