-
Notifications
You must be signed in to change notification settings - Fork 9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[SERVICES-2669] Cron job for triggering analytics indexing #1517
Open
mad2sm0key
wants to merge
3
commits into
SERVICES-2668-rest-endpoints-for-managing-indexing
Choose a base branch
from
SERVICES-2669-cron-job-for-triggering-analytics-indexing
base: SERVICES-2668-rest-endpoints-for-managing-indexing
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+243
−1
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
222 changes: 222 additions & 0 deletions
222
src/modules/analytics-indexer/services/indexer.cron.service.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,222 @@ | ||
import { Inject, Injectable } from '@nestjs/common'; | ||
import { Cron, CronExpression } from '@nestjs/schedule'; | ||
import { WINSTON_MODULE_PROVIDER } from 'nest-winston'; | ||
import { Logger } from 'winston'; | ||
import moment from 'moment'; | ||
import { generateLogMessage } from 'src/utils/generate-log-message'; | ||
import { Lock } from '@multiversx/sdk-nestjs-common'; | ||
import { | ||
IndexerJob, | ||
IndexerSession, | ||
IndexerStatus, | ||
} from '../schemas/indexer.session.schema'; | ||
import { PerformanceProfiler } from '@multiversx/sdk-nestjs-monitoring'; | ||
import { CacheService } from '@multiversx/sdk-nestjs-cache'; | ||
import { IndexerService } from './indexer.service'; | ||
import { IndexerPersistenceService } from './indexer.persistence.service'; | ||
import { IndexerEventTypes } from '../entities/indexer.event.types'; | ||
|
||
const JOB_MAX_ATTEMPTS = 3; | ||
|
||
@Injectable() | ||
export class IndexerCronService { | ||
constructor( | ||
private readonly indexerService: IndexerService, | ||
private readonly indexerPersistence: IndexerPersistenceService, | ||
private readonly cachingService: CacheService, | ||
@Inject(WINSTON_MODULE_PROVIDER) protected readonly logger: Logger, | ||
) {} | ||
|
||
async onModuleInit() { | ||
await this.resetStuckJobsAndSessions(); | ||
} | ||
|
||
@Cron(CronExpression.EVERY_10_SECONDS) | ||
@Lock({ name: 'indexAnalytics' }) | ||
public async indexAnalytics() { | ||
let activeSession: IndexerSession; | ||
|
||
try { | ||
activeSession = await this.indexerPersistence.getActiveSession(); | ||
if (!activeSession) { | ||
return; | ||
} | ||
|
||
const sessionAbortSignal = await this.getSessionAbortSignal( | ||
activeSession, | ||
); | ||
if (sessionAbortSignal) { | ||
return await this.markSessionAborted(activeSession); | ||
} | ||
|
||
if (activeSession.status === IndexerStatus.PENDING) { | ||
activeSession.status = IndexerStatus.IN_PROGRESS; | ||
await this.indexerPersistence.updateSession(activeSession); | ||
} | ||
|
||
await this.processIndexingJobs(activeSession); | ||
} catch (error) { | ||
const logMessage = generateLogMessage( | ||
IndexerCronService.name, | ||
this.indexAnalytics.name, | ||
'', | ||
error, | ||
); | ||
this.logger.error(logMessage); | ||
} | ||
} | ||
|
||
private async processIndexingJobs(session: IndexerSession): Promise<void> { | ||
for (const [index, job] of session.jobs.entries()) { | ||
if ( | ||
job.status !== IndexerStatus.IN_PROGRESS && | ||
job.status !== IndexerStatus.PENDING | ||
) { | ||
continue; | ||
} | ||
|
||
try { | ||
job.status = IndexerStatus.IN_PROGRESS; | ||
|
||
await this.indexerPersistence.updateSession(session); | ||
|
||
session.jobs[index] = await this.runIndexingJob( | ||
job, | ||
session.eventTypes, | ||
); | ||
|
||
await this.indexerPersistence.updateSession(session); | ||
} catch (error) { | ||
this.logger.error( | ||
`Indexing session ${session.name} failed`, | ||
error, | ||
); | ||
await this.markSessionFailed(session); | ||
break; | ||
} | ||
} | ||
|
||
return await this.markSessionCompleted(session); | ||
} | ||
|
||
private async runIndexingJob( | ||
job: IndexerJob, | ||
eventTypes: IndexerEventTypes[], | ||
): Promise<IndexerJob> { | ||
const profiler = new PerformanceProfiler(); | ||
|
||
const startDate = moment | ||
.unix(job.startTimestamp) | ||
.format('YYYY-MM-DD HH:mm:ss'); | ||
const endDate = moment | ||
.unix(job.endTimestamp) | ||
.format('YYYY-MM-DD HH:mm:ss'); | ||
|
||
let errorsCount = 0; | ||
while (job.runAttempts < JOB_MAX_ATTEMPTS) { | ||
try { | ||
errorsCount = await this.indexerService.indexAnalytics( | ||
job.startTimestamp, | ||
job.endTimestamp, | ||
eventTypes, | ||
); | ||
|
||
profiler.stop(); | ||
|
||
this.logger.info( | ||
`Finished indexing analytics data between '${startDate}' and '${endDate}' in ${profiler.duration}ms`, | ||
{ | ||
context: 'IndexerCronService', | ||
}, | ||
); | ||
|
||
job.runAttempts += 1; | ||
job.errorCount = errorsCount; | ||
job.durationMs = profiler.duration; | ||
job.status = IndexerStatus.COMPLETED; | ||
|
||
return job; | ||
} catch (error) { | ||
job.runAttempts += 1; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. same here There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
this.logger.error( | ||
`Failed attempt #${job.runAttempts} while indexing analytics data between '${startDate}' and '${endDate}'`, | ||
error, | ||
); | ||
} | ||
} | ||
|
||
profiler.stop(); | ||
|
||
throw new Error( | ||
`Failed to index analytics data between '${startDate}' and '${endDate}'`, | ||
); | ||
} | ||
|
||
private async getSessionAbortSignal( | ||
session: IndexerSession, | ||
): Promise<boolean> { | ||
const abortSignal = await this.cachingService.get( | ||
`indexer.abortSession.${session.name}`, | ||
); | ||
|
||
if (abortSignal) { | ||
return true; | ||
} | ||
|
||
return false; | ||
} | ||
|
||
private async markSessionAborted(session: IndexerSession): Promise<void> { | ||
session = this.updateSessionAndJobsStatus( | ||
session, | ||
[IndexerStatus.PENDING, IndexerStatus.IN_PROGRESS], | ||
IndexerStatus.ABORTED, | ||
); | ||
|
||
await this.indexerPersistence.updateSession(session); | ||
|
||
await this.cachingService.delete( | ||
`indexer.abortSession.${session.name}`, | ||
); | ||
} | ||
|
||
private async markSessionFailed(session: IndexerSession): Promise<void> { | ||
session = this.updateSessionAndJobsStatus( | ||
session, | ||
[ | ||
IndexerStatus.PENDING, | ||
IndexerStatus.IN_PROGRESS, | ||
IndexerStatus.ABORTED, | ||
], | ||
IndexerStatus.FAILED, | ||
); | ||
|
||
await this.indexerPersistence.updateSession(session); | ||
} | ||
|
||
private async markSessionCompleted(session: IndexerSession): Promise<void> { | ||
session.status = IndexerStatus.COMPLETED; | ||
|
||
await this.indexerPersistence.updateSession(session); | ||
} | ||
|
||
private updateSessionAndJobsStatus( | ||
session: IndexerSession, | ||
affectedStatuses: IndexerStatus[], | ||
newStatus: IndexerStatus, | ||
): IndexerSession { | ||
session.status = newStatus; | ||
|
||
for (const job of session.jobs) { | ||
if (affectedStatuses.includes(job.status)) { | ||
job.status = newStatus; | ||
} | ||
} | ||
|
||
return session; | ||
} | ||
|
||
private async resetStuckJobsAndSessions(): Promise<void> { | ||
// TODO implement reset functionality | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
i would also save the error somewhere to be easier to debug. Or log it here
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
done