Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 5x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 5x 6x 6x 5x 1x 1x 5x 5x 5x 5x 5x 5x 11x 11x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 5x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 5x 3x 3x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { pick } from 'lodash-es';
import { Repository } from 'typeorm';
import { DataRefreshment, type Company } from '@amalia/core/models';
import {
CalculationTrigger,
CalculationType,
CustomObjectImportStatus,
RefreshmentErrorLevel,
RefreshmentErrorType,
REFRESHMENTS_ONGOING_STATUSES,
RefreshmentTrigger,
type ScheduleCalculationEvent,
} from '@amalia/core/types';
import { assert, toError } from '@amalia/ext/typescript';
import { AppLogger, InjectAppLogger, withLoggerContext } from '@amalia/kernel/logger/server';
import {
MessageTasks,
MessageType,
QueueService,
ResumeCalculationPayload,
type RefreshmentExecutePayload,
type TaskHandler,
} from '@amalia/kernel/queue/core';
import { configuration } from '../../../configuration';
import { DataSyncService } from '../dataSync.service';
@Injectable()
export class RefreshmentExecuteHandler implements TaskHandler<RefreshmentExecutePayload> {
private readonly logger = new Logger(RefreshmentExecuteHandler.name);
public constructor(
@InjectRepository(DataRefreshment)
private readonly dataRefreshmentRepository: Repository<DataRefreshment>,
private readonly dataSyncService: DataSyncService,
private readonly queueService: QueueService,
@InjectAppLogger(RefreshmentExecuteHandler.name)
private readonly appLogger: AppLogger,
) {}
public async handle(payload: RefreshmentExecutePayload) {
const { refreshmentId, companyId } = payload;
assert(companyId && refreshmentId, 'Payload error, refreshment cannot start');
await withLoggerContext(this.appLogger, { company: { id: companyId }, refreshmentId }, async () => {
await this.refreshData(refreshmentId, companyId);
});
}
/**
* @param refreshmentId
* @param companyId
*/
private async refreshData(refreshmentId: string, companyId: string): Promise<void> {
const dataRefreshment = await this.dataRefreshmentRepository.findOne({
where: {
company: { id: companyId },
id: refreshmentId,
},
relations: ['company', 'connector'],
});
assert(dataRefreshment, `Refreshment ${refreshmentId} not found.`);
const { company } = dataRefreshment;
await withLoggerContext(
this.appLogger,
{
company: pick(company, ['id', 'name']),
connector: pick(dataRefreshment.connector, 'id', 'type', 'alias'),
dataRefreshment: pick(dataRefreshment, 'id', 'object'),
},
async () => {
await this.tryRefresh(refreshmentId, dataRefreshment);
},
);
}
private async tryRefresh(refreshmentId: string, dataRefreshment: DataRefreshment) {
const { timeout: TIMEOUT_IN_MILLISECONDS } = configuration.apps.dataRefreshments;
const COMPUTATION_TIMEOUT = Date.now() + TIMEOUT_IN_MILLISECONDS;
let isTimeoutReached = false;
// This function will be called for each loop in the prune, and update the local "isTimeoutReached" variable
const checkIfRequestTimeoutWasReached = () => {
isTimeoutReached = Date.now() > COMPUTATION_TIMEOUT;
return isTimeoutReached;
};
const { company, connector, runAttempts } = dataRefreshment;
// If the worker doesn't acknowledge the message quickly enough, GCP PubSub can
// send it again for retry. We protect ourselves from starting another process
// by stopping it right now if it's already ongoing.
if (dataRefreshment.status !== CustomObjectImportStatus.PENDING) {
this.logger.warn({
message: `Data import ${refreshmentId} of ${dataRefreshment.object} is already started`,
dataRefreshment: pick(dataRefreshment, 'id', 'status', 'object'),
});
return;
}
const currentAttempt = runAttempts + 1;
// And now we can mark it as started.
await this.dataRefreshmentRepository.update(
{ id: refreshmentId },
{
status: CustomObjectImportStatus.STARTED,
runAttempts: currentAttempt,
},
);
const { options, triggerCalculationId } = dataRefreshment;
const { calculationsOptions, willLaunchCalculation } = options;
try {
const { updated, deleted, offsetForNextPruneIteration, nextPageUrlForNextSyncIteration } =
await this.dataSyncService.syncData(company, dataRefreshment, connector, checkIfRequestTimeoutWasReached);
// Compute once the data which will be updated in the refreshment
const computedData: Pick<DataRefreshment, 'deleted' | 'pruneOffset' | 'resumeAt' | 'updated'> = {
deleted: dataRefreshment.deleted + deleted,
updated,
resumeAt: { offset: updated, nextUrl: nextPageUrlForNextSyncIteration },
pruneOffset: offsetForNextPruneIteration,
};
// We must check if the refreshment was stopped because timeout was reached
// and thus schedule another REFRESHMENT instead of a CALCULATION
if (checkIfRequestTimeoutWasReached()) {
await this.handlePossibleRetryAfterTimeout(dataRefreshment, company, currentAttempt, computedData);
return;
}
// If we're here it means it didn't throw and no timeout happened,
// so we can update the refreshment in db to mark it as done.
await this.dataRefreshmentRepository.update(
{ id: refreshmentId },
{
status: CustomObjectImportStatus.SUCCESS,
...computedData,
},
);
// Since this refreshment went well, and there was no timeout,
// we can now schedule a recalculation for the current period if needed.
if (willLaunchCalculation || triggerCalculationId) {
await this.handleCalculationLaunchAfterRefreshment(dataRefreshment, company, calculationsOptions);
}
} catch (e) {
await this.handleRefreshmentError(e, refreshmentId);
// If it's a nightly batch, start the computation even if refreshment crashed.
// Indeed, if we don't, some companies might never compute, even though "most" of the connectors did
// update successfully.
if (dataRefreshment.trigger === RefreshmentTrigger.SCHEDULED && (willLaunchCalculation || triggerCalculationId)) {
this.logger.warn(`Error while refreshing ${dataRefreshment.object}, will launch calculation anyway.`);
await this.handleCalculationLaunchAfterRefreshment(dataRefreshment, company, calculationsOptions);
}
}
}
/**
* If we launched multiple refreshments in parallel for the same command,
* then there are multiple refreshments that have the same group id. We must check that
* all siblings are terminated before launching the calculation.
*
* @param dataRefreshment
* @param company
* @param calculationsOptions
*/
private async handleCalculationLaunchAfterRefreshment(
dataRefreshment: DataRefreshment,
company: Company,
calculationsOptions?: ScheduleCalculationEvent['options'],
) {
const { id: companyId } = company;
// Let's see how my siblings are doing.
const siblingsRefreshments = await this.dataRefreshmentRepository.findBy({
company: { id: company.id },
group: dataRefreshment.group,
});
if (siblingsRefreshments.some((r) => REFRESHMENTS_ONGOING_STATUSES.includes(r.status))) {
// If there are still some refreshments ongoing, we need to wait.
this.logger.log({
message: 'Some refreshments in the group are ongoing, skipping calculation scheduling.',
siblings: siblingsRefreshments.map((r) => pick(r, 'id', 'status')),
});
} else if (dataRefreshment.triggerCalculationId) {
// Resume the calculation.
this.logger.log('Last refreshment of the group is finished, we can resume the calculation.');
await this.queueService.sendToQueue(
{
type: MessageType.TASK,
taskIdentifier: MessageTasks.RESUME_CALCULATION,
},
{
companyId,
calculationId: dataRefreshment.triggerCalculationId,
} as ResumeCalculationPayload,
);
} else {
assert(
calculationsOptions,
`Refreshment ${dataRefreshment.id} is supposed to start a calculation, but calculationsOptions are missing.`,
);
// If they are all finished, we can start the calculation.
this.logger.log('Last refreshment of the group is finished, we can schedule the calculation.');
await this.queueService.sendToQueue(
{
type: MessageType.TASK,
taskIdentifier: MessageTasks.SCHEDULE_CALCULATION,
},
{
calculationEvent: {
companyId,
query: {
trigger:
dataRefreshment.trigger === RefreshmentTrigger.SCHEDULED
? CalculationTrigger.NIGHTLY_CALCULATION
: CalculationTrigger.DATA_REFRESHMENT,
type: CalculationType.STATEMENT,
},
options: calculationsOptions,
} satisfies ScheduleCalculationEvent,
},
);
}
}
/**
* If the refreshment was "abort" because the timeout was reached, we update the refreshment
* data such "deleted", "updated" and we check if we can schedule another data refreshment.
*
* @param dataRefreshment
* @param company
* @param currentAttempt
* @param computedData
*/
private async handlePossibleRetryAfterTimeout(
dataRefreshment: DataRefreshment,
company: Company,
currentAttempt: number,
computedData: Pick<DataRefreshment, 'deleted' | 'pruneOffset' | 'updated'>,
): Promise<void> {
const { maxAttempts } = configuration.apps.dataRefreshments;
const { id: refreshmentId, object } = dataRefreshment;
const { id: companyId } = company;
const hasRetryRemaining = !!(maxAttempts - currentAttempt);
// First we update the refreshment
await this.dataRefreshmentRepository.update(
{ id: refreshmentId },
{
...(hasRetryRemaining && { status: CustomObjectImportStatus.PENDING }),
...computedData,
},
);
// If no more retry remaining throw an Error and log appropriate things
assert(hasRetryRemaining, `Refreshment timeout, max retry exceeded`);
// Trigger another refreshment because there are remaining retry
await this.queueService.sendToQueue(
{
type: MessageType.TASK,
taskIdentifier: MessageTasks.EXECUTE_REFRESHMENT,
},
{
refreshmentEvent: {
companyId,
refreshmentId,
},
},
);
this.logger.log(`Data import ${refreshmentId} of ${object} was scheduled for another attempt`);
}
/**
* If an error is throw, we should handle the error depending on the type and update
* the refreshment in DB.
*
* @param e
* @param refreshmentId
*/
private async handleRefreshmentError(e: unknown, refreshmentId: string) {
const isRefreshmentError = (e: unknown): e is Error & { errorType: RefreshmentErrorType } =>
typeof e === 'object' && !!e && 'errorType' in e;
const error = toError(e);
const type = isRefreshmentError(e) ? e.errorType : RefreshmentErrorType.OTHER;
// If refreshment was intentionally stopped
if (type === RefreshmentErrorType.STOPPED) {
// Put the status of refreshment to stopped (it was either put as stopped or stopping)
await this.dataRefreshmentRepository.update(
{ id: refreshmentId },
{
status: CustomObjectImportStatus.STOPPED,
error: {
message: error.message,
stack: error.stack?.toString(),
type,
level: RefreshmentErrorLevel.WARNING,
},
},
);
} else {
await this.dataRefreshmentRepository.update(
{ id: refreshmentId },
{
status: CustomObjectImportStatus.ERROR,
error: {
message: error.message,
stack: error.stack?.toString(),
type,
level: RefreshmentErrorLevel.ERROR,
},
},
);
this.logger.error({ message: `Refreshment error - ${error.message}`, error, stack: error.stack });
}
}
}
|