forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplit-batch.processor.ts
More file actions
188 lines (154 loc) · 5.64 KB
/
Copy pathsplit-batch.processor.ts
File metadata and controls
188 lines (154 loc) · 5.64 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
import { Process, Processor } from "@nestjs/bull";
import { Logger } from "@nestjs/common";
import { Job } from "bull";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { BatchJob, BatchJobStatus } from "../entities/batch-job.entity";
import { BatchOperation, BatchOperationStatus } from "../entities/batch-operation.entity";
import { BatchProgressService } from "../batch-progress.service";
import { BatchJobData } from "../batch.service";
interface SplitPayload {
totalAmount: number;
participants: Array<{ userId: string; amount: number; walletAddress?: string }>;
description?: string;
preferredCurrency?: string;
creatorWalletAddress?: string;
}
type ProcessorError = Error & { code?: string };
@Processor("batch_splits")
export class SplitBatchProcessor {
private readonly logger = new Logger(SplitBatchProcessor.name);
constructor(
@InjectRepository(BatchJob)
private batchJobRepository: Repository<BatchJob>,
@InjectRepository(BatchOperation)
private batchOperationRepository: Repository<BatchOperation>,
private batchProgressService: BatchProgressService,
) {}
@Process("process")
async handleSplitBatch(job: Job<BatchJobData>): Promise<void> {
const { batchId, chunkSize, concurrency } = job.data;
this.logger.log(`Starting split batch ${batchId}`);
// Update batch status
await this.batchJobRepository.update(batchId, {
status: BatchJobStatus.PROCESSING,
started_at: new Date(),
});
try {
// Get all pending operations
const operations = await this.batchOperationRepository.find({
where: {
batch_id: batchId,
status: BatchOperationStatus.PENDING,
},
order: { operation_index: "ASC" },
});
if (operations.length === 0) {
this.logger.warn(`No pending operations for batch ${batchId}`);
return;
}
// Process in chunks
for (let i = 0; i < operations.length; i += chunkSize) {
const chunk = operations.slice(i, i + chunkSize);
this.logger.debug(`Processing chunk ${Math.floor(i / chunkSize) + 1} of ${Math.ceil(operations.length / chunkSize)}`);
// Process chunk with concurrency limit
await this.processChunk(chunk, concurrency);
// Update job progress
const progress = Math.round(((i + chunk.length) / operations.length) * 100);
await job.progress(progress);
}
this.logger.log(`Completed split batch ${batchId}`);
} catch (error: any) {
this.logger.error(`Failed to process split batch ${batchId}: ${error.message}`);
// Update batch with error
await this.batchJobRepository.update(batchId, {
status: BatchJobStatus.FAILED,
error_message: error.message,
completed_at: new Date(),
});
throw error;
}
}
/**
* Process a chunk of operations with concurrency control
*/
private async processChunk(
operations: BatchOperation[],
concurrency: number,
): Promise<void> {
const queue = [...operations];
const workerCount = Math.max(1, concurrency || 1);
const workers = Array.from({ length: workerCount }, async () => {
while (queue.length > 0) {
const operation = queue.shift();
if (!operation) {
return;
}
await this.processOperation(operation);
}
});
await Promise.all(workers);
}
/**
* Process a single split operation
*/
private async processOperation(operation: BatchOperation): Promise<void> {
try {
// Mark as started
await this.batchProgressService.markOperationStarted(operation.id);
const payload = operation.payload as SplitPayload;
// Validate payload
this.validatePayload(payload);
// Simulate split creation (replace with actual service call)
const result = await this.createSplit(payload);
// Mark as completed
await this.batchProgressService.markOperationCompleted(operation.id, result);
this.logger.debug(`Completed operation ${operation.id}`);
} catch (error: any) {
this.logger.error(`Failed operation ${operation.id}: ${error.message}`);
await this.batchProgressService.markOperationFailed(
operation.id,
error.message,
error.code || "UNKNOWN_ERROR",
);
}
}
/**
* Validate split payload
*/
private validatePayload(payload: SplitPayload): void {
if (!payload.totalAmount || payload.totalAmount <= 0) {
throw this.createValidationError("Invalid total amount");
}
if (!payload.participants || payload.participants.length === 0) {
throw this.createValidationError("No participants provided");
}
const totalParticipantAmount = payload.participants.reduce(
(sum, p) => sum + (p.amount || 0),
0,
);
if (Math.abs(totalParticipantAmount - payload.totalAmount) > 0.01) {
throw this.createValidationError(
"Participant amounts do not sum to total amount",
);
}
}
/**
* Create a split (placeholder for actual implementation)
*/
private async createSplit(payload: SplitPayload): Promise<Record<string, any>> {
// TODO: Integrate with actual split creation service
// For now, simulate successful creation
return {
splitId: `split_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
totalAmount: payload.totalAmount,
participantCount: payload.participants.length,
createdAt: new Date().toISOString(),
};
}
private createValidationError(message: string): ProcessorError {
const error = new Error(message) as ProcessorError;
error.code = "VALIDATION_ERROR";
return error;
}
}