-
Notifications
You must be signed in to change notification settings - Fork 0
Implement Event Handler to evaluate trigger statements #7
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
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
4818c3e
feat:implement event handler
bipinparajuli f4b5eaa
Merge branch 'main' of https://github.com/dipesh-rumsan/trigger-datas…
bipinparajuli 2005146
fix:clean up
bipinparajuli 99b00d8
fix:merge conflicy
bipinparajuli b10f937
fix:removed console log
bipinparajuli 2093c7c
fix:remove indicators from log
bipinparajuli a7f387c
fix:fixed merge conflict
bipinparajuli cf0a0ea
feat:added event for gfh
bipinparajuli 45de990
fix:remove logs
bipinparajuli d84213d
feat: update glofas algorithm to evaluate trigger statement
dipesh-rumsan 0394971
feat: update DHM algo to evaluate trigger statement
dipesh-rumsan 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 hidden or 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 hidden or 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
323 changes: 311 additions & 12 deletions
323
apps/triggers/src/sources-data/data-source-events.listener.ts
This file contains hidden or 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 |
|---|---|---|
| @@ -1,26 +1,325 @@ | ||
| import { Injectable, Logger } from '@nestjs/common'; | ||
| import { OnEvent } from '@nestjs/event-emitter'; | ||
| import { DATA_SOURCE_EVENTS } from '@lib/core'; | ||
| import type { DataSourceEventPayload } from '@lib/core'; | ||
| import * as core from '@lib/core'; | ||
| import { DataSource, Prisma } from '@lib/database'; | ||
| import { TriggerStatement } from 'src/trigger/validation/trigger.schema'; | ||
| import { Parser } from 'expr-eval'; | ||
| import { TriggerService } from 'src/trigger/trigger.service'; | ||
|
|
||
| type TriggerType = Prisma.TriggerGetPayload<{ | ||
| include: { | ||
| phase: true; | ||
| }; | ||
| }>; | ||
|
|
||
| @Injectable() | ||
| export class DataSourceEventsListener { | ||
| private readonly logger = new Logger(DataSourceEventsListener.name); | ||
|
|
||
| constructor() {} | ||
| constructor(private readonly triggerService: TriggerService) {} | ||
|
|
||
| @OnEvent(core.DATA_SOURCE_EVENTS.DHM.WATER_LEVEL) | ||
| async handleDhmWaterLevel(event: core.DataSourceEventPayload) { | ||
| const indicators: core.Indicator[] = event.indicators; | ||
|
|
||
| this.logger.log( | ||
| `DHM WATER LEVEL EVENT RECEIVED ${indicators.length} indicators`, | ||
| ); | ||
|
|
||
| if (indicators.length === 0) { | ||
| this.logger.warn(`indicators not found `); | ||
| return; | ||
| } | ||
|
|
||
| const indicator = indicators[0].indicator; | ||
|
|
||
| const triggers = await this.triggerService.findTriggersBySourceAndIndicator( | ||
| DataSource.DHM, | ||
| indicator, | ||
| ); | ||
|
|
||
| if (!triggers.length) { | ||
| this.logger.log( | ||
| `No triggers found for DHM Water Level event for indicator ${indicator}`, | ||
| ); | ||
| return; | ||
| } | ||
|
|
||
| const triggerMap: Record<string, TriggerType[]> = triggers.reduce( | ||
| (acc, trigger) => { | ||
| const statement = trigger.triggerStatement as TriggerStatement; | ||
| const stationId = statement.stationId; | ||
| if (!stationId) { | ||
| this.logger.warn( | ||
| `Station ID not found for trigger ${trigger.uuid} for WATER LEVEL TRIGGER`, | ||
| ); | ||
| return acc; | ||
| } | ||
|
|
||
| if (!acc[stationId]) { | ||
| acc[stationId] = []; | ||
| } | ||
| acc[stationId].push(trigger); | ||
| return acc; | ||
| }, | ||
| {}, | ||
| ); | ||
|
|
||
| for await (const indicator of indicators) { | ||
| const stationId = | ||
| indicator.location.type === 'BASIN' | ||
| ? indicator.location.seriesId | ||
| : undefined; | ||
|
|
||
| const triggers = triggerMap[stationId]; | ||
|
|
||
| if (!triggers) { | ||
| continue; | ||
| } | ||
|
|
||
| await this.processAndEvaluateTriggers(triggers, indicator.value); | ||
| } | ||
| } | ||
|
|
||
| @OnEvent(core.DATA_SOURCE_EVENTS.DHM.RAINFALL) | ||
| async handleDhmRainfall(event: core.DataSourceEventPayload) { | ||
| const indicators: core.Indicator[] = event.indicators; | ||
| this.logger.log( | ||
| `DHM RAIN FALL EVENT RECEIVED ${indicators.length} indicators`, | ||
| ); | ||
|
|
||
| @OnEvent(DATA_SOURCE_EVENTS.DHM.WATER_LEVEL) | ||
| handleDhmWaterLevel(event: DataSourceEventPayload) { | ||
| console.log('LOGGED EVENT'); | ||
| if (indicators.length === 0) { | ||
| this.logger.warn(`indicators not found `); | ||
| return; | ||
| } | ||
|
|
||
| const indicator = indicators[0].indicator; | ||
|
|
||
| const triggers = await this.triggerService.findTriggersBySourceAndIndicator( | ||
| DataSource.DHM, | ||
| indicator, | ||
| ); | ||
|
|
||
| if (!triggers.length) { | ||
| this.logger.log('No triggers found for DHM Rainfall event'); | ||
| return; | ||
| } | ||
|
|
||
| const triggerMap: Record<string, TriggerType[]> = triggers.reduce( | ||
| (acc, trigger) => { | ||
| const statement = trigger.triggerStatement as TriggerStatement; | ||
| const stationId = statement.stationId; | ||
|
|
||
| if (!stationId) { | ||
| this.logger.warn( | ||
| `Station ID not found for trigger ${trigger.uuid} for RAINFALL TRIGGER`, | ||
| ); | ||
| return acc; | ||
| } | ||
|
|
||
| if (!acc[stationId]) { | ||
| acc[stationId] = []; | ||
| } | ||
| acc[stationId].push(trigger); | ||
| return acc; | ||
| }, | ||
| {}, | ||
| ); | ||
|
|
||
| for await (const indicator of indicators) { | ||
| const stationId = | ||
| indicator.location.type === 'BASIN' | ||
| ? indicator.location.seriesId | ||
| : undefined; | ||
|
|
||
| const triggers = triggerMap[stationId]; | ||
|
|
||
| if (!triggers) { | ||
| continue; | ||
| } | ||
|
|
||
| await this.processAndEvaluateTriggers(triggers, indicator.value); | ||
| } | ||
| } | ||
|
|
||
| @OnEvent(DATA_SOURCE_EVENTS.DHM.RAINFALL) | ||
| handleDhmRainfall(event: DataSourceEventPayload) { | ||
| console.log('LOGGED EVENT'); | ||
| @OnEvent(core.DATA_SOURCE_EVENTS.GLOFAS.WATER_LEVEL) | ||
| async handleGlofasWaterLevel(event: core.DataSourceEventPayload) { | ||
| const indicators = event.indicators; | ||
|
|
||
| this.logger.log( | ||
| `GLOFAS WATER LEVEL EVENT RECEIVED ${indicators.length} indicators`, | ||
| ); | ||
|
|
||
| if (indicators.length === 0) { | ||
| this.logger.warn(`indicators not found `); | ||
| return; | ||
| } | ||
|
|
||
| const indicator = indicators[0].indicator; | ||
|
|
||
| const triggers = await this.triggerService.findTriggersBySourceAndIndicator( | ||
| DataSource.GLOFAS, | ||
| indicator, | ||
| ); | ||
|
|
||
| if (!triggers.length) { | ||
| this.logger.log('No triggers found for DHM Rainfall event'); | ||
| return; | ||
| } | ||
|
|
||
| // we will create hash map with key as sourceSubType and values as triggers | ||
| const triggerMap = triggers.reduce((acc, trigger) => { | ||
| const statement = trigger.triggerStatement as TriggerStatement; | ||
| const sourceSubType = statement.sourceSubType; | ||
| if (!acc[sourceSubType]) { | ||
| acc[sourceSubType] = []; | ||
| } | ||
| acc[sourceSubType].push(trigger); | ||
| return acc; | ||
| }, {}); | ||
|
|
||
| for await (const indicator of indicators) { | ||
| const [twoYearsMaxProb, fiveYearsMaxProb, twentyYearsMaxProb] = | ||
| indicator.value.toString().split('/'); | ||
|
|
||
| const twoYearsMaxProbTriggers = triggerMap['two_years_max_prob']; | ||
| const fiveYearsMaxProbTriggers = triggerMap['five_years_max_prob']; | ||
| const twentyYearsMaxProbTriggers = triggerMap['twenty_years_max_prob']; | ||
|
|
||
| await this.processAndEvaluateTriggers( | ||
| twoYearsMaxProbTriggers, | ||
| Number(twoYearsMaxProb.trim()) || 0, | ||
| ); | ||
|
|
||
| await this.processAndEvaluateTriggers( | ||
| fiveYearsMaxProbTriggers, | ||
| Number(fiveYearsMaxProb.trim()) || 0, | ||
| ); | ||
|
|
||
| await this.processAndEvaluateTriggers( | ||
| twentyYearsMaxProbTriggers, | ||
| Number(twentyYearsMaxProb.trim()) || 0, | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| @OnEvent(core.DATA_SOURCE_EVENTS.GFH.WATER_LEVEL) | ||
| async handleGfsWaterLevel(event: core.DataSourceEventPayload) { | ||
| const indicators: core.Indicator[] = event.indicators; | ||
|
|
||
| this.logger.log( | ||
| `GFS WATER LEVEL EVENT RECEIVED ${indicators.length} indicators`, | ||
| ); | ||
|
|
||
| if (indicators.length === 0) { | ||
| this.logger.warn(`indicators not found `); | ||
| return; | ||
| } | ||
| const triggers = await this.triggerService.findTriggersBySourceAndIndicator( | ||
| DataSource.GFH, | ||
| indicators[0].indicator, | ||
| ); | ||
|
|
||
| if (!triggers.length) { | ||
| this.logger.log('No triggers found for DHM Rainfall event'); | ||
| return; | ||
| } | ||
| /** The indicators freshly emitted from transform() */ | ||
|
|
||
| for (const trigger of triggers) { | ||
| const statement = trigger.triggerStatement as TriggerStatement; | ||
| const expression = statement.expression; | ||
|
|
||
| // 2. Compute MEAN of all indicator values | ||
| const meanValue = | ||
| indicators.reduce((sum, ind) => sum + ind.value, 0) / indicators.length; | ||
|
|
||
| const meetsThreshold = this.evaluateConditionExpression( | ||
| { | ||
| expression, | ||
| sourceSubType: statement.sourceSubType, | ||
| }, | ||
| meanValue, | ||
| ); | ||
|
|
||
| if (meetsThreshold) { | ||
| this.logger.log(`Trigger ${trigger.id} MET threshold`); | ||
| // update trigger | ||
| await this.triggerService.activateTrigger(trigger.uuid, '', trigger); | ||
| } else { | ||
| this.logger.log(`Trigger ${trigger.id} NOT met`); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private generateExpression(triggerStatement: TriggerStatement) { | ||
| return `${triggerStatement.sourceSubType} ${triggerStatement.operator} ${triggerStatement.value}`; | ||
| } | ||
|
|
||
| private evaluateConditionExpression( | ||
| triggerStatement: { expression: string; sourceSubType: string }, | ||
| indicatorValue: number, | ||
| ): boolean { | ||
| try { | ||
| const parser = new Parser({ | ||
| operators: { | ||
| logical: true, | ||
| comparison: true, | ||
| }, | ||
| }); | ||
|
|
||
| const variableName = triggerStatement.sourceSubType; | ||
|
|
||
| const expression = parser.parse(triggerStatement.expression); | ||
|
|
||
| const exprResult = expression.evaluate({ | ||
| [variableName]: indicatorValue, | ||
| }); | ||
|
|
||
| return Boolean(exprResult); | ||
| } catch (error) { | ||
| this.logger.error( | ||
| `Failed to evaluate expression: ${triggerStatement.expression}`, | ||
| error, | ||
| ); | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| private async processAndEvaluateTriggers( | ||
| triggers: TriggerType[] = [], | ||
| value: number, | ||
| ) { | ||
| const triggerUuids = []; | ||
|
|
||
| for (const trigger of triggers) { | ||
| const statement = trigger.triggerStatement as TriggerStatement; | ||
| const expression = this.generateExpression(statement); | ||
|
|
||
| const meetsThreshold = this.evaluateConditionExpression( | ||
| { | ||
| expression, | ||
| sourceSubType: statement.sourceSubType, | ||
| }, | ||
| value, | ||
| ); | ||
|
|
||
| if (meetsThreshold) { | ||
| this.logger.log(`Trigger ${trigger.uuid} MET threshold`); | ||
| triggerUuids.push(trigger.uuid); | ||
| } | ||
| } | ||
|
|
||
| if (triggerUuids.length > 0) { | ||
| this.logger.log( | ||
| `Activated ${triggerUuids.length} triggers for GLOFAS Subtype ${(triggers[0].triggerStatement as TriggerStatement).sourceSubType} | ||
| with value ${value} and triggers ${triggerUuids.join(', ')}`, | ||
| ); | ||
| await this.activateTriggers(triggerUuids); | ||
| } | ||
| } | ||
|
|
||
| @OnEvent(DATA_SOURCE_EVENTS.GLOFAS.WATER_LEVEL) | ||
| handleGlofasWaterLevel(event: DataSourceEventPayload) { | ||
| console.log('LOGGED EVENT'); | ||
| private async activateTriggers(triggerUuids: string[]) { | ||
| await this.triggerService.activeAutomatedTriggers(triggerUuids); | ||
| } | ||
| } |
This file contains hidden or 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 hidden or 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
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.